Showing preview only (543K chars total). Download the full file or copy to clipboard to get everything.
Repository: itu-algorithms/itu.algs4
Branch: master
Commit: cb08048fa718
Files: 133
Total size: 507.2 KB
Directory structure:
gitextract_mlb3nvxv/
├── .github/
│ └── workflows/
│ ├── check.yml
│ └── python_publish.yml
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── create_html_doc.sh
├── docs/
│ ├── conf.py
│ ├── index.rst
│ ├── requirements.txt
│ └── source/
│ ├── itu.algs4.errors.rst
│ ├── itu.algs4.fundamentals.rst
│ ├── itu.algs4.graphs.rst
│ ├── itu.algs4.rst
│ ├── itu.algs4.searching.rst
│ ├── itu.algs4.sorting.rst
│ ├── itu.algs4.stdlib.rst
│ └── itu.algs4.strings.rst
├── examples/
│ ├── bst.py
│ ├── hello_world.py
│ ├── queue.py
│ ├── sort-numbers.py
│ └── stack.py
├── itu/
│ ├── __init__.py
│ └── algs4/
│ ├── __init__.py
│ ├── errors/
│ │ ├── __init__.py
│ │ └── errors.py
│ ├── fundamentals/
│ │ ├── __init__.py
│ │ ├── bag.py
│ │ ├── binary_search.py
│ │ ├── evaluate.py
│ │ ├── java_helper.py
│ │ ├── queue.py
│ │ ├── stack.py
│ │ ├── three_sum.py
│ │ ├── three_sum_fast.py
│ │ ├── two_sum_fast.py
│ │ └── uf.py
│ ├── graphs/
│ │ ├── Arbitrage.py
│ │ ├── CPM.py
│ │ ├── __init__.py
│ │ ├── acyclic_lp.py
│ │ ├── acyclic_sp.py
│ │ ├── bellman_ford_sp.py
│ │ ├── bipartite.py
│ │ ├── breadth_first_paths.py
│ │ ├── cc.py
│ │ ├── cycle.py
│ │ ├── degrees_of_separation.py
│ │ ├── depth_first_order.py
│ │ ├── depth_first_paths.py
│ │ ├── depth_first_search.py
│ │ ├── digraph.py
│ │ ├── dijkstra_all_pairs_sp.py
│ │ ├── dijkstra_sp.py
│ │ ├── dijkstra_undirected_sp.py
│ │ ├── directed_cycle.py
│ │ ├── directed_dfs.py
│ │ ├── directed_edge.py
│ │ ├── edge.py
│ │ ├── edge_weighted_digraph.py
│ │ ├── edge_weighted_directed_cycle.py
│ │ ├── edge_weighted_directed_cycle_anton.py
│ │ ├── edge_weighted_graph.py
│ │ ├── graph.py
│ │ ├── kosaraju_sharir_scc.py
│ │ ├── kruskal_mst.py
│ │ ├── lazy_prim_mst.py
│ │ ├── prim_mst.py
│ │ ├── symbol_digraph.py
│ │ ├── symbol_graph.py
│ │ ├── topological.py
│ │ └── transitive_closure.py
│ ├── searching/
│ │ ├── __init__.py
│ │ ├── binary_search_st.py
│ │ ├── bst.py
│ │ ├── file_index.py
│ │ ├── frequency_counter.py
│ │ ├── linear_probing_hst.py
│ │ ├── lookup_csv.py
│ │ ├── lookup_index.py
│ │ ├── red_black_bst.py
│ │ ├── seperate_chaining_hst.py
│ │ ├── sequential_search_st.py
│ │ ├── set.py
│ │ ├── sparse_vector.py
│ │ └── st.py
│ ├── sorting/
│ │ ├── __init__.py
│ │ ├── datafiles/
│ │ │ ├── tiny.txt
│ │ │ └── words3.txt
│ │ ├── heap.py
│ │ ├── index_min_pq.py
│ │ ├── insertion_sort.py
│ │ ├── max_pq.py
│ │ ├── merge.py
│ │ ├── merge_bu.py
│ │ ├── min_pq.py
│ │ ├── quick3way.py
│ │ ├── quicksort.py
│ │ ├── selection.py
│ │ └── shellsort.py
│ ├── stdlib/
│ │ ├── __init__.py
│ │ ├── binary_out.py
│ │ ├── binary_stdin.py
│ │ ├── binary_stdout.py
│ │ ├── color.py
│ │ ├── instream.py
│ │ ├── outstream.py
│ │ ├── picture.py
│ │ ├── stdarray.py
│ │ ├── stdaudio.py
│ │ ├── stddraw.py
│ │ ├── stdio.py
│ │ ├── stdrandom.py
│ │ └── stdstats.py
│ └── strings/
│ ├── __init__.py
│ ├── boyer_moore.py
│ ├── huffman_compression.py
│ ├── kmp.py
│ ├── lsd.py
│ ├── lzw.py
│ ├── msd.py
│ ├── nfa.py
│ ├── quick3string.py
│ ├── rabin_karp.py
│ ├── trie_st.py
│ └── tst.py
├── setup.cfg
├── setup.py
└── tests/
├── test_bst.py
├── test_red_black_bst.py
├── test_stack.py
└── test_symbol_tables.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/check.yml
================================================
name: check
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
strategy:
max-parallel: 4
matrix:
python-version: ["3.10", "3.12"]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install
run: |
pip install --upgrade -e .[dev]
- name: Test
run: |
pytest --cov-report term-missing --cov itu.algs4
- name: Lint
run: |
flake8 examples tests itu
isort -c --diff examples tests itu
- name: Typecheck
run: |
mypy
continue-on-error: true
- name: Documentation
run: |
pip install sphinx
cd docs
mkdir _target && mkdir _static
sphinx-build . _target/
================================================
FILE: .github/workflows/python_publish.yml
================================================
name: Upload Python Package to PyPi
on:
push:
tags:
- "v*" # Push events matching v*, i.e. v1.0, v20.15.10
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
- name: Build and publish
env:
TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
run: |
python setup.py sdist bdist_wheel
twine upload dist/*
================================================
FILE: .gitignore
================================================
*.pyc
.vs/
algs4-data/
.mypy_cache
.pytest_cache
.ruff_cache
itu.algs4.egg-info
__pycache__
================================================
FILE: CONTRIBUTING.md
================================================
# Development
## Testing
Before you can run tests, you should clone the repository, and install the
package in "editable" mode, including its development dependencies:
```bash
pip install --upgrade -e '.[dev]'
```
Run all tests as follows:
```bash
pytest
```
To additionally display code coverage statistics, use this:
```bash
pytest --cov
```
To run individual tests, you can also do this:
```
python3 -m unittest tests/test_bst.py
pytest tests/test_stack.py
```
## Linter
Run `flake8` to lint all code. Run `black .` to automatically fix some linting error.
Moreover, run
```
isort -y
```
to sort import statements.
We enforce linting on [examples/](examples), [tests/](tests), and [itu/](itu).
## Types
Weak type checking is currently enforced only on [examples/](examples) and [tests/](tests). To run the type checker, try:
```
mypy
```
Ideally, we want every module to strictly type check. For example, the binary search trees strictly type check:
```
mypy --strict itu/algs4/searching/bst.py itu/algs4/searching/red_black_bst.py itu/algs4/fundamentals/queue.py
```
## Examples
Client code should be migrated to [examples/](examples).
## Uploading to PyPi
Create package and upload it:
```bash
python3 setup.py sdist bdist_wheel
python3 -m twine upload dist/*
```
## Useful Resources
- the book https://algs4.cs.princeton.edu/home/
- a python version of a similar book https://introcs.cs.princeton.edu/python/home/
- all java code -- good list, includes what needs to be done https://algs4.cs.princeton.edu/code/ https://github.com/kevin-wayne/algs4
## Coding style
https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions
- we have subdirectories for the code, one for each chapter
- if java relies on having different implementations depending on the type:
Use somehting like
```
class DirectedDFS:
def __init__(self, G, *s):
```
like in `graphs/directed_dfs.py`
Otherwise we use static factory methods where the name indicates the expected type.
If appropriate we use `isinstance()` and its variants, for example to distinguish undirected and directed graphs.
- things like 'node' are inside classes, no leading underscore
- file names, variables, methods are file_name (and not CamelCase, adjustting from algs4), only classes are CamelCase (PascalCase)
- 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
- java main becomes `__main__` stuff; follow what is there; adjust the initial comment
- don't replicate imports unless
- lower case letter with underscore
- like in the book
- private variables become _variable_name
- if java has `toString()`, then we have `__repr__()`
- keep the comments from the java code
- if in doubt, we go with the book, not the code on the book web site (keep it simple)
- docstring without formatting
## ideas
- should we include generators (additionally to iterators) everywhere?
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
# Algs4 library for Python 3
`itu.algs4` is a Python 3 port of the Java code in [Algorithms, 4th Edition](https://algs4.cs.princeton.edu/home/).
[](https://github.com/itu-algorithms/itu.algs4/actions)
[](https://itualgs4.readthedocs.io/en/latest/?badge=latest)
## Target audience
`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.
It 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.
## Installation
This 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).
Some 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.
### With pip
If you have previously installed this package under its old name, we recommend you remove it with
```bash
pip uninstall algs4 algs4_python
```
Then you can install `itu.algs4` simply with
```bash
pip install itu.algs4
```
If you have already installed `itu.algs4` and want to upgrade to a new version, run:
```bash
pip install itu.algs4 --upgrade
```
To test that you have installed the library correctly, run this command:
```bash
python -c 'from itu.algs4.stdlib import stdio; stdio.write("Hello World!")'
```
It should greet you. If an error message appears instead, the library is not installed correctly.
### Alternative: With pip and git
If git is available, the following command will install the library in your Python environment:
```bash
pip install git+https://github.com/itu-algorithms/itu.algs4
```
### Alternative: With pip and zip
To install this library without git:
1. Download and unzip the repository.
2. Open a command prompt or terminal and navigate to the downloaded folder. There should be the file `setup.py`.
3. 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 .`
### Alternative: Step-by-step guide for Windows
To install the Python package `itu.algs4`:
- Download the repository by pressing the green "Clone or download" button, and pressing "Download ZIP".
- Extract the content of the zip to your Desktop (you can delete the folder after installing the package).
- Open the "Command Prompt" by pressing "Windows + R", type "cmd" in the window that appears, and press "OK".
- If you saved the folder on the Desktop you should be able to navigate to the folder by typing "cd Desktop\itu.algs4-master".
```
C:\Users\user>cd Desktop\itu.algs4-master
```
- When in the correct folder, type `pip install .` to install the package.
```
C:\Users\user\Desktop\itu.algs4-master>pip install .
```
- After this, the package should be installed correctly and you can delete the folder from your Desktop.
## Package structure
The Python package `itu.algs4` has a hierarchical structure with seven sub-packages:
- [itu.algs4.fundamentals](itu/algs4/fundamentals)
- [itu.algs4.sorting](itu/algs4/sorting)
- [itu.algs4.searching](itu/algs4/searching)
- [itu.algs4.graphs](itu/algs4/graphs)
- [itu.algs4.strings](itu/algs4/strings)
- [itu.algs4.stdlib](itu/algs4/stdlib)
- [itu.algs4.errors](itu/algs4/errors)
While 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.
The 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.
All 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.
## Examples
The directory [examples/](examples) contains examples, some of which are
described here.
### Hello World
A simple program, stored as a file [hello_world.py](examples/hello_world.py), looks like this:
```python
from itu.algs4.stdlib import stdio
stdio.write("Hello World!\n")
```
It can be run with the command `python hello_world.py`.
### Sort numbers
A slightly more interesting example is
[sort-numbers.py](examples/sort-numbers.py):
```python
from itu.algs4.sorting import merge
from itu.algs4.stdlib import stdio
"""
Reads a list of integers from standard input.
Then prints it in sorted order.
"""
L = stdio.readAllInts()
merge.sort(L)
if len(L) > 0:
stdio.write(L[0])
for i in range(1, len(L)):
stdio.write(" ")
stdio.write(L[i])
stdio.writeln()
```
This code uses the convenient function `stdio.readAllInts()` to read the
integers (separated by whitespaces) from the standard input and put them in the
array `L`. It then sorts the elements of the array. Finally, it outputs the
sorted list -- the code to do so is somewhat less elegant to get the whitespace
exactly right. (Of course, advanced Python users know more concise ways to
produce the same output: `print(" ".join(map(str, L)))`)
### Import classes
You can import classes, such as the class EdgeWeightedDigraph, with
```python
from itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph
```
## Documentation
The documentation can be found [here](https://itualgs4.readthedocs.io/en/latest/).
You 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.
For example `help(itu.algs4)` yields the following:
```
Help on package itu.algs4 in itu:
NAME
itu.algs4
PACKAGE CONTENTS
errors (package)
fundamentals (package)
graphs (package)
searching (package)
sorting (package)
stdlib (package)
strings (package)
FILE
(built-in)
```
## Development
`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.
## Contributors
- Andreas Holck Høeg-Petersen
- Anton Mølbjerg Eskildsen
- Frederik Haagensen
- Holger Dell
- Martino Secchi
- Morten Keller Grøftehauge
- Morten Tychsen Clausen
- Nina Mesing Stausholm Nielsen
- Otto Stadel Clausen
- Riko Jacob
- Thore Husfeldt
- Viktor Shamal Andersen
## License
This project is licensed under the GPLv3 License - see the [LICENSE](LICENSE) file for details
## Links to other projects
- [algs4](https://github.com/kevin-wayne/algs4/) is the original Java implementation by Sedgewick and Wayne.
- 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.
- [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.
- [Scala-Algorithms](https://github.com/garyaiki/Scala-Algorithms) is a Scala port of `algs4`.
- [Algs4Net](https://github.com/nguyenqthai/Algs4Net) is a .NET port of `algs4`.
================================================
FILE: create_html_doc.sh
================================================
DIR=~/WorkSpace/bads-code/AlgorithmsInPython/algs4/
DEST=/home/rikj/WorkSpace/riko/html_templ_tum/itu_dest/AlgorithmsInPython
DIR=algs4
DEST=DOC
mkdir DOC
FILES=`cd $DIR; find . -type d -or -name \*.py`
cd $DEST
for f in $FILES
do
p=${f#./}
b=${p%.py}
if [ ! $b == ${b%datafiles} ]
then
continue
fi
if [ ! $b == ${b#test} ]
then
continue
fi
arg=algs4.`echo ${b} | tr / .`
res=`pydoc3 -w $arg | grep -v '^wrote'`
if [ ! -z "$res" ]
then
echo $arg $res
fi
# pydoc3 -w algs4.`echo ${b} | tr / .` > /dev/null
done
cd ../..
#rsync -va itu_dest/ ssh.itu.dk:public_html/
================================================
FILE: docs/conf.py
================================================
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath("../"))
# -- Project information -----------------------------------------------------
project = "itu.algs4"
copyright = "2020, ITU Algorithms Group"
author = "ITU Algorithms Group"
master_doc = "index"
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ["sphinx.ext.autodoc"]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "alabaster"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
================================================
FILE: docs/index.rst
================================================
.. itu.algs4 documentation master file, created by
sphinx-quickstart on Mon Jul 6 13:50:43 2020.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to itu.algs4's documentation!
=====================================
.. toctree::
:maxdepth: 2
:caption: Contents:
source/itu.algs4.fundamentals.rst
source/itu.algs4.graphs.rst
source/itu.algs4.searching.rst
source/itu.algs4.sorting.rst
source/itu.algs4.stdlib.rst
source/itu.algs4.strings.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
================================================
FILE: docs/requirements.txt
================================================
pygame
typing_extensions
color
================================================
FILE: docs/source/itu.algs4.errors.rst
================================================
itu.algs4.errors package
========================
Submodules
----------
itu.algs4.errors.errors module
------------------------------
.. automodule:: itu.algs4.errors.errors
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: itu.algs4.errors
:members:
:undoc-members:
:show-inheritance:
================================================
FILE: docs/source/itu.algs4.fundamentals.rst
================================================
itu.algs4.fundamentals package
==============================
Submodules
----------
itu.algs4.fundamentals.bag module
---------------------------------
.. automodule:: itu.algs4.fundamentals.bag
:members:
:undoc-members:
:show-inheritance:
itu.algs4.fundamentals.binary\_search module
--------------------------------------------
.. automodule:: itu.algs4.fundamentals.binary_search
:members:
:undoc-members:
:show-inheritance:
itu.algs4.fundamentals.evaluate module
--------------------------------------
.. automodule:: itu.algs4.fundamentals.evaluate
:members:
:undoc-members:
:show-inheritance:
itu.algs4.fundamentals.java\_helper module
------------------------------------------
.. automodule:: itu.algs4.fundamentals.java_helper
:members:
:undoc-members:
:show-inheritance:
itu.algs4.fundamentals.queue module
-----------------------------------
.. automodule:: itu.algs4.fundamentals.queue
:members:
:undoc-members:
:show-inheritance:
itu.algs4.fundamentals.stack module
-----------------------------------
.. automodule:: itu.algs4.fundamentals.stack
:members:
:undoc-members:
:show-inheritance:
itu.algs4.fundamentals.three\_sum module
----------------------------------------
.. automodule:: itu.algs4.fundamentals.three_sum
:members:
:undoc-members:
:show-inheritance:
itu.algs4.fundamentals.three\_sum\_fast module
----------------------------------------------
.. automodule:: itu.algs4.fundamentals.three_sum_fast
:members:
:undoc-members:
:show-inheritance:
itu.algs4.fundamentals.two\_sum\_fast module
--------------------------------------------
.. automodule:: itu.algs4.fundamentals.two_sum_fast
:members:
:undoc-members:
:show-inheritance:
itu.algs4.fundamentals.uf module
--------------------------------
.. automodule:: itu.algs4.fundamentals.uf
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: itu.algs4.fundamentals
:members:
:undoc-members:
:show-inheritance:
================================================
FILE: docs/source/itu.algs4.graphs.rst
================================================
itu.algs4.graphs package
========================
Submodules
----------
itu.algs4.graphs.Arbitrage module
---------------------------------
.. automodule:: itu.algs4.graphs.Arbitrage
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.CPM module
---------------------------
.. automodule:: itu.algs4.graphs.CPM
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.acyclic\_lp module
-----------------------------------
.. automodule:: itu.algs4.graphs.acyclic_lp
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.acyclic\_sp module
-----------------------------------
.. automodule:: itu.algs4.graphs.acyclic_sp
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.bellman\_ford\_sp module
-----------------------------------------
.. automodule:: itu.algs4.graphs.bellman_ford_sp
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.bipartite module
---------------------------------
.. automodule:: itu.algs4.graphs.bipartite
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.breadth\_first\_paths module
---------------------------------------------
.. automodule:: itu.algs4.graphs.breadth_first_paths
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.cc module
--------------------------
.. automodule:: itu.algs4.graphs.cc
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.cycle module
-----------------------------
.. automodule:: itu.algs4.graphs.cycle
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.degrees\_of\_separation module
-----------------------------------------------
.. automodule:: itu.algs4.graphs.degrees_of_separation
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.depth\_first\_order module
-------------------------------------------
.. automodule:: itu.algs4.graphs.depth_first_order
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.depth\_first\_paths module
-------------------------------------------
.. automodule:: itu.algs4.graphs.depth_first_paths
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.depth\_first\_search module
--------------------------------------------
.. automodule:: itu.algs4.graphs.depth_first_search
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.digraph module
-------------------------------
.. automodule:: itu.algs4.graphs.digraph
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.dijkstra\_all\_pairs\_sp module
------------------------------------------------
.. automodule:: itu.algs4.graphs.dijkstra_all_pairs_sp
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.dijkstra\_sp module
------------------------------------
.. automodule:: itu.algs4.graphs.dijkstra_sp
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.dijkstra\_undirected\_sp module
------------------------------------------------
.. automodule:: itu.algs4.graphs.dijkstra_undirected_sp
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.directed\_cycle module
---------------------------------------
.. automodule:: itu.algs4.graphs.directed_cycle
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.directed\_dfs module
-------------------------------------
.. automodule:: itu.algs4.graphs.directed_dfs
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.directed\_edge module
--------------------------------------
.. automodule:: itu.algs4.graphs.directed_edge
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.edge module
----------------------------
.. automodule:: itu.algs4.graphs.edge
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.edge\_weighted\_digraph module
-----------------------------------------------
.. automodule:: itu.algs4.graphs.edge_weighted_digraph
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.edge\_weighted\_directed\_cycle module
-------------------------------------------------------
.. automodule:: itu.algs4.graphs.edge_weighted_directed_cycle
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.edge\_weighted\_directed\_cycle\_anton module
--------------------------------------------------------------
.. automodule:: itu.algs4.graphs.edge_weighted_directed_cycle_anton
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.edge\_weighted\_graph module
---------------------------------------------
.. automodule:: itu.algs4.graphs.edge_weighted_graph
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.graph module
-----------------------------
.. automodule:: itu.algs4.graphs.graph
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.kosaraju\_sharir\_scc module
---------------------------------------------
.. automodule:: itu.algs4.graphs.kosaraju_sharir_scc
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.kruskal\_mst module
------------------------------------
.. automodule:: itu.algs4.graphs.kruskal_mst
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.lazy\_prim\_mst module
---------------------------------------
.. automodule:: itu.algs4.graphs.lazy_prim_mst
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.prim\_mst module
---------------------------------
.. automodule:: itu.algs4.graphs.prim_mst
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.symbol\_digraph module
---------------------------------------
.. automodule:: itu.algs4.graphs.symbol_digraph
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.symbol\_graph module
-------------------------------------
.. automodule:: itu.algs4.graphs.symbol_graph
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.topological module
-----------------------------------
.. automodule:: itu.algs4.graphs.topological
:members:
:undoc-members:
:show-inheritance:
itu.algs4.graphs.transitive\_closure module
-------------------------------------------
.. automodule:: itu.algs4.graphs.transitive_closure
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: itu.algs4.graphs
:members:
:undoc-members:
:show-inheritance:
================================================
FILE: docs/source/itu.algs4.rst
================================================
itu.algs4 package
=================
Subpackages
-----------
.. toctree::
:maxdepth: 4
itu.algs4.errors
itu.algs4.fundamentals
itu.algs4.graphs
itu.algs4.searching
itu.algs4.sorting
itu.algs4.stdlib
itu.algs4.strings
Module contents
---------------
.. automodule:: itu.algs4
:members:
:undoc-members:
:show-inheritance:
================================================
FILE: docs/source/itu.algs4.searching.rst
================================================
itu.algs4.searching package
===========================
Submodules
----------
itu.algs4.searching.binary\_search\_st module
---------------------------------------------
.. automodule:: itu.algs4.searching.binary_search_st
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.bst module
------------------------------
.. automodule:: itu.algs4.searching.bst
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.file\_index module
--------------------------------------
.. automodule:: itu.algs4.searching.file_index
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.frequency\_counter module
---------------------------------------------
.. automodule:: itu.algs4.searching.frequency_counter
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.linear\_probing\_hst module
-----------------------------------------------
.. automodule:: itu.algs4.searching.linear_probing_hst
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.lookup\_csv module
--------------------------------------
.. automodule:: itu.algs4.searching.lookup_csv
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.lookup\_index module
----------------------------------------
.. automodule:: itu.algs4.searching.lookup_index
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.red\_black\_bst module
------------------------------------------
.. automodule:: itu.algs4.searching.red_black_bst
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.seperate\_chaining\_hst module
--------------------------------------------------
.. automodule:: itu.algs4.searching.seperate_chaining_hst
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.sequential\_search\_st module
-------------------------------------------------
.. automodule:: itu.algs4.searching.sequential_search_st
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.set module
------------------------------
.. automodule:: itu.algs4.searching.set
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.sparse\_vector module
-----------------------------------------
.. automodule:: itu.algs4.searching.sparse_vector
:members:
:undoc-members:
:show-inheritance:
itu.algs4.searching.st module
-----------------------------
.. automodule:: itu.algs4.searching.st
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: itu.algs4.searching
:members:
:undoc-members:
:show-inheritance:
================================================
FILE: docs/source/itu.algs4.sorting.rst
================================================
itu.algs4.sorting package
=========================
Submodules
----------
itu.algs4.sorting.heap module
-----------------------------
.. automodule:: itu.algs4.sorting.heap
:members:
:undoc-members:
:show-inheritance:
itu.algs4.sorting.index\_min\_pq module
---------------------------------------
.. automodule:: itu.algs4.sorting.index_min_pq
:members:
:undoc-members:
:show-inheritance:
itu.algs4.sorting.insertion\_sort module
----------------------------------------
.. automodule:: itu.algs4.sorting.insertion_sort
:members:
:undoc-members:
:show-inheritance:
itu.algs4.sorting.max\_pq module
--------------------------------
.. automodule:: itu.algs4.sorting.max_pq
:members:
:undoc-members:
:show-inheritance:
itu.algs4.sorting.merge module
------------------------------
.. automodule:: itu.algs4.sorting.merge
:members:
:undoc-members:
:show-inheritance:
itu.algs4.sorting.merge\_bu module
----------------------------------
.. automodule:: itu.algs4.sorting.merge_bu
:members:
:undoc-members:
:show-inheritance:
itu.algs4.sorting.min\_pq module
--------------------------------
.. automodule:: itu.algs4.sorting.min_pq
:members:
:undoc-members:
:show-inheritance:
itu.algs4.sorting.quick3way module
----------------------------------
.. automodule:: itu.algs4.sorting.quick3way
:members:
:undoc-members:
:show-inheritance:
itu.algs4.sorting.quicksort module
----------------------------------
.. automodule:: itu.algs4.sorting.quicksort
:members:
:undoc-members:
:show-inheritance:
itu.algs4.sorting.selection module
----------------------------------
.. automodule:: itu.algs4.sorting.selection
:members:
:undoc-members:
:show-inheritance:
itu.algs4.sorting.shellsort module
----------------------------------
.. automodule:: itu.algs4.sorting.shellsort
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: itu.algs4.sorting
:members:
:undoc-members:
:show-inheritance:
================================================
FILE: docs/source/itu.algs4.stdlib.rst
================================================
itu.algs4.stdlib package
========================
Submodules
----------
itu.algs4.stdlib.binary\_out module
-----------------------------------
.. automodule:: itu.algs4.stdlib.binary_out
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.binary\_stdin module
-------------------------------------
.. automodule:: itu.algs4.stdlib.binary_stdin
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.binary\_stdout module
--------------------------------------
.. automodule:: itu.algs4.stdlib.binary_stdout
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.color module
-----------------------------
.. automodule:: itu.algs4.stdlib.color
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.instream module
--------------------------------
.. automodule:: itu.algs4.stdlib.instream
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.outstream module
---------------------------------
.. automodule:: itu.algs4.stdlib.outstream
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.picture module
-------------------------------
.. automodule:: itu.algs4.stdlib.picture
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.stdarray module
--------------------------------
.. automodule:: itu.algs4.stdlib.stdarray
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.stdaudio module
--------------------------------
.. automodule:: itu.algs4.stdlib.stdaudio
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.stddraw module
-------------------------------
.. automodule:: itu.algs4.stdlib.stddraw
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.stdio module
-----------------------------
.. automodule:: itu.algs4.stdlib.stdio
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.stdrandom module
---------------------------------
.. automodule:: itu.algs4.stdlib.stdrandom
:members:
:undoc-members:
:show-inheritance:
itu.algs4.stdlib.stdstats module
--------------------------------
.. automodule:: itu.algs4.stdlib.stdstats
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: itu.algs4.stdlib
:members:
:undoc-members:
:show-inheritance:
================================================
FILE: docs/source/itu.algs4.strings.rst
================================================
itu.algs4.strings package
=========================
Submodules
----------
itu.algs4.strings.boyer\_moore module
-------------------------------------
.. automodule:: itu.algs4.strings.boyer_moore
:members:
:undoc-members:
:show-inheritance:
itu.algs4.strings.huffman\_compression module
---------------------------------------------
.. automodule:: itu.algs4.strings.huffman_compression
:members:
:undoc-members:
:show-inheritance:
itu.algs4.strings.kmp module
----------------------------
.. automodule:: itu.algs4.strings.kmp
:members:
:undoc-members:
:show-inheritance:
itu.algs4.strings.lsd module
----------------------------
.. automodule:: itu.algs4.strings.lsd
:members:
:undoc-members:
:show-inheritance:
itu.algs4.strings.lzw module
----------------------------
.. automodule:: itu.algs4.strings.lzw
:members:
:undoc-members:
:show-inheritance:
itu.algs4.strings.msd module
----------------------------
.. automodule:: itu.algs4.strings.msd
:members:
:undoc-members:
:show-inheritance:
itu.algs4.strings.nfa module
----------------------------
.. automodule:: itu.algs4.strings.nfa
:members:
:undoc-members:
:show-inheritance:
itu.algs4.strings.quick3string module
-------------------------------------
.. automodule:: itu.algs4.strings.quick3string
:members:
:undoc-members:
:show-inheritance:
itu.algs4.strings.rabin\_karp module
------------------------------------
.. automodule:: itu.algs4.strings.rabin_karp
:members:
:undoc-members:
:show-inheritance:
itu.algs4.strings.trie\_st module
---------------------------------
.. automodule:: itu.algs4.strings.trie_st
:members:
:undoc-members:
:show-inheritance:
itu.algs4.strings.tst module
----------------------------
.. automodule:: itu.algs4.strings.tst
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: itu.algs4.strings
:members:
:undoc-members:
:show-inheritance:
================================================
FILE: examples/bst.py
================================================
#!/usr/bin/env python3
import sys
from itu.algs4.searching.bst import BST
from itu.algs4.stdlib import stdio
if __name__ == "__main__":
if len(sys.argv) > 1:
try:
sys.stdin = open(sys.argv[1])
except IOError:
print("File not found, using standard input instead")
data = stdio.readAllStrings()
st: BST[str, int] = BST()
i = 0
for key in data:
st.put(key, i)
i += 1
print("LEVELORDER:")
for key in st.level_order():
print(str(key) + " " + str(st.get(key)))
print()
print("KEYS:")
for key in st.keys():
print(str(key) + " " + str(st.get(key)))
================================================
FILE: examples/hello_world.py
================================================
#!/usr/bin/env python3
from itu.algs4.stdlib import stdio
stdio.write("Hello World!\n")
================================================
FILE: examples/queue.py
================================================
#!/usr/bin/env python3
from itu.algs4.fundamentals.queue import Queue
from itu.algs4.stdlib import stdio
"""
Reads strings from an stdin and adds them to a queue.
When reading a '-' it removes the least recently added item and prints it.
Prints the amount of items left on the queue.
"""
queue: Queue[str] = Queue()
while not stdio.isEmpty():
input_item = stdio.readString()
if input_item != "-":
queue.enqueue(input_item)
elif not queue.is_empty():
print(queue.dequeue())
print("({} left on queue)".format(queue.size()))
================================================
FILE: examples/sort-numbers.py
================================================
#!/usr/bin/env python3
from itu.algs4.sorting import merge
from itu.algs4.stdlib import stdio
"""
Reads a list of integers from standard input.
Then prints it in sorted order.
"""
L = stdio.readAllInts()
merge.sort(L)
if len(L) > 0:
stdio.write(L[0])
for i in range(1, len(L)):
stdio.write(" ")
stdio.write(L[i])
stdio.writeln()
================================================
FILE: examples/stack.py
================================================
#!/usr/bin/env python3
import sys
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.stdlib import stdio
if len(sys.argv) > 1:
try:
sys.stdin = open(sys.argv[1])
except IOError:
print("File not found, using standard input instead")
stack: Stack[str] = Stack()
while not stdio.isEmpty():
item = stdio.readString()
if not item == "-":
stack.push(item)
elif not stack.is_empty():
stdio.write(stack.pop() + " ")
stdio.writef("(%i left on stack)\n", stack.size())
================================================
FILE: itu/__init__.py
================================================
================================================
FILE: itu/algs4/__init__.py
================================================
================================================
FILE: itu/algs4/errors/__init__.py
================================================
================================================
FILE: itu/algs4/errors/errors.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
class NoSuchElementException(Exception):
pass
class IllegalArgumentException(Exception):
pass
class UnsupportedOperationException(Exception):
pass
================================================
FILE: itu/algs4/fundamentals/__init__.py
================================================
================================================
FILE: itu/algs4/fundamentals/bag.py
================================================
# Created for BADS 2018
# see README.md for details
# This is python3
# See ResizingArrayBag for a version that uses a resizing array.
from typing import Generic, Iterator, Optional, TypeVar
T = TypeVar("T")
S = TypeVar("S")
class Bag(Generic[T]):
"""The Bag class represents a bag (or multiset) of generic items. It
supports insertion and iterating over the items in arbitrary order.
This implementation uses a singly linked list with a static nested class Node.
See LinkedBag for the version from the
textbook that uses a non-static nested class.
The add, is_empty, and size operations
take constant time. Iteration takes time proportional to the number of items.
"""
class Node(Generic[S]):
# helper linked list class
def __init__(self):
self.next: Optional[Bag.Node[T]] = None
self.item: Optional[S] = None
def __init__(self) -> None:
"""Initializes an empty bag."""
self._first: Optional[Bag.Node[T]] = None # beginning of bag
self._n = 0 # number of elements in bag
def is_empty(self) -> bool:
"""Returns true if this bag is empty.
:returns: true if this bag is empty
false otherwise
"""
return self._first is None
def size(self) -> int:
"""Returns the number of items in this bag.
:returns: the number of items in this bag
"""
return self._n
def __len__(self) -> int:
return self.size()
def add(self, item: T) -> None:
"""Adds the item to this bag.
:param item: the item to add to this bag
"""
oldfirst = self._first
self._first = Bag.Node()
self._first.item = item
self._first.next = oldfirst
self._n += 1
def __iter__(self) -> Iterator[T]:
"""Returns an iterator that iterates over the items in this bag in
arbitrary order.
:returns: an iterator that iterates over the items in this bag in arbitrary order
"""
current = self._first
while current is not None:
assert current.item is not None
yield current.item
current = current.next
def __repr__(self) -> str:
out = "{"
for elem in self:
out += "{}, ".format(elem)
return out + "}"
# start of the script itself
if __name__ == "__main__":
import sys
from itu.algs4.stdlib import stdio
if len(sys.argv) > 1:
try:
sys.stdin = open(sys.argv[1])
except IOError:
print("File not found, using standard input instead")
bag: Bag[str] = Bag()
while not stdio.isEmpty():
item = stdio.readString()
bag.add(item)
stdio.writef("size of bag = %i\n", bag.size())
for s in bag:
stdio.writeln(s)
================================================
FILE: itu/algs4/fundamentals/binary_search.py
================================================
import sys
from typing import List, TypeVar
from itu.algs4.stdlib import stdio
T = TypeVar("T")
# Created for BADS 2018
# See README.md for details
# This is python3
"""
The binary_search module provides a method for binary
searching for an item in a sorted array.
The index_of operation takes logarithmic time in the worst case.
"""
def index_of(a: List[T], key: T):
"""Returns the index of the specified key in the specified array.
:param a: the array of items, must be sorted in ascending order
:param key: the search key
:return: index of key in array if present -1 otherwise
"""
lo = 0
hi = len(a) - 1
while hi >= lo:
mid = lo + (hi - lo) // 2
if a[mid] < key:
lo = mid + 1
elif a[mid] > key:
hi = mid - 1
else:
return mid
return -1
def main():
"""Reads strings from first input file and sorts them Reads strings from
second input file and prints every string not in first input file."""
if len(sys.argv) == 3:
sys.stdin = open(sys.argv[1])
arr = stdio.readAllStrings()
arr.sort()
sys.stdin = open(sys.argv[2])
while not stdio.isEmpty():
key = stdio.readString()
if index_of(arr, key) == -1:
print(key)
if __name__ == "__main__":
main()
================================================
FILE: itu/algs4/fundamentals/evaluate.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
import math
import sys
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.stdlib import stdio
def evaluate():
ops = Stack()
vals = Stack()
while not stdio.isEmpty():
# Read token, push if operator
s = stdio.readString()
if s == "(":
pass
elif s == "+":
ops.push(s)
elif s == "-":
ops.push(s)
elif s == "*":
ops.push(s)
elif s == "/":
ops.push(s)
elif s == "sqrt":
ops.push(s)
elif s == ")":
# Pop, evaluate and push result if token is ")"
op = ops.pop()
v = vals.pop()
if op == "+":
v = vals.pop() + v
elif op == "-":
v = vals.pop() - v
elif op == "*":
v = vals.pop() * v
elif op == "/":
v = vals.pop() / v
elif op == "sqrt":
v = math.sqrt(v)
vals.push(v)
else:
vals.push(float(s))
stdio.writeln(vals.pop())
if __name__ == "__main__":
if len(sys.argv) > 1:
try:
sys.stdin = open(sys.argv[1])
except IOError:
print("File not found, using standard input instead")
evaluate()
================================================
FILE: itu/algs4/fundamentals/java_helper.py
================================================
# Created for BADS 2018
# See README.md for details
# this one is not inspired by algorithms from the book, but useful for running java and python in parallel
# Python 3
def java_string_hash(key):
"""If key is a string, compute its java .hash() code.
Taken from http://garage.pimentech.net/libcommonPython_src_python_libcommon_javastringhashcode/
"""
h = 0
for c in key:
h = (31 * h + ord(c)) & 0xFFFFFFFF
return ((h + 0x80000000) & 0xFFFFFFFF) - 0x80000000
def trailing_zeros(i):
zeros = 0
while i & 1 == 0 and zeros < 32:
zeros += 1
i = i >> 1
return zeros
================================================
FILE: itu/algs4/fundamentals/queue.py
================================================
from typing import Generic, Iterator, Optional, TypeVar
from ..errors.errors import NoSuchElementException
# Created for BADS 2018
# See README.md for details
# This is python3
T = TypeVar("T")
class Node(Generic[T]):
def __init__(self, item: T, next: Optional["Node[T]"]) -> None:
"""Initializes a new node.
:param item: the item to be stored in the node
:param next: the next node in the queue
"""
self.item: T = item
self.next: Optional[Node[T]] = next
class Queue(Generic[T]):
"""The Queue class represents a first-in-first-out (FIFO) queue of generic
items.
It supports the usual enqueue and dequeue operations, along with
methods for peeking at the first item, testing if the queue is
empty, and iterating through the items in FIFO order This
implementation uses a singly linked list of linked-list nodes The
enqueue, dequeue, peek, size, and is_empty operations all take
constant time in the worst case
"""
def __init__(self) -> None:
"""Initializes an empty queue."""
self._first: Optional[Node[T]] = None
self._last: Optional[Node[T]] = None
self._n: int = 0
def enqueue(self, item: T) -> None:
"""Adds the item to this queue.
:param item: the item to add
"""
old_last: Optional[Node[T]] = self._last
self._last = Node(item, None)
if self.is_empty():
self._first = self._last
else:
assert old_last is not None
old_last.next = self._last
self._n += 1
def dequeue(self) -> T:
"""
Removes and returns the item on this queue that was least recently added.
:return: the item on this queue that was least recently added.
:raises NoSuchElementException: if this queue is empty
"""
if self.is_empty():
raise NoSuchElementException("Queue underflow")
assert self._first is not None
item = self._first.item
self._first = self._first.next
self._n -= 1
if self.is_empty():
self._last = None
return item
def is_empty(self) -> bool:
"""Returns true if this queue is empty.
:return: True if this queue is empty otherwise False
:rtype: bool
"""
return self._first is None
def size(self) -> int:
"""Returns the number of items in this queue.
:return: the number of items in this queue
:rtype: int
"""
return self._n
def __len__(self) -> int:
return self.size()
def peek(self) -> T:
"""
Returns the item least recently added to this queue.
:return: the item least recently added to this queue
:raises NoSuchElementException: if this queue is empty
"""
if self.is_empty():
raise NoSuchElementException("Queue underflow")
assert self._first is not None
return self._first.item
def __iter__(self) -> Iterator[T]:
"""Iterates over all the items in this queue in FIFO order."""
curr = self._first
while curr is not None:
yield curr.item
curr = curr.next
def __repr__(self) -> str:
"""Returns a string representation of this queue.
:return: the sequence of items in FIFO order, separated by spaces
"""
s = []
for item in self:
s.append("{} ".format(item))
return "".join(s)
================================================
FILE: itu/algs4/fundamentals/stack.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
from typing import Generic, Iterator, List, Optional, TypeVar
T = TypeVar("T")
class Node(Generic[T]):
# helper linked list class
def __init__(self):
self.item: T = None
self.next: Optional[Node] = None
class Stack(Generic[T]):
"""The Stack class represents a last-in-first-out (LIFO) stack of generic
items. It supports the usual push and pop operations, along with methods
for peeking at the top item, testing if the stack is empty, and iterating
through the items in LIFO order.
This implementation uses a singly linked list with a static nested
class for linked-list nodes. See LinkedStack for the version from
the textbook that uses a non-static nested class. See
ResizingArrayStack for a version that uses a resizing array. The
push, pop, peek, size, and is-empty operations all take constant
time in the worst case.
"""
def __init__(self) -> None:
"""Initializes an empty stack."""
self._first: Optional[Node[T]] = None
self._n: int = 0
def is_empty(self) -> bool:
"""Returns true if this stack is empty.
:returns: true if this stack is empty false otherwise
"""
return self._n == 0
def size(self) -> int:
"""Returns the number of items in this stack.
:returns: the number of items in this stack
"""
return self._n
def __len__(self) -> int:
return self.size()
def push(self, item: T) -> None:
"""Adds the item to this stack.
:param item: the item to add
"""
oldfirst = self._first
self._first = Node()
self._first.item = item
self._first.next = oldfirst
self._n += 1
def pop(self) -> T:
"""Removes and returns the item most recently added to this stack.
:returns: the item most recently added
:raises ValueError: if this stack is empty
"""
if self.is_empty():
raise ValueError("Stack underflow")
assert self._first is not None
item = self._first.item
assert item is not None
self._first = self._first.next
self._n -= 1
return item
def peek(self) -> T:
"""Returns (but does not remove) the item most recently added to this
stack.
:returns: the item most recently added to this stack
:raises ValueError: if this stack is empty
"""
if self.is_empty():
raise ValueError("Stack underflow")
assert self._first is not None
item = self._first.item
assert item is not None
return item
def __repr__(self) -> str:
"""Returns a string representation of this stack.
:returns: the sequence of items in this stack in LIFO order, separated by spaces
"""
s = []
for item in self:
s.append(item.__repr__())
return " ".join(s)
def __iter__(self) -> Iterator[T]:
"""Returns an iterator to this stack that iterates through the items in
LIFO order.
:return: an iterator to this stack that iterates through the items in LIFO order
"""
current = self._first
while current is not None:
item = current.item
assert item is not None
yield item
current = current.next
class FixedCapacityStack(Generic[T]):
def __init__(self, capacity: int):
self.a: List[Optional[T]] = [None] * capacity
self.n: int = 0
def is_empty(self) -> bool:
return self.n == 0
def size(self) -> int:
return self.n
def __len__(self) -> int:
return self.size()
def push(self, item: T):
self.a[self.n] = item
self.n += 1
def pop(self) -> T:
self.n -= 1
item = self.a[self.n]
assert item is not None
return item
class ResizingArrayStack(Generic[T]):
def __init__(self) -> None:
self.a: List[Optional[T]] = [None]
self.n: int = 0
def is_empty(self) -> bool:
return self.n == 0
def size(self) -> int:
return self.n
def __len__(self) -> int:
return self.size()
def resize(self, capacity: int) -> None:
temp: List[Optional[T]] = [None] * capacity
for i in range(self.n):
temp[i] = self.a[i]
self.a = temp
def push(self, item: T) -> None:
if self.n == len(self.a):
self.resize(2 * len(self.a))
self.a[self.n] = item
self.n += 1
def pop(self) -> T:
self.n -= 1
item = self.a[self.n]
self.a[self.n] = None
if self.n > 0 and self.n <= len(self.a) // 4:
self.resize(len(self.a) // 2)
assert item is not None
return item
def __iter__(self) -> Iterator[T]:
i = self.n - 1
while i >= 0:
item = self.a[i]
assert item is not None
yield item
i -= 1
================================================
FILE: itu/algs4/fundamentals/three_sum.py
================================================
class ThreeSum:
@staticmethod
def count(a):
# Count triples that sum to 0
n = len(a)
count = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if a[i] + a[j] + a[k] == 0:
count += 1
return count
================================================
FILE: itu/algs4/fundamentals/three_sum_fast.py
================================================
from itu.algs4.fundamentals import binary_search
class ThreeSumFast:
@staticmethod
def count(a):
# Count triples that sum to 0
a.sort()
n = len(a)
count = 0
for i in range(n):
for j in range(i + 1, n):
if binary_search.index_of(a, -a[i] - a[j]) > j:
count += 1
return count
================================================
FILE: itu/algs4/fundamentals/two_sum_fast.py
================================================
from itu.algs4.fundamentals import binary_search
class TwoSumFast:
@staticmethod
def count(a):
# Count pairs that sum to 0
a = sorted(a)
n = len(a)
count = 0
for i in range(n):
if binary_search.index_of(a, -a[i]) > i:
count += 1
return count
================================================
FILE: itu/algs4/fundamentals/uf.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
"""The UF module implements several versions of the union-find data structure
(also known as the disjoint-sets data type). It supports the union and find
operations, along with a connected operation for determining whether two sites
are in the same component and a count operation that returns the total number
of components.
The union-find data type models connectivity among a set of n sites, named 0
through n-1. The is-connected-to relation must be an equivalence relation:
* Reflexive: p is connected to p.
* Symmetric: If p is connected to q, then q is connected to p.
* Transitive: If p is connected to q and q is connected to r, then
p is connected to r.
"""
import sys
from itu.algs4.stdlib import stdio
class UF:
"""
This is an implementation of the union-find data structure - see module documentation for
more info.
This implementation uses weighted quick union by rank with path compression by
halving. Initializing a data structure with n sites takes linear time. Afterwards,
the union, find, and connected operations take logarithmic time (in the worst case)
and the count operation takes constant time. Moreover, the amortized time per union,
find, and connected operation has inverse Ackermann complexity.
For additional documentation, see Section 1.5 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
"""
def __init__(self, n: int) -> None:
"""Initializes an empty union-find data structure with n sites, 0
through n-1. Each site is initially in its own component.
:param n: the number of sites
"""
self._count = n
self._parent = list(range(n))
self._rank = [0] * n
def _validate(self, p: int) -> None:
# validate that p is a valid index
n = len(self._parent)
if p < 0 or p >= n:
raise ValueError("index {} is not between 0 and {}".format(p, n - 1))
def union(self, p: int, q: int) -> None:
"""Merges the component containing site p with the component containing
site q.
:param p: the integer representing one site
:param q: the integer representing the other site
"""
root_p = self.find(p)
root_q = self.find(q)
if root_p == root_q:
return
# make root of smaller rank point to root of larger rank
if self._rank[root_p] < self._rank[root_q]:
self._parent[root_p] = root_q
elif self._rank[root_p] > self._rank[root_q]:
self._parent[root_q] = root_p
else:
self._parent[root_q] = root_p
self._rank[root_p] += 1
self._count -= 1
def find(self, p: int) -> int:
"""Returns the component identifier for the component containing site
p.
:param p: the integer representing one site
:return: the component identifier for the component containing site p
"""
self._validate(p)
while p != self._parent[p]:
self._parent[p] = self._parent[
self._parent[p]
] # path compression by halving
p = self._parent[p]
return p
def connected(self, p: int, q: int) -> bool:
"""Returns true if the two sites are in the same component.
:param p: the integer representing one site
:param q: the integer representing the other site
:return: true if the two sites p and q are in the same component; false otherwise
"""
return self.find(p) == self.find(q)
def count(self) -> int:
return self._count
class QuickUnionUF:
"""
This is an implementation of the union-find data structure - see module documentation for
more info.
This implementation uses quick union. Initializing a data structure with n sites takes
linear time. Afterwards, the union, find, and connected operations take linear time
(in the worst case) and the count operation takes constant time. For alternate implementations
of the same API, see UF, QuickFindUF, and WeightedQuickUnionUF.
For additional documentation, see Section 1.5 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
"""
def __init__(self, n: int) -> None:
"""Initializes an empty union-find data structure with n sites, 0
through n-1. Each site is initially in its own component.
:param n: the number of sites
"""
self._count = n
self._parent = list(range(n))
def _validate(self, p: int) -> None:
# validate that p is a valid index
n = len(self._parent)
if p < 0 or p >= n:
raise ValueError("index {} is not between 0 and {}".format(p, n - 1))
def union(self, p: int, q: int) -> None:
"""Merges the component containing site p with the component containing
site q.
:param p: the integer representing one site
:param q: the integer representing the other site
"""
root_p = self.find(p)
root_q = self.find(q)
if root_p == root_q:
return
self._parent[root_p] = root_q
self._count -= 1
def find(self, p: int) -> int:
"""Returns the component identifier for the component containing site
p.
:param p: the integer representing one site
:return: the component identifier for the component containing site p
"""
self._validate(p)
while p != self._parent[p]:
p = self._parent[p]
return p
def connected(self, p: int, q: int) -> bool:
"""Returns true if the two sites are in the same component.
:param p: the integer representing one site
:param q: the integer representing the other site
:return: true if the two sites p and q are in the same component; false otherwise
"""
return self.find(p) == self.find(q)
def count(self) -> int:
return self._count
class WeightedQuickUnionUF:
"""
This is an implementation of the union-find data structure - see module documentation for
more info.
This implementation uses weighted quick union by size (without path compression).
Initializing a data structure with n sites takes linear time. Afterwards, the union, find,
and connected operations take logarithmic time (in the worst case) and the count operation
takes constant time. For alternate implementations of the same API, see UF, QuickFindUF,
and QuickUnionUF.
For additional documentation, see Section 1.5 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
"""
def __init__(self, n: int) -> None:
"""Initializes an empty union-find data structure with n sites, 0
through n-1. Each site is initially in its own component.
:param n: the number of sites
"""
self._count = n
self._parent = list(range(n))
self._size = [1] * n
def _validate(self, p: int) -> None:
# validate that p is a valid index
n = len(self._parent)
if p < 0 or p >= n:
raise ValueError("index {} is not between 0 and {}".format(p, n - 1))
def union(self, p: int, q: int) -> None:
"""Merges the component containing site p with the component containing
site q.
:param p: the integer representing one site
:param q: the integer representing the other site
"""
root_p = self.find(p)
root_q = self.find(q)
if root_p == root_q:
return
# make root of smaller rank point to root of larger rank
if self._size[root_p] < self._size[root_q]:
small, large = root_p, root_q
else:
small, large = root_q, root_p
self._parent[small] = large
self._size[large] += self._size[small]
self._count -= 1
def find(self, p: int) -> int:
"""Returns the component identifier for the component containing site
p.
:param p: the integer representing one site
:return: the component identifier for the component containing site p
"""
self._validate(p)
while p != self._parent[p]:
p = self._parent[p]
return p
def connected(self, p: int, q: int) -> bool:
"""Returns true if the two sites are in the same component.
:param p: the integer representing one site
:param q: the integer representing the other site
:return: true if the two sites p and q are in the same component; false otherwise
"""
return self.find(p) == self.find(q)
def count(self) -> int:
return self._count
class QuickFindUF:
"""
This is an implementation of the union-find data structure - see module documentation for
more info.
This implementation uses quick find. Initializing a data structure with n sites takes linear time.
Afterwards, the find, connected, and count operations take constant time but the union operation
takes linear time.
For additional documentation, see Section 1.5 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
"""
def __init__(self, n: int) -> None:
"""Initializes an empty union-find data structure with n sites, 0
through n-1. Each site is initially in its own component.
:param n: the number of sites
"""
self._count = n
self._id = list(range(n))
def _validate(self, p: int) -> None:
# validate that p is a valid index
n = len(self._id)
if p < 0 or p >= n:
raise ValueError("index {} is not between 0 and {}".format(p, n - 1))
def union(self, p: int, q: int) -> None:
"""Merges the component containing site p with the component containing
site q.
:param p: the integer representing one site
:param q: the integer representing the other site
"""
self._validate(p)
self._validate(q)
p_id = self._id[p] # needed for correctness
q_id = self._id[q] # to reduce the number of array accesses
# p and q are already in the same component
if p_id == q_id:
return
for i in range(len(self._id)):
if self._id[i] == p_id:
self._id[i] = q_id
self._count -= 1
def find(self, p: int) -> int:
"""Returns the component identifier for the component containing site
p.
:param p: the integer representing one site
:return: the component identifier for the component containing site p
"""
self._validate(p)
return self._id[p]
def connected(self, p: int, q: int) -> bool:
"""Returns true if the two sites are in the same component.
:param p: the integer representing one site
:param q: the integer representing the other site
:return: true if the two sites p and q are in the same component; false otherwise
"""
self._validate(p)
self._validate(q)
return self._id[p] == self._id[q]
def count(self):
return self._count
# Reads in a an integer n and a sequence of pairs of integers
# (between 0 and n-1) from standard input or a file
# supplied as argument to the program, where each integer
# in the pair represents some site; if the sites are in different
# components, merge the two components and print the pair to standard output.
if __name__ == "__main__":
if len(sys.argv) > 1:
try:
sys.stdin = open(sys.argv[1])
except IOError:
print("File not found, using standard input instead")
n = stdio.readInt()
uf = UF(n)
while not stdio.isEmpty():
p = stdio.readInt()
q = stdio.readInt()
if uf.connected(p, q):
continue
uf.union(p, q)
print("{} {}".format(p, q))
print("number of components: {}".format(uf.count()))
================================================
FILE: itu/algs4/graphs/Arbitrage.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
import math
import sys
from itu.algs4.graphs.bellman_ford_sp import BellmanFordSP
from itu.algs4.graphs.directed_edge import DirectedEdge
from itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph
from itu.algs4.stdlib import stdio
if __name__ == "__main__":
"""The Arbitrage function provides a client that finds an arbitrage
opportunity in a currency exchange table by constructing a complete-digraph
representation of the exchange table and then finding a negative cycle in
the digraph.
This implementation uses the Bellman-Ford algorithm to find a negative cycle in
the complete digraph. The running time is proportional to V3 in the worst case,
where V is the number of currencies.
For additional documentation, see Section 4.4 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
"""
if len(sys.argv) > 1:
try:
sys.stdin = open(sys.argv[1])
except IOError:
print("File not found, using standard input instead")
# V currencies
V = stdio.readInt()
name = [None] * V
# Create complete network
graph = EdgeWeightedDigraph(V)
for v in range(V):
name[v] = stdio.readString()
for w in range(V):
rate = stdio.readFloat()
edge = DirectedEdge(v, w, -math.log(rate))
graph.add_edge(edge)
# find negative cycle
spt = BellmanFordSP(graph, 0)
if spt.has_negative_cycle():
stake = 1000.0
for edge in spt.negative_cycle():
print("{} {}", stake, name[edge.from_vertex()])
stake *= math.exp(-edge.weight())
print("{} {}")
================================================
FILE: itu/algs4/graphs/CPM.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
import sys
from itu.algs4.graphs.acyclic_lp import AcyclicLp
from itu.algs4.graphs.directed_edge import DirectedEdge
from itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph
from itu.algs4.stdlib import instream
"""
The cpm module is an example of using graphs to solve the parallel precedence-constrained
job scheduling problem via the critical path method. It reduces the problem to the longest-paths
problem in edge-weighted DAGs. It builds an edge-weighted digraph (which must be a DAG) from the
job-scheduling problem specification, finds the longest-paths tree, and computes the longest-paths
lengths (which are precisely the start times for each job).
This implementation uses AcyclicLP to find a longest path in a DAG. The running time is proportional
to V + E, where V is the number of jobs and E is the number of precedence constraints.
For additional documentation, see Section 4.4 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
"""
# Try this with the jobsPC.txt data file
if __name__ == "__main__":
# Create stream from file or the standard input,
# depending on whether a file name was passed.
file = sys.argv[1] if len(sys.argv) > 1 else None
stream = instream.InStream(file)
# Number of jobs
N = stream.readInt()
# Source and sink
source, sink = 2 * N, 2 * N + 1
# Construct the network
G = EdgeWeightedDigraph(2 * N + 2)
for i in range(N):
duration = stream.readFloat()
G.add_edge(DirectedEdge(i, i + N, duration))
G.add_edge(DirectedEdge(source, i, 0.0))
G.add_edge(DirectedEdge(i + N, sink, 0.0))
# Precedence constraints
m = stream.readInt()
for _ in range(m):
successor = stream.readInt()
G.add_edge(DirectedEdge(i + N, successor, 0.0))
# Compute longest path
lp = AcyclicLp(G, source)
# Print results
print("Start times:")
for i in range(N):
print("{:4d}: {:5.1f}".format(i, lp.dist_to(i)))
print("Finish time: {:5.1f}".format(lp.dist_to(i)))
================================================
FILE: itu/algs4/graphs/__init__.py
================================================
================================================
FILE: itu/algs4/graphs/acyclic_lp.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
import sys
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph
from itu.algs4.graphs.topological import Topological
from itu.algs4.stdlib import instream
"""
This module implements a class for solving the single-source Longest
paths problem in edge-weighted directed acyclic graphs (DAGs), described in
Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
For more information, see chapter 4.2 of the book.
"""
class AcyclicLp:
"""The AcyclicLP class represents a data type for solving the single-source
longest paths problem in edge-weighted directed acyclic graphs (DAGs). The
edge weights can be positive, negative, or zero.
This implementation uses a topological-sort based algorithm. The constructor takes
time proportional to V + E, where V is the number of vertices and E is the number of edges.
Each call to distTo(int) and hasPathTo(int) takes constant time; each call to pathTo(int)
takes time proportional to the number of edges in the shortest path returned.
For additional documentation, see Section 4.4 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
"""
def __init__(self, edge_weighted_digraph, s):
"""Computes a longest paths tree from s to every other vertex in the
directed acyclic graph G.
:param edge_weighted_digraph: the acyclic digraph
:param s: the source vertex
"""
graph = edge_weighted_digraph
self._dist_to = [float("-inf")] * graph.V()
self._edge_to = [None] * graph.V()
self._validate_vertex(s)
self._dist_to[s] = 0.0
# relax vertices in topological order
topological = Topological(graph)
if not topological.has_order():
print(graph)
raise ValueError("Digraph is not acyclic.")
for v in topological.order():
for edge in graph.adj(v):
self._relax(edge)
def dist_to(self, v):
"""Returns the length of a longest path from the source vertex s to
vertex v.
:param v: the destination vertex
:returns: the length of a longest path from the source vertex s to vertex v;
negative infinity if no such path exists
"""
self._validate_vertex(v)
return self._dist_to[v]
def has_path_to(self, v):
"""Is there a path from the source vertex s to vertex v?"""
return self.dist_to(v) > float("-inf")
def path_to(self, v):
"""Returns a longest path from the source vertex s to vertex v.
:param: the destination vertex
:returns: a longest path from the source vertex s to vertex v as an iterable of edges, and None if no such path
"""
self._validate_vertex(v)
if not self.has_path_to(v):
return None
path = Stack()
edge = self._edge_to[v]
while edge is not None:
path.push(edge)
edge = self._edge_to[edge.from_vertex()]
return path
# relax edge e, but update if you find a *longer* path
def _relax(self, edge):
v, w = edge.from_vertex(), edge.to_vertex()
if self._dist_to[w] < self._dist_to[v] + edge.weight():
self._dist_to[w] = self._dist_to[v] + edge.weight()
self._edge_to[w] = edge
# throw an IllegalArgumentException unless 0 <= v < V
def _validate_vertex(self, v):
V = len(self._dist_to)
if not (0 <= v < V):
raise ValueError("vertex {} is not between 0 and {}".format(v, V - 1))
if __name__ == "__main__":
# Create stream from file or the standard input,
# depending on whether a file name was passed.
stream = sys.argv[1] if len(sys.argv) > 1 else None
d = EdgeWeightedDigraph.from_stream(instream.InStream(stream))
a = AcyclicLp(d, 3)
# print longest paths to all other vertices
for i in range(d.V()):
print("{} to {}".format(i, a.path_to(i)))
================================================
FILE: itu/algs4/graphs/acyclic_sp.py
================================================
# Created for BADS 2018
# see README.md for details
# This is python3
import math
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.graphs.topological import Topological
class AcyclicSP:
"""The AcyclicSP class represents a data type for solving the single-source
shortest paths problem in edge-weighted directed acyclic graphs (DAGs). The
edge weights can be positive, negative, or zero.
This implementation uses a topological-sort based algorithm. The
constructor takes time proportional to V + E, where V is the number
of vertices and E is the number of edges. Each call to distTo(int)
and has_path_to(int) takes constant time each call to pathTo(int)
takes time proportional to the number of edges in the shortest path
returned.
"""
def __init__(self, G, s):
"""Computes a shortest paths tree from s to every other vertex in the
directed acyclic graph G.
:param G: the acyclic digraph
:param s: the source vertex
:raises ValueError: if the digraph is not acyclic
:raises ValueError: unless 0 <= s < V
"""
self._dist_to = [0] * G.V() # _dist_to[v] = distance of shortest s->v path
self._edge_to = [None] * G.V() # _edge_to[v] = last edge on shortest s->v path
self._validate_vertex(s)
for v in range(G.V()):
self._dist_to[v] = math.inf
self._dist_to[s] = 0.0
# visit vertices in toplogical order
topological = Topological(G)
if not topological.has_order():
raise ValueError("Digraph is not acyclic.")
for v in topological.order():
for e in G.adj(v):
self._relax(e)
def _relax(self, e):
v = e.from_vertex()
w = e.to_vertex()
if self._dist_to[w] > self._dist_to[v] + e.weight():
self._dist_to[w] = self._dist_to[v] + e.weight()
self._edge_to[w] = e
def dist_to(self, v):
"""Returns the length of a shortest path from the source vertex s to
vertex v.
:param v: the destination vertex
:returns: the length of a shortest path from the source vertex s to vertex v
math.inf if no such path
:raises ValueError: unless 0 <= v < V
"""
self._validate_vertex(v)
return self._dist_to[v]
def has_path_to(self, v):
"""Is there a path from the source vertex s to vertex v?
:param v: the destination vertex
:returns: true if there is a path from the source vertex
s to vertex v, and false otherwise
:raises ValueError: unless 0 <= v < V
"""
self._validate_vertex(v)
return self._dist_to[v] < math.inf
def path_to(self, v):
"""Returns a shortest path from the source vertex s to vertex v.
:param v: the destination vertex
:returns: a shortest path from the source vertex s to vertex v
as an iterable of edges, and None if no such path
:raises ValueError: unless 0 <= v < V
"""
self._validate_vertex(v)
if not self.has_path_to(v):
return None
path = Stack()
e = self._edge_to[v]
while e is not None:
path.push(e)
e = self._edge_to[e.from_vertex()]
return path
def _validate_vertex(self, v):
# raise an ValueError unless 0 <= v < V
V = len(self._dist_to)
if v < 0 or v >= V:
raise ValueError("vertex {} is not between 0 and {}".format(v, V - 1))
if __name__ == "__main__":
import sys
from itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph
from itu.algs4.stdlib import stdio
from itu.algs4.stdlib.instream import InStream
In = InStream(sys.argv[1])
s = int(sys.argv[2])
G = EdgeWeightedDigraph.from_stream(In)
# find shortest path from s to each other vertex in DAG
sp = AcyclicSP(G, s)
for v in range(G.V()):
if sp.has_path_to(v):
stdio.writef("%d to %d (%.2f) ", s, v, sp.dist_to(v))
for e in sp.path_to(v):
stdio.writef("%s\t", e.__repr__())
stdio.writeln()
else:
stdio.writef("%d to %d no path\n", s, v)
================================================
FILE: itu/algs4/graphs/bellman_ford_sp.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
import sys
from itu.algs4.errors.errors import (
IllegalArgumentException,
UnsupportedOperationException,
)
from itu.algs4.fundamentals.queue import Queue
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph
from itu.algs4.graphs.edge_weighted_directed_cycle import EdgeWeightedDirectedCycle
from itu.algs4.stdlib.instream import InStream
try:
q = Queue()
q.enqueue(1)
except AttributeError:
print("ERROR - Could not import itu.algs4 queue")
sys.exit(1)
# Execution: python BellmanFordSP.py filename.txt s
# Data files: https://algs4.cs.princeton.edu/44sp/tinyEWDn.txt
# https://algs4.cs.princeton.edu/44sp/mediumEWDnc.txt
#
# Bellman-Ford shortest path algorithm. Computes the shortest path tree in
# edge-weighted digraph G from vertex s, or finds a negative cost cycle
# reachable from s.
"""
The BellmanFordSP class represents a data type for solving the
single-source shortest paths problem in edge-weighted digraphs with
no negative cycles.
The edge weights can be positive, negative, or zero.
This class finds either a shortest path from the source vertex s
to every other vertex or a negative cycle reachable from the source vertex.
This implementation uses the Bellman-Ford-Moore algorithm.
The constructor takes time proportional to V (V + E)
in the worst case, where V is the number of vertices and E
is the number of edges.
Each call to distTo(int) and hasPathTo(int),
hasNegativeCycle takes constant time;
each call to pathTo(int) and negativeCycle()
takes time proportional to length of the path returned.
"""
class BellmanFordSP:
# Computes a shortest paths tree from s to every other vertex in
# the edge-weighted digraph G.
# @param G the acyclic digraph
# @param s the source vertex
# @throws IllegalArgumentException unless 0 <= s < V
def __init__(self, G, s):
self._distTo = [
sys.float_info.max
] * G.V() # distTo[v] = distance of shortest s->v path
self._edgeTo = [None] * G.V() # edgeTo[v] = last edge on shortest s->v path
self._onQueue = [False] * G.V() # onQueue[v] = is v currently on the queue?
self._queue = Queue() # queue of vertices to relax
self._cost = 0 # number of calls to relax()
self._cycle = None # negative cycle (or None if no such cycle)
# Bellman-Ford algorithm
self._distTo[s] = 0.0
self._queue.enqueue(s)
self._onQueue[s] = True
while not self._queue.is_empty() and not self.has_negative_cycle():
v = self._queue.dequeue()
self._onQueue[v] = False
self._relax(G, v)
assert self._check(G, s)
# relax vertex v and put other endpoints on queue if changed
def _relax(self, G, v):
for e in G.adj(v):
w = e.to_vertex()
if self._distTo[w] > self._distTo[v] + e.weight():
self._distTo[w] = self._distTo[v] + e.weight()
self._edgeTo[w] = e
if not self._onQueue[w]:
self._queue.enqueue(w)
self._onQueue[w] = True
if self._cost % G.V() == 0:
self._find_negative_cycle()
if self.has_negative_cycle():
return # found a negative cycle
self._cost += 1
# Is there a negative cycle reachable from the source vertex s?
# @return true if there is a negative cycle reachable from the
# source vertex s, and false otherwise
def has_negative_cycle(self):
return self._cycle is not None
# Returns a negative cycle reachable from the source vertex s, or None
# if there is no such cycle.
# @return a negative cycle reachable from the soruce vertex s
# as an iterable of edges, and None if there is no such cycle
def negative_cycle(self):
return self._cycle
# by finding a cycle in predecessor graph
def _find_negative_cycle(self):
V = len(self._edgeTo)
spt = EdgeWeightedDigraph(V)
for v in range(V):
if self._edgeTo[v] is not None:
spt.add_edge(self._edgeTo[v])
finder = EdgeWeightedDirectedCycle(spt)
self._cycle = finder.cycle()
# Returns the length of a shortest path from the source vertex s to vertex v.
# @param v the destination vertex
# @return the length of a shortest path from the source vertex s to vertex v;
# sys.float_info.max if no such path
# @throws UnsupportedOperationException if there is a negative cost cycle reachable
# from the source vertex s
# @throws IllegalArgumentException unless 0 <= v < V
def dist_to(self, v):
self._validate_vertex(v)
if self.has_negative_cycle():
raise UnsupportedOperationException("Negative cost cycle exists")
return self._distTo[v]
# Is there a path from the source s to vertex v?
# @param v the destination vertex
# @return true if there is a path from the source vertex
# s to vertex v, and false otherwise
# @throws IllegalArgumentException unless 0 <= v < V
def has_path_to(self, v):
self._validate_vertex(v)
return self._distTo[v] < sys.float_info.max
# Returns a shortest path from the source s to vertex v.
# @param v the destination vertex
# @return a shortest path from the source s to vertex v
# as an iterable of edges, and None if no such path
# @throws UnsupportedOperationException if there is a negative cost cycle reachable
# from the source vertex s
# @throws IllegalArgumentException unless 0 <= v < V
def path_to(self, v):
self._validate_vertex(v)
if self.has_negative_cycle():
raise UnsupportedOperationException("Negative cost cycle exists")
if not self.has_path_to(v):
return None
path = Stack()
e = self._edgeTo[v]
while e is not None:
path.push(e)
e = self._edgeTo[e.from_vertex()]
return path
# check optimality conditions: either
# (i) there exists a negative cycle reacheable from s
# or
# (ii) for all edges e = v->w: distTo[w] <= distTo[v] + e.weight()
# (ii') for all edges e = v->w on the SPT: distTo[w] == distTo[v] + e.weight()
def _check(self, G, s):
# has a negative cycle
if self.has_negative_cycle():
weight = 0.0
for e in self.negative_cycle():
weight += e.weight()
if weight >= 0.0:
print("error: weight of negative cycle = {}".format(weight))
return False
# no negative cycle reachable from source
else:
# check that distTo[v] and edgeTo[v] are consistent
if self._distTo[s] != 0.0 or self._edgeTo[s] is not None:
print("distanceTo[s] and edgeTo[s] inconsistent")
return False
for v in range(G.V()):
if v == s:
continue
if self._edgeTo[v] is None and self._distTo[v] != sys.float_info.max:
print("distTo[] and edgeTo[] inconsistent")
return False
# check that all edges e = v->w satisfy distTo[w] <= distTo[v] + e.weight()
for v in range(G.V()):
for e in G.adj(v):
w = e.to_vertex()
if self._distTo[v] + e.weight() < self._distTo[w]:
print("edge {} not relaxed".format(e))
return False
# check that all edges e = v->w on SPT satisfy distTo[w] == distTo[v] + e.weight()
for w in range(G.V()):
if self._edgeTo[w] is None:
continue
e = self._edgeTo[w]
v = e.from_vertex()
if w != e.to_vertex():
return False
if self._distTo[v] + e.weight() != self._distTo[w]:
print("edge {} on shortest path not tight".format(e))
return False
print("Satisfies optimality conditions")
print()
return True
# raise an IllegalArgumentException unless 0 <= v < V
def _validate_vertex(self, v):
V = len(self._distTo)
if v < 0 or v >= V:
raise IllegalArgumentException(
"vertex {} is not between 0 and {}".format(v, V - 1)
)
def main(args):
stream = InStream(args[0])
s = int(args[1])
G = EdgeWeightedDigraph.from_stream(stream)
sp = BellmanFordSP(G, s)
# print negative cycle
if sp.has_negative_cycle():
for e in sp.negative_cycle():
print(e)
# print shortest paths
else:
for v in range(G.V()):
if sp.has_path_to(v):
print("{} to {} ({}) ".format(s, v, sp.dist_to(v)))
for e in sp.path_to(v):
print("{}\t".format(e), end="")
print()
else:
print("{} to {} no path".format(s, v))
if __name__ == "__main__":
main(sys.argv[1:])
# * % python BellmanFordSP.py tinyEWDn.txt 0
# * 0 to 0 ( 0.00)
# * 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
# * 0 to 2 ( 0.26) 0->2 0.26
# * 0 to 3 ( 0.99) 0->2 0.26 2->7 0.34 7->3 0.39
# * 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
# * 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
# * 0 to 6 ( 1.51) 0->2 0.26 2->7 0.34 7->3 0.39 3->6 0.52
# * 0 to 7 ( 0.60) 0->2 0.26 2->7 0.34
# *
# * % python BellmanFordSP.py tinyEWDnc.txt 0
# * 4->5 0.35
# * 5->4 -0.66
# *
================================================
FILE: itu/algs4/graphs/bipartite.py
================================================
# Created for BADS 2018
# see README.md for details
# This is python3
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.graphs.graph import Graph
class Bipartite:
"""The Bipartite class represents a data type for determining whether an
undirected graph is bipartite or whether it has an odd-length cycle. The
isBipartite operation determines whether the graph is bipartite. If so, the
color operation determines a bipartition if not, the oddCycle operation
determines a cycle with an odd number of edges.
This implementation uses depth-first search. The constructor takes
time proportional to V + E (in the worst case), where V is the
number of vertices and E is the number of edges. Afterwards, the
isBipartite and color operations take constant time the oddCycle
operation takes time proportional to the length of the cycle. See
BipartiteX for a nonrecursive version that uses breadth-first
search.
"""
class UnsupportedOperationException(Exception):
pass
def __init__(self, G):
"""Determines whether an undirected graph is bipartite and finds either
a bipartition or an odd-length cycle.
:param G: the graph
"""
self._is_bipartite = True # is the graph bipartite?
self._color = [
False
] * G.V() # color[v] gives vertices on one side of bipartition
self._marked = [False] * G.V() # marked[v] = True if v has been visited in DFS
self._edge_to = [0] * G.V() # edgeTo[v] = last edge on path to v
self._cycle = None # odd-length cycle
for v in range(G.V()):
if not self._marked[v]:
self._dfs(G, v)
assert self._check(G)
def _dfs(self, G, v):
self._marked[v] = True
for w in G.adj(v):
# short circuit if odd-length cycle found
if self._cycle is not None:
return
# found uncolored vertex, so recur
if not self._marked[w]:
self._edge_to[w] = v
self._color[w] = not self._color[v]
self._dfs(G, w)
# if v-w create an odd-length cycle, find it
elif self._color[w] == self._color[v]:
self._is_bipartite = False
self._cycle = Stack()
self._cycle.push(
w
) # don't need this unless you want to include start vertex twice
x = v
while x != w:
self._cycle.push(x)
x = self._edge_to[x]
self._cycle.push(w)
def is_bipartite(self):
"""Returns True if the graph is bipartite.
:returns: True if the graph is bipartite False otherwise
"""
return self._is_bipartite
def color(self, v):
"""Returns the side of the bipartite that vertex v is on.
:param v: the vertex
:returns: the side of the bipartition that vertex v is on two vertices
are in the same side of the bipartition if and only if they have the
same color
:raises IllegalArgumentException: unless 0 <= v < V
:raises UnsupportedOperationException: if this method is called when the graph
is not bipartite
"""
self._validateVertex(v)
if not self._is_bipartite:
raise Bipartite.UnsupportedOperationException("graph is not bipartite")
return self._color[v]
def odd_cycle(self):
"""Returns an odd-length cycle if the graph is not bipartite, and None
otherwise.
:returns: an odd-length cycle if the graph is not bipartite
(and hence has an odd-length cycle), and None otherwise
"""
return self._cycle
def _check(self, G):
# graph is bipartite
if self._is_bipartite:
for v in range(G.V()):
for w in G.adj(v):
if self._color[v] == self._color[w]:
error = "edge {}-{} with {} and {} in same side of bipartition\n".format(
v, w, v, w
)
print(error, file=sys.stderr)
return False
# graph has an odd-length cycle
else:
# verify cycle
first = -1
last = -1
for v in self.odd_cycle():
if first == -1:
first = v
last = v
if first != last:
error = "cycle begins with {} and ends with {}\n".format(first, last)
print(error, file=sys.stderr)
return False
return True
def _validateVertex(self, v):
# raise an ValueError unless 0 <= v < V
V = len(self._marked)
if v < 0 or v >= V:
raise ValueError("vertex {} is not between 0 and {}".format(v, V - 1))
if __name__ == "__main__":
import sys
from itu.algs4.stdlib import stdio
from itu.algs4.stdlib.instream import InStream
In = InStream(sys.argv[1])
G = Graph.from_stream(In)
stdio.writeln(G)
b = Bipartite(G)
if b.is_bipartite():
stdio.writeln("Graph is bipartite")
for v in range(G.V()):
stdio.writef("%i: %i\n", v, b.color(v))
else:
stdio.writeln("Graph has an odd-length cycle: ")
for x in b.odd_cycle():
stdio.writef("%i ", x)
stdio.writeln()
================================================
FILE: itu/algs4/graphs/breadth_first_paths.py
================================================
# Created for BADS 2018
# see README.md for details
# This is python3
import math
from itu.algs4.fundamentals.queue import Queue
from itu.algs4.fundamentals.stack import Stack
class BreadthFirstPaths:
"""The BreadthFirstPaths class represents a data type for finding shortest
paths (number of edges) from a source vertex s (or a set of source
vertices) to every other vertex in a directed or undirected graph.
This implementation uses breadth-first search. The constructor takes
time proportional to V + E, where V is the number of vertices and E
is the number of edges. Each call to distTo(int) and hasPathTo(int)
takes constant time each call to pathTo(int) takes time proportional
to the length of the path. It uses extra space (not including the
graph) proportional to V.
"""
def __init__(self, G, s):
"""Computes the shortest path between the source vertex s and every
other vertex in the graph G.
:param G: the graph
:param s: the source vertex
:raises ValueError: unless 0 <= s < V
"""
self._marked = [False] * G.V() # Is a shortest path to this vertex known?
self._dist_to = [math.inf] * G.V()
self._edgeTo = [0] * G.V() # last vertex on known path to this vertex
self._validateVertex(s)
self._bfs(G, s)
assert self._check(G, s)
# @staticmethod
# def from_multiple_sources(G, sources):
# """
# Computes the shortest path between any one of the source vertices in sources
# and every other vertex in graph G.
# :param G the graph
# :param sources the source vertices
# :raises ValueError: unless 0 <= s < V for each vertex
# s in sources
# """
# pass
def _bfs(self, G, s):
# breadth-first search from a single source
queue = Queue()
self._dist_to[s] = 0
self._marked[s] = True # Mark the source
queue.enqueue(s) # and put it on the queue.
while not queue.is_empty():
v = queue.dequeue() # Remove next vertex from the queue.
for w in G.adj(v):
if not self._marked[w]:
self._edgeTo[w] = v # For every unmarked adjacent vertex,
self._dist_to[w] = self._dist_to[v] + 1
self._marked[w] = True # mark it because path is known,
queue.enqueue(w) # and add it to the queue.
# def _bfs_multiple_sources(self, G, sources):
# # breadth-first search from multiple sources
# pass
def has_path_to(self, v):
"""Is there a path between the source vertex s (or sources) and vertex
v?
:param v: the vertex
:returns: true if there is a path, and False otherwise
:raises ValueError: unless 0 <= v < V
"""
return self._marked[v]
def dist_to(self, v):
"""Returns the number of edges in a shortest path between the source
vertex s (or sources) and vertex v?
:param v: the vertex
:returns: the number of edges in a shortest path
:raises ValueError: unless 0 <= v < V
"""
self._validateVertex(v)
return self._dist_to[v]
def path_to(self, v):
"""Returns a shortest path between the source vertex s (or sources) and
v, or null if no such path.
:param v: the vertex
:returns: the sequence of vertices on a shortest path, as an Iterable
:raises ValueError: unless 0 <= v < V
"""
if not self.has_path_to(v):
return None
path = Stack()
x = v
while self._dist_to[x] != 0:
path.push(x)
x = self._edgeTo[x]
path.push(x)
return path
def _check(self, G, s):
# check optimality conditions for singe source
# check that the distance of s = 0
if self._dist_to[s] != 0:
stdio.writef("distance of source %i to itself = %i\n", s, self._dist_to[s])
return False
# check that for each edge v-w dist[w] <= dist[v] + 1
# provided v is reachable from s
for v in range(G.V()):
for w in G.adj(v):
# if self.has_path_to(v) != self.has_path_to(w):
# modified for directed graphs
if self.has_path_to(v) and not self.has_path_to(w):
stdio.writef("edge %i-%i\n", v, w)
stdio.writef("has_path_to(%i) = %s\n", v, self.has_path_to(v))
stdio.writef("has_path_to(%i) = %s\n", w, self.has_path_to(w))
return False
if self.has_path_to(v) and (self._dist_to[w] > self._dist_to[v] + 1):
stdio.writef("edge %i-%i\n", v, w)
stdio.writef("dist_to[%i] = %i\n", v, self._dist_to[v])
stdio.writef("dist_to[%i] = %i\n", v, self._dist_to[w])
return False
# check that v = edgeTo[w] satisfies distTo[w] = distTo[v] + 1
# provided v is reachable from s
for w in range(G.V()):
if not self.has_path_to(w) or w == s:
continue
v = self._edgeTo[w]
if self._dist_to[w] != self._dist_to[v] + 1:
stdio.writef("shortest path edge %i-%i\n", v, w)
stdio.writef("dist_to[%i] = %i\n", v, self._dist_to[v])
stdio.writef("dist_to[%i] = %i\n", w, self._dist_to[w])
return False
return True
def _validateVertex(self, v):
# throw an ValueError unless 0 <= v < V
V = len(self._marked)
if v < 0 or v >= V:
raise ValueError("vertex {} is not between 0 and {}".format(v, V - 1))
# def _validateVertices(self, vertices):
# # throw an ValueError unless 0 <= v < V
# pass
class BreadthFirstPathsBook:
def __init__(self, G, s):
self._marked = [False] * G.V() # Is a shortest path to this vertex known?
self._edgeTo = [0] * G.V() # last vertex on known path to this vertex
self._s = s # source
self._bfs(G, s)
def _bfs(self, G, s):
# breadth-first search from a single source
queue = Queue()
self._marked[s] = True # Mark the source
queue.enqueue(s) # and put it on the queue.
while not queue.is_empty():
v = queue.dequeue() # Remove next vertex from the queue.
for w in G.adj(v):
if not self._marked[w]:
self._edgeTo[w] = v # For every unmarked adjacent vertex,
self._marked[w] = True # mark it because path is known,
queue.enqueue(w) # and add it to the queue.
def has_path_to(self, v):
return self._marked[v]
def path_to(self, v):
if not self.has_path_to(v):
return None
path = Stack()
x = v
while x != self._s:
path.push(x)
x = self._edgeTo[x]
path.push(self._s)
return path
if __name__ == "__main__":
import sys
from itu.algs4.graphs.graph import Graph
from itu.algs4.stdlib import stdio
from itu.algs4.stdlib.instream import InStream
In = InStream(sys.argv[1])
G = Graph.from_stream(In)
s = int(sys.argv[2])
bfs = BreadthFirstPaths(G, s)
for v in range(G.V()):
if bfs.has_path_to(v):
stdio.writef("%d to %d (%d): ", s, v, bfs.dist_to(v))
for x in bfs.path_to(v):
if x == s:
stdio.write(x)
else:
stdio.writef("-%i", x)
stdio.writeln()
else:
stdio.writef("%d to %d (-): not connected\n", s, v)
================================================
FILE: itu/algs4/graphs/cc.py
================================================
# Created for BADS 2018
# see README.md for details
# This is python3
class CC:
"""The CC class represents a data type for determining the connected
components in an undirected graph. The id operation determines in which
connected component a given vertex lies the connected operation determines
whether two vertices are in the same connected component the count
operation determines the number of connected components and the size
operation determines the number of vertices in the connect component
containing a given vertex.
The component identifier of a connected component is one of the
vertices in the connected component: two vertices have the same component
identifier if and only if they are in the same connected component.
This implementation uses depth-first search.
The constructor takes time proportional to V + E
(in the worst case),
where V is the number of vertices and E is the number of edges.
Afterwards, the id, count, connected,
and size operations take constant time.
"""
def __init__(self, G):
"""Computes the connected components of the undirected graph G.
:param G: the undirected graph
"""
self._marked = [False] * G.V() # marked[v] = has vertex v been marked?
self._id = [None] * G.V() # id[v] = id of connected component containing v
self._size = [0] * G.V() # size[id] = number of vertices in given component
self._count = 0 # number of connected components
for v in range(G.V()):
if not self._marked[v]:
self._dfs(G, v)
self._count += 1
def _dfs(self, G, v):
# depth-first search for a Graph
self._marked[v] = True
self._id[v] = self._count
self._size[self._count] += 1
for w in G.adj(v):
if not self._marked[w]:
self._dfs(G, w)
def id(self, v):
"""Returns the component id of the connected component containing
vertex v.
:param v: the vertex
:returns: the component id of the connected component containing vertex v
:raises ValueError: unless 0 <= v < V
"""
self._validate_vertex(v)
return self._id[v]
def size(self, v):
"""Returns the number of vertices in the connected component containing
vertex v.
:param v: the vertex
:returns: the number of vertices in the connected component containing vertex v
:raises ValueError: unless 0 <= v < V
"""
self._validate_vertex(v)
return self._size[self._id[v]]
def count(self):
"""Returns the number of connected components in the graph G.
:returns: the number of connected components in the graph G
"""
return self._count
def connected(self, v, w):
"""Returns true if vertices v and w are in the same connected
component.
:param v: one vertex
:param w: the other vertex
:returns: True if vertices v and w are in the same connected component;
False otherwise
:raises ValueError: unless 0 <= v < V
:raises ValueError: unless 0 <= w < V
"""
self._validate_vertex(v)
self._validate_vertex(w)
return self.id(v) == self.id(w)
def _validate_vertex(self, v):
# Raises a ValueError n unless 0 <= v < V
V = len(self._marked)
if v < 0 or v >= V:
raise ValueError("vertex {} is not between 0 and {}".format(v, V - 1))
class CCBook:
def __init__(self, G):
self._marked = [False] * G.V() # marked[v] = has vertex v been marked?
self._id = [None] * G.V() # id[v] = id of connected component containing v
self._count = 0 # number of connected components
for s in range(G.V()):
if not self._marked[s]:
self._dfs(G, s)
self._count += 1
def _dfs(self, G, v):
self._marked[v] = True
self._id[v] = self._count
for w in G.adj(v):
if not self._marked[w]:
self._dfs(G, w)
def connected(self, v, w):
return self._id[v] == self._id[w]
def id(self, v):
return self._id[v]
def count(self):
return self._count
if __name__ == "__main__":
import sys
from itu.algs4.fundamentals.queue import Queue
from itu.algs4.graphs.graph import Graph
from itu.algs4.stdlib import stdio
from itu.algs4.stdlib.instream import InStream
In = InStream(sys.argv[1])
G = Graph.from_stream(In)
cc = CC(G)
# number of connected components
m = cc.count()
stdio.writef("%i components\n", m)
# compute list of vertices in each connected component
components = [Queue() for _ in range(m)]
for v in range(G.V()):
components[cc.id(v)].enqueue(v)
# print results
for i in range(m):
for v in components[i]:
stdio.writef("%i ", v)
stdio.writeln()
================================================
FILE: itu/algs4/graphs/cycle.py
================================================
# Created for BADS 2018
# see README.md for details
# This is python3
from itu.algs4.fundamentals.stack import Stack
class Cycle:
"""The Cycle class represents a data type for determining whether an
undirected graph has a cycle. The hasCycle operation determines whether the
graph has a cycle and, if so, the cycle operation returns one.
This implementation uses depth-first search. The constructor takes
time proportional to V + E (in the worst case), where V is the
number of vertices and E is the number of edges. Afterwards, the
hasCycle operation takes constant time the cycle operation takes
time proportional to the length of the cycle.
"""
def __init__(self, G):
"""Determines whether the undirected graph G has a cycle and, if so,
finds such a cycle.
:param G: the undirected graph
"""
if self._has_self_loop(G):
return
if self._has_parallel_edges(G):
return
self._marked = [False] * G.V()
self._edgeTo = [0] * G.V()
self._cycle = None
for v in range(G.V()):
if not self._marked[v]:
self._dfs(G, -1, v)
def _has_self_loop(self, G):
# does this graph have a self loop?
# side effect: initialize cycle to be self loop
for v in range(G.V()):
for w in G.adj(v):
if v == w:
self._cycle = Stack()
self._cycle.push(v)
self._cycle.push(w)
return True
return False
def _has_parallel_edges(self, G):
# does this graph have two parallel edges?
# side effect: initialize cycle to be two parallel edges
self._marked = [False] * G.V()
for v in range(G.V()):
# check for parallel edges incident to v
for w in G.adj(v):
if self._marked[w]:
self._cycle = Stack()
self._cycle.push(v)
self._cycle.push(w)
self._cycle.push(v)
return True
self._marked[w] = True
for w in G.adj(v):
self._marked[w] = False
return False
def has_cycle(self):
"""Returns true if the graph G has a cycle.
:returns: true if the graph has a cycle false otherwise
"""
return self._cycle is not None
def cycle(self):
"""Returns a cycle in the graph G.
:returns: a cycle if the graph G has a cycle,
and null otherwise
"""
return self._cycle
def _dfs(self, G, u, v):
self._marked[v] = True
for w in G.adj(v):
# short circuit if cycle already found
if self._cycle is not None:
return
if not self._marked[w]:
self._edgeTo[w] = v
self._dfs(G, v, w)
elif w != u:
self._cycle = Stack()
x = v
while x != w:
self._cycle.push(x)
x = self._edgeTo[x]
self._cycle.push(w)
self._cycle.push(v)
if __name__ == "__main__":
import sys
from itu.algs4.graphs.graph import Graph
from itu.algs4.stdlib import stdio
from itu.algs4.stdlib.instream import InStream
In = InStream(sys.argv[1])
G = Graph.from_stream(In)
finder = Cycle(G)
if finder.has_cycle():
for v in finder.cycle():
stdio.writef("%i ", v)
stdio.writeln()
else:
stdio.writeln("Graph is acyclic")
================================================
FILE: itu/algs4/graphs/degrees_of_separation.py
================================================
from itu.algs4.graphs.breadth_first_paths import BreadthFirstPaths
from itu.algs4.graphs.symbol_graph import SymbolGraph
from itu.algs4.stdlib import stdio
class DegreesOfSeparation:
"""The DegreesOfSeparation class provides a client for finding the degree
of separation between one distinguished individual and every other
individual in a social network. As an example, if the social network
consists of actors in which two actors are connected by a link if they
appeared in the same movie, and Kevin Bacon is the distinguished
individual, then the client computes the Kevin Bacon number of every actor
in the network.
The running time is proportional to the number of individuals and
connections in the network. If the connections are given implicitly,
as in the movie network example (where every two actors are
connected if they appear in the same movie), the efficiency of the
algorithm is improved by allowing both movie and actor vertices and
connecting each movie to all of the actors that appear in that
movie.
"""
def __init__(self):
"""this class shouldn't be instantiated."""
pass
@staticmethod
def main(args):
"""Reads in a social network from a file, and then repeatedly reads in
individuals from standard input and prints out their degrees of
separation. Takes three command-line arguments: the name of a file, a
delimiter, and the name of the distinguished individual. Each line in
the file contains the name of a vertex, followed by a list of the names
of the vertices adjacent to that vertex, separated by the delimiter.
:param args: the command-line arguments
"""
filename = args[1]
delimiter = args[2]
source = args[3]
sg = SymbolGraph(filename, delimiter)
G = sg.graph()
if not sg.contains(source):
stdio.writeln("{} not in database".format(source))
return
s = sg.index_of(source)
bfs = BreadthFirstPaths(G, s)
while not stdio.isEmpty():
sink = stdio.readLine()
if sg.contains(sink):
t = sg.index_of(sink)
if bfs.has_path_to(t):
for v in bfs.path_to(t):
stdio.writef("\t%s\n", sg.name_of(v))
else:
stdio.writeln("\tNot connected")
else:
stdio.writeln("\tNot in database.")
if __name__ == "__main__":
import sys
DegreesOfSeparation.main(sys.argv)
================================================
FILE: itu/algs4/graphs/depth_first_order.py
================================================
from itu.algs4.fundamentals.queue import Queue
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.graphs.digraph import Digraph
class DepthFirstOrder:
"""The DepthFirstOrder class represents a data type for determining depth-
first search ordering of the vertices in a digraph or edge-weighted
digraph, including preorder, postorder, and reverse postorder.
This implementation uses depth-first search. The constructor takes time proportional
to V + E (in the worst case), where V is the number of vertices and E is the number
of edges. Afterwards, the preorder, postorder, and reverse postorder operation takes
take time proportional to V.
For additional documentation, see Section 4.2 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
"""
def __init__(self, digraph):
"""Determines a depth-first order for the digraph.
:param digraph: the digraph to check
"""
self._pre = [0] * digraph.V()
self._post = [0] * digraph.V()
self._preorder = Queue()
self._postorder = Queue()
self._marked = [False] * digraph.V()
self._pre_counter = 0
self._post_counter = 0
if isinstance(digraph, Digraph):
dfs = self._dfs
else:
dfs = self._dfs_edge_weighted
for v in range(digraph.V()):
if not self._marked[v]:
dfs(digraph, v)
def post(self, v=None):
"""Either returns the postorder number of vertex v or, if v is None,
returns the vertices in postorder.
:param v: None, or the vertex to return the postorder number of
:return: if v is None, the vertices in postorder, otherwise the postorder
number of v
"""
if v is None:
return self._postorder
else:
self._validate_vertex(v)
return self._post[v]
def pre(self, v=None):
"""Either returns the preorder number of vertex v or, if v is None,
returns the vertices in preorder.
:param v: None, or the vertex to return the preorder number of
:return: if v is None, the vertices in preorder, otherwise the preorder
number of v
"""
if v is None:
return self._preorder
else:
self._validate_vertex(v)
return self._pre[v]
def reverse_post(self):
"""Returns the vertices in reverse postorder.
:return: the vertices in reverse postorder, as an iterable of vertices
"""
reverse = Stack()
for v in self._postorder:
reverse.push(v)
return reverse
# run DFS in digraph G from vertex v and compute preorder/postorder
def _dfs(self, digraph, v):
self._marked[v] = True
self._pre[v] = self._pre_counter
self._pre_counter += 1
self._preorder.enqueue(v)
for w in digraph.adj(v):
if not self._marked[w]:
self._dfs(digraph, w)
self._postorder.enqueue(v)
self._post[v] = self._post_counter
self._post_counter += 1
# run DFS in edge-weighted digraph G from vertex v and compute preorder/postorder
def _dfs_edge_weighted(self, graph, v):
self._marked[v] = True
self._pre[v] = self._pre_counter
self._pre_counter += 1
self._preorder.enqueue(v)
for edge in graph.adj(v):
w = edge.to_vertex()
if not self._marked[w]:
self._dfs_edge_weighted(graph, w)
self._postorder.enqueue(v)
self._post[v] = self._post_counter
self._post_counter += 1
# throw an IllegalArgumentException unless 0 <= v < V
def _validate_vertex(self, v):
V = len(self._marked)
if v < 0 or v >= V:
raise ValueError("vertex {} is not between 0 and {}", v, V - 1)
# check that pre() and post() are consistent with pre(v) and post(v)
def _check(self):
# check that post(v) is consistent with post()
r = 0
for v in self.post():
if self.post(v) != r:
print("post(v) and post() inconsistent")
return False
r += 1
# check that pre(v) is consistent with pre()
r = 0
for v in self.pre():
if self.pre(v) != r:
print("pre(v) and pre() inconsistent")
return False
r += 1
return True
================================================
FILE: itu/algs4/graphs/depth_first_paths.py
================================================
# Created for BADS 2018
# see README.md for details
# This is python3
from itu.algs4.fundamentals.stack import Stack
class DepthFirstPaths:
"""The DepthFirstPaths class represents a data type for finding paths from
a source vertex s to every other vertex in an undirected graph.
This implementation uses depth-first search. The constructor takes
time proportional to V + E, where V is the number of vertices and E
is the number of edges. Each call to hasPathTo(int) takes constant
time each call to pathTo(int) takes time proportional to the length
of the path. It uses extra space (not including the graph)
proportional to V.
"""
def __init__(self, G, s):
"""Computes a path between s and every other vertex in graph G.
:param G: the graph
:param s: the source vertex
:raises ValueError: unless 0 <= s < V
"""
self._marked = [False] * G.V() # Has dfs been called for this vertex?
self._edgeTo = [0] * G.V() # last vertex on known path to this vertex
self._s = s # source
self._validateVertex(s)
self._dfs(G, s)
def _dfs(self, G, v):
# depth first search from v
self._marked[v] = True
for w in G.adj(v):
if not self._marked[w]:
self._edgeTo[w] = v
self._dfs(G, w)
def has_path_to(self, v):
"""Is there a path between the source vertex s and vertex v?
:param v: the vertex
:returns: true if there is a path, false otherwise
:raises ValueError: unless 0 <= v < V
"""
self._validateVertex(v)
return self._marked[v]
def path_to(self, v):
"""Returns a path between the source vertex s and vertex v, or None if
no such path.
:param v: the vertex
:returns: the sequence of vertices on a path between the source vertex
s and vertex v, as an Iterable
:raises ValueError: unless 0 <= v < V
"""
self._validateVertex(v)
if not self.has_path_to(v):
return None
path = Stack()
w = v
while w != self._s:
path.push(w)
w = self._edgeTo[w]
path.push(self._s)
return path
def _validateVertex(self, v):
# throw an ValueError unless 0 <= v < V
V = len(self._marked)
if v < 0 or v >= V:
raise ValueError("vertex {} is not between 0 and {}".format(v, V - 1))
if __name__ == "__main__":
import sys
from itu.algs4.graphs.graph import Graph
from itu.algs4.stdlib import stdio
from itu.algs4.stdlib.instream import InStream
In = InStream(sys.argv[1])
G = Graph.from_stream(In)
s = int(sys.argv[2])
dfs = DepthFirstPaths(G, s)
for v in range(G.V()):
if dfs.has_path_to(v):
stdio.writef("%d to %d: ", s, v)
for x in dfs.path_to(v):
if x == s:
stdio.write(x)
else:
stdio.writef("-%i", x)
stdio.writeln()
else:
stdio.writef("%d to %d: not connected\n", s, v)
================================================
FILE: itu/algs4/graphs/depth_first_search.py
================================================
# Created for BADS 2018
# see README.md for details
# This is python3
class DepthFirstSearch:
"""The DepthFirstSearch class represents a data type for determining the
vertices connected to a given source vertex s in an undirected graph. For
versions that find the paths, see DepthFirstPaths and BreadthFirstPaths.
This implementation uses depth-first search. The constructor takes
time proportional to V + E (in the worst case), where V is the
number of vertices and E is the number of edges. It uses extra space
(not including the graph) proportional to V.
"""
def __init__(self, G, s):
"""Computes the vertices in graph G that are connected to the source
vertex s.
:param G: the graph
:param s: the source vertex
:throws ValueError: unless 0 <= s < V
"""
self._marked = [False] * G.V() # marked[v] = is there an s-v path?
self._count = 0 # number of vertices connected to s
self._validateVertex(s)
self._dfs(G, s)
def _dfs(self, G, v):
# depth first search from v
self._marked[v] = True
self._count += 1
for w in G.adj(v):
if not self._marked[w]:
self._dfs(G, w)
def marked(self, v):
"""Is there a path between the source vertex s and vertex v?
:param v: the vertex
:returns: true if there is a path, false otherwise
:raises ValueError: unless 0 <= v < V
"""
self._validateVertex(v)
return self._marked[v]
def count(self):
"""Returns the number of vertices connected to the source vertex s.
:returns: the number of vertices connected to the source vertex s
"""
return self._count
def _validateVertex(self, v):
# throw an ValueError unless 0 <= v < V
V = len(self._marked)
if v < 0 or v >= V:
raise ValueError("vertex {} is not between 0 and {}".format(v, V - 1))
if __name__ == "__main__":
import sys
from itu.algs4.graphs.graph import Graph
from itu.algs4.stdlib import stdio
from itu.algs4.stdlib.instream import InStream
In = InStream(sys.argv[1])
G = Graph.from_stream(In)
s = int(sys.argv[2])
search = DepthFirstSearch(G, s)
for v in range(G.V()):
if search.marked(v):
stdio.writef("%i ", v)
stdio.writeln()
if search.count() != G.V():
stdio.writeln("NOT connected")
else:
stdio.writeln("connected")
================================================
FILE: itu/algs4/graphs/digraph.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
"""This module implements the directed graph data structure described in
Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
For more information, see chapter 4.2 of the book.
"""
import sys
from itu.algs4.fundamentals.bag import Bag
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.graphs.graph import Graph
from itu.algs4.stdlib.instream import InStream
class Digraph:
"""The Graph class represents an undirected graph of vertices.
named 0 through V - 1.
It supports the following two primary operations: add an edge to the graph,
iterate over all of the vertices adjacent to a vertex. It also provides
methods for returning the number of vertices V and the number
of edges E. Parallel edges and self-loops are permitted.
By convention, a self-loop v-v appears in the
adjacency list of v twice and contributes two to the degree
of v.
This implementation uses an adjacency-lists representation, which
is a vertex-indexed array of Bag objects.
All operations take constant time (in the worst case) except
iterating over the vertices adjacent to a given vertex, which takes
time proportional to the number of such vertices.
"""
def __init__(self, V):
"""Initializes an empty graph with V vertices and 0 edges. param V the
number of vertices.
:param V: number of vertices
:raises: ValueError if V < 0
"""
if V < 0:
raise ValueError("Number of vertices must be nonnegative")
self._V = V # number of vertices
self._E = 0 # number of edges
self._adj = [] # adjacency lists
for _ in range(V):
self._adj.append(Bag()) # Initialize all lists to empty bags.
@staticmethod
def from_stream(stream):
"""Initializes a graph from the specified input stream. The format is
the number of vertices V, followed by the number of edges E, followed
by E pairs of vertices, with each entry separated by whitespace.
:param stream: the input stream
:returns: new graph from stream
:raises ValueError: if the endpoints of any edge are not in prescribed range
:raises ValueError: if the number of vertices or edges is negative
:raises ValueError: if the input stream is in the wrong format
"""
V = stream.readInt() # read V
if V < 0:
raise ValueError("Number of vertices must be nonnegative")
g = Digraph(V) # construct this graph
E = stream.readInt() # read E
if E < 0:
raise ValueError("Number of edges in a Graph must be nonnegative")
for _ in range(E):
# Add an edge
v = stream.readInt() # read a vertex,
w = stream.readInt() # read another vertex,
g._validateVertex(v)
g._validateVertex(w)
g.add_edge(v, w) # and add edge connecting them.
return g
@staticmethod
def from_graph(G):
"""Initializes a new graph that is a deep copy of G.
:param G: the graph to copy
:returns: copy of G
"""
g = Graph(G.V())
g._E = G.E()
for v in range(G.V()):
# reverse so that adjacency list is in same order as original
reverse = Stack()
for w in G._adj[v]:
reverse.push(w)
for w in reverse:
g._adj[v].add(w)
def V(self):
"""Returns the number of vertices in this graph.
:returns: the number of vertices in this graph.
"""
return self._V
def E(self):
"""Returns the number of edges in this graph.
:returns: the number of edges in this graph.
"""
return self._E
def _validateVertex(self, v):
# throw a ValueError unless 0 <= v < V
if v < 0 or v >= self._V:
raise ValueError("vertex {} is not between 0 and {}".format(v, self._V))
def add_edge(self, v, w):
"""Adds the undirected edge v-w to this graph.
:param v: one vertex in the edge
:param w: the other vertex in the edge
:raises ValueError: unless both 0 <= v < V and 0 <= w < V
"""
self._adj[v].add(w) # add w to v's list
self._E += 1
def adj(self, v):
"""Returns the vertices adjacent to vertex v.
:param v: the vertex
:returns: the vertices adjacent to vertex v, as an iterable
:raises ValueError: unless 0 <= v < V
"""
self._validateVertex(v)
return self._adj[v]
def degree(self, v):
"""Returns the degree of vertex v.
:param v: the vertex
:returns: the degree of vertex v
:raises ValueError: unless 0 <= v < V
"""
self._validateVertex(v)
return self._adj[v].size()
def reverse(self):
"""Returns the reverse of the digraph.
:returns: the reverse of the digraph
"""
rev = Digraph(self._V)
for v in range(self._V):
for w in self.adj(v):
rev.add_edge(w, v)
return rev
def __repr__(self):
"""Returns a string representation of this graph.
:returns: the number of vertices V, followed by the number of edges E,
followed by the V adjacency lists
"""
s = ["{} vertices, {} edges\n".format(self._V, self._E)]
for v in range(self._V):
s.append("%d : " % (v))
for w in self._adj[v]:
s.append("%d " % (w))
s.append("\n")
return "".join(s)
if __name__ == "__main__":
# Create stream from file or the standard input,
# depending on whether a file name was passed.
stream = sys.argv[1] if len(sys.argv) > 1 else None
d = Digraph.from_stream(InStream(stream))
print(d)
================================================
FILE: itu/algs4/graphs/dijkstra_all_pairs_sp.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
"""This module implements a data type for solving the all-pairs shortest paths
problem in edge-weighted digraphs where the edge weights are nonnegative."""
import sys
from itu.algs4.graphs.dijkstra_sp import DijkstraSP
from itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph
from itu.algs4.stdlib import instream
class DijkstraAllPairsSP:
"""This implementation runs Dijkstra's algorithm from each vertex. The
constructor takes time proportional to V (E log V) and uses space
proprtional to V2, where V is the number of vertices and E is the number of
edges. Afterwards, the dist() and hasPath() methods take constant time and
the path() method takes time proportional to the number of edges in the
shortest path returned.
For additional documentation, see Section 4.4 of Algorithms, 4th
Edition by Robert Sedgewick and Kevin Wayne.
"""
def __init__(self, edge_weighted_digraph):
"""Computes a shortest paths tree from each vertex to to every other
vertex in the edge-weighted digraph G.
:param edge_weighted_digraph: the edge-weighted digraph
"""
self._all = []
for v in range(edge_weighted_digraph.V()):
self._all.append(DijkstraSP(edge_weighted_digraph, v))
def path(self, source, target):
"""Returns a shortest path from source vertex to the target vertex.
:param source: the source vertex
:param target: the destination vertex
:returns: a shortest path from the source vertex to the target vertex as an iterable of edges,
and None if no such path
"""
self._validateVertex(source)
self._validateVertex(target)
return self._all[source].path_to(target)
def has_path(self, source, target):
"""Is there a path from the source vertex to the target vertex?
:param source: the source vertex
:param target: the target vertex
:returns: True if there is a path from the source to the target, and False otherwise
"""
return self.dist(source, target) < float("inf")
def dist(self, source, target):
"""Returns the length of a shortest path from the source vertex to the
target vertex.
:param source: the source vertex
:param target: the target vertex
:returns: the length of a shortest path from the source vertex to the target vertex;
float('inf') if no such path
"""
self._validateVertex(source)
self._validateVertex(target)
return self._all[source].dist_to(target)
# throw a ValueError unless 0 <= v < V
def _validateVertex(self, v):
V = len(self._all)
if v < 0 or v >= V:
raise ValueError("vertex {} is not between 0 and {}".format(v, (V - 1)))
if __name__ == "__main__":
# Create stream from file or the standard input,
# depending on whether a file name was passed.
stream = sys.argv[1] if len(sys.argv) > 1 else None
# Create a DijkstraAllPairsSP data structure
g = EdgeWeightedDigraph.from_stream(instream.InStream(stream))
dijkstra_all = DijkstraAllPairsSP(g)
# Print the shortest path distances between all possible pairs of vertices.
for source in range(g.V()):
for target in range(g.V()):
print(dijkstra_all.dist(source, target))
================================================
FILE: itu/algs4/graphs/dijkstra_sp.py
================================================
import sys
from itu.algs4.errors.errors import IllegalArgumentException
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph
from itu.algs4.sorting.index_min_pq import IndexMinPQ
from itu.algs4.stdlib.instream import InStream
# Created for BADS 2018
# See README.md for details
# Python 3
class DijkstraSP:
"""The DijkstraSP class represents a data type for solving the single-
source shortest paths problem in edge-weighted digraphs where the edge
weights are nonnegative.
This implementation uses Dijkstra's algorithm with a binary heap.
The constructor takes time proportional to E log V, where V is the
number of vertices and E is the number of edges. Each call to
dist_to() and has_path_to() takes constant time. Each call to
path_to() takes time proportional to the number of edges in the
shortest path returned.
"""
def __init__(self, G, s):
"""Computes a shortest-paths tree from the source vertex s to every
other vertex in the edge-weighted digraph G.
:param G: The edge-weighted digraph
:param s: The source vertex
:raises IllegalArgumentException: if an edge weight is negative
:raises IllegalArgumentException: unless 0 <= s < V
"""
for e in G.edges():
if e.weight() < 0:
raise IllegalArgumentException("edge {} has negative weight".format(e))
self._dist_to = [float("inf")] * G.V()
self._edge_to = [None] * G.V()
self._validate_vertex(s)
self._dist_to[s] = 0.0
self._pq = IndexMinPQ(G.V())
self._pq.insert(s, 0.0)
while not self._pq.is_empty():
v = self._pq.del_min()
for e in G.adj(v):
self._relax(e)
def dist_to(self, v):
"""Returns the length of a shortest path from the source vertex s to
vertex v.
:param v: the destination vertex
:return: the length of a shortest path from the source vertex s to vertex v
:rtype: float
:raises IllegalArgumentException: unless 0 <= v < V
"""
self._validate_vertex(v)
return self._dist_to[v]
def has_path_to(self, v):
"""Returns True if there is a ath from the source vertex s to vertex v.
:param v: the destination vertex
:return: True if there is a path from the source vertex
s to vertex v. Otherwise returns False
:rtype: bool
:raises IllegalArgumentException: unless 0 <= v < V
"""
self._validate_vertex(v)
return self._dist_to[v] < float("inf")
def path_to(self, v):
"""Returns a shortest path from the source vertex s to vertex v.
:param v: the destination vertex
:return: a shortest path from the source vertex s to vertex v
:rtype: collections.iterable[DirectedEdge]
:raises IllegalArgumentException: unless 0 <= v < V
"""
self._validate_vertex(v)
if not self.has_path_to(v):
return None
path = Stack()
e = self._edge_to[v]
while e is not None:
path.push(e)
e = self._edge_to[e.from_vertex()]
return path
def _relax(self, e):
"""Relaxes the edge e and updates the pq if changed.
:param e: the edge to relax
"""
v = e.from_vertex()
w = e.to_vertex()
if self._dist_to[w] > self._dist_to[v] + e.weight():
self._dist_to[w] = self._dist_to[v] + e.weight()
self._edge_to[w] = e
if self._pq.contains(w):
self._pq.decrease_key(w, self._dist_to[w])
else:
self._pq.insert(w, self._dist_to[w])
def _validate_vertex(self, v):
"""Raises an IllegalArgumentException unless 0 <= v < V.
:param v: the vertex to be validated
"""
V = len(self._dist_to)
if v < 0 or v >= V:
raise IllegalArgumentException(
"vertex {} is not between 0 and {}".format(v, V - 1)
)
def main():
"""Creates an EdgeWeightedDigraph from input file.
Runs DijkstraSP on the graph with the given source vertex. Prints
the shortest path from the source vertex to all other vertices.
"""
if len(sys.argv) == 3:
stream = InStream(sys.argv[1])
G = EdgeWeightedDigraph.from_stream(stream)
s = int(sys.argv[2])
sp = DijkstraSP(G, s)
for t in range(G.V()):
if sp.has_path_to(t):
print("{} to {} ({:.2f}) ".format(s, t, sp.dist_to(t)), end="")
for e in sp.path_to(t):
print(e, end=" ")
print()
else:
print("{} to {} no path\n".format(s, t))
if __name__ == "__main__":
main()
================================================
FILE: itu/algs4/graphs/dijkstra_undirected_sp.py
================================================
import sys
from itu.algs4.errors.errors import IllegalArgumentException
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.graphs.edge_weighted_graph import EdgeWeightedGraph
from itu.algs4.sorting.index_min_pq import IndexMinPQ
from itu.algs4.stdlib.instream import InStream
# Created for BADS 2018
# See README.md for details
# Python 3
class DijkstraUndirectedSP:
"""The DijkstraSP class represents a data type for solving the single-
source shortest paths problem in edge-weighted diagraphs where the edge
weights are nonnegative.
This implementation uses Dijkstra's algorithm with a binary heap.
The constructor takes time proportional to E log V, where V is the
number of vertices and E is the number of edges. Each call to
dist_to() and has_path_to() takes constant time each call to
path_to() takes time proportional to the number of edges in the
shortest path returned.
"""
def __init__(self, G, s):
"""Computes a shortest-paths tree from the source vertex s to every
other vertex in the edge-weighted graph G.
:param G: the edge-weighted graph
:param s: the source vertex
:raises IllegalArgumentException: if an edge weight is negative
:raises IllegalArgumentException: unless 0 <= s < V
"""
for e in G.edges():
if e.weight() < 0:
raise IllegalArgumentException("edge {} has negative weight".format(e))
self._dist_to = [float("inf")] * G.V()
self._edge_to = [None] * G.V()
self._dist_to[s] = 0.0
self._validate_vertex(s)
self._pq = IndexMinPQ(G.V())
self._pq.insert(s, 0)
while not self._pq.is_empty():
v = self._pq.del_min()
for e in G.adj(v):
self._relax(e, v)
def dist_to(self, v):
"""Returns the length of a shortest path between the source vertex s
and vertex v.
:param v: the destination vertex
:return: the length of a shortest path between the source vertex s and
the vertex v. float('inf') is not such path
:rtype: float
:raises IllegalArgumentException: unless 0 <= v < V
"""
return self._dist_to[v]
def has_path_to(self, v):
"""Returns true if there is a path between the source vertex s and
vertex v.
:param v: the destination vertex
:return: True if there is a path between the source vertex
s to vertex v. False otherwise
:rtype: bool
"""
return self._dist_to[v] < float("inf")
def path_to(self, v):
"""Returns a shortest path between the source vertex s and vertex v.
:param v: the destination vertex
:return: a shortest path between the source vertex s and vertex v.
None if no such path
:rtype: collections.iterable[Edge]
:raises IllegalArgumentException: unless 0 <= v < V
"""
self._validate_vertex(v)
if not self.has_path_to(v):
return None
path = Stack()
x = v
e = self._edge_to[v]
while e is not None:
edge = self._edge_to[x]
path.push(edge)
x = e.other(x)
e = self._edge_to[x]
return path
def _validate_vertex(self, v):
"""Raises an IllegalArgumentException unless 0 <= v < V.
:param v: the vertex to validate
"""
V = len(self._dist_to)
if v < 0 or v >= V:
raise IllegalArgumentException(
"vertex {} is not between 0 and {}".format(v, V - 1)
)
def _relax(self, e, v):
"""Relax edge e and update pq if changed.
:param e: the edge to relax
:param v: the vertex e goes out from
"""
w = e.other(v)
if self._dist_to[v] + e.weight() < self._dist_to[w]:
self._dist_to[w] = self._dist_to[v] + e.weight()
self._edge_to[w] = e
if self._pq.contains(w):
self._pq.decrease_key(w, self._dist_to[w])
else:
self._pq.insert(w, self._dist_to[w])
def main():
if len(sys.argv) == 3:
stream = InStream(sys.argv[1])
G = EdgeWeightedGraph.from_stream(stream)
s = int(sys.argv[2])
sp = DijkstraUndirectedSP(G, s)
for t in range(G.V()):
if sp.has_path_to(t):
print("{} to {} ({:.2f}) ".format(s, t, sp.dist_to(t)), end="")
for e in sp.path_to(t):
print(e, end=" ")
print()
else:
print("{} to {} no path\n".format(s, t))
if __name__ == "__main__":
main()
================================================
FILE: itu/algs4/graphs/directed_cycle.py
================================================
# Created for BADS 2018
# See README.md for details
# Python 3
"""This module implements the directed cycle algorithm described in Algorithms,
4th Edition by Robert Sedgewick and Kevin Wayne. This version works for both
weighted and unweighted directed graphs, due to Python's duck-typing.
For more information, see chapter 4.2 of the book.
"""
import sys
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.graphs.digraph import Digraph
from itu.algs4.stdlib.instream import InStream
class DirectedCycle:
"""The DirectedCycle class represents a data type for determining whether a
digraph has a directed cycle. The hasCycle operation determines whether the
digraph has a directed cycle and, and of so, the cycle operation returns
one.
This implementation uses depth-first search. The constructor takes time proportional
to V + E (in the worst case), where V is the number of vertices and E is the
number of edges. Afterwards, the hasCycle operation takes constant time; the
cycle operation takes time proportional to the length of the cycle.
See Topological to compute a topological order if the digraph is acyclic.
For additional documentation, see Section 4.2 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
"""
def __init__(self, digraph):
"""Determines whether the digraph has a directed cycle and, if so,
finds such a cycle.
:digraph: the digraph
"""
self._cycle = None
self._on_stack = [False] * digraph.V()
self._edge_to = [0] * digraph.V()
self._marked = [False] * digraph.V()
for v in range(digraph.V()):
if not self._marked[v]:
self._dfs(digraph, v)
# check that algorithm computes either the topological order or finds a directed cycle
def _dfs(self, digraph, v):
self._on_stack[v] = True
self._marked[v] = True
for w in digraph.adj(v):
# short circuit if directed cycle found
if self.has_cycle():
return
# found new vertex, so recur
elif not self._marked[w]:
self._edge_to[w] = v
self._dfs(digraph, w)
# trace back directed cycle
elif self._on_stack[w]:
self._cycle = Stack()
x = v
while x != w:
self._cycle.push(x)
x = self._edge_to[x]
self._cycle.push(w)
self._cycle.push(v)
self._on_stack[v] = False
def has_cycle(self):
"""Does the digraph have a directed cycle?
:returns: true if there is a cycle, false otherwise
"""
return self._cycle is not None
def cycle(self):
"""Returns a directed cycle if the digraph has a directed cycle, and
null otherwise.
:returns: a directed cycle (as an iterable) if the digraph has a directed cycle, and null otherwise
"""
return self._cycle
if __name__ == "__main__":
# Create stream from file or the standard input,
# depending on whether a file name was passed.
stream = sys.argv[1] if len(sys.argv) > 1 else None
d = Digraph.from_stream(InStream(stream))
cyc = DirectedCycle(d)
print(cyc.cycle())
================================================
FILE: itu/algs4/graphs/directed_dfs.py
================================================
# Created for BADS 2018
# See README.md for details
# This is python3
import sys
from itu.algs4.fundamentals.bag import Bag
from itu.algs4.graphs.digraph import Digraph
from itu.algs4.stdlib.instream import InStream
class DirectedDFS:
"""The DirectedDFS class represents a data type for determining the vertices
reachable from a given source vertex s (or a set of source vertices) in a
digraph. For versions that find the paths, see DepthFirstDirectedPaths and
BreadthFirstDirectedPaths.
This implementation uses depth-first search.
The constructor takes time proportional to V + E (in the worst case),
where V is the number of vertices and E is the number of edges.
For additional documentation, see Section 4.2 of Algorithms,
4th Edition by Robert Sedgewick and Kevin Wayne.
"""
def __init__(self, G, *s):
"""Computes the vertices in digraph G that are reachable from the source
vertex s.
:param G: the digraph
:param s: the source vertex/vertices
:raises ValueError: unless 0 <= s_ < V for every s_ in s
"""
self.marked = [False for i in range(0, G.V())]
self.reachables = 0
for s_ in s:
self._validate_vertex(s_)
self._dfs(G, s_)
def _dfs(self, G, v):
self.reachables += 1
self.marked[v] = True
for w in G.adj(v):
if not self.marked[w]:
self._dfs(G, w)
def is_marked(self, v):
"""Is there a directed path from the source vertex and vertex v?
:param v: the vertex
:returns: True if there is a directed
"""
self._validate_vertex(v)
return self.marked[v]
def count(self):
"""
Returns the number of vertices reachable from the source vertex
(or source vertices)
:returns: the number of vertices reachable from the source vertex
(or source vertices)
"""
return self.reachables
def _validate_vertex(self, v):
# Raise a ValueError unless 0 <= v < V
V = len(self.marked)
if v < 0 or v >= V:
raise ValueError("vertex {} is not between 0 and {}".format(v, V - 1))
def main():
"""Unit tests the DirectedDFS data type."""
G = Digraph.from_stream(InStream(None))
sources = Bag()
for i in range(1, len(sys.argv)):
s = int(sys.argv[i])
sources.add(s)
dfs = DirectedDFS(G, *sources)
print("Reachable vertices:")
for v in range(0, G.V()):
if dfs.is_marked(v):
print(v, end=" ")
print()
if __name__ == "__main__":
main()
================================================
FILE: itu/algs4/graphs/directed_edge.py
================================================
import math
from itu.algs4.errors.errors import IllegalArgumentException
# Created for BADS 2018
# See README.md for details
# Python 3
class DirectedEdge:
"""The DirectedEdge class represents a weighted edge in an
EdgeWeightedDigraph.
Each edge consists of two integers (naming the two vertices) and a
real-value weight. The data type provides methods for accessing the
two endpoints of the directed edge and the weight.
"""
def __init__(self, v, w, weight):
"""Initializes a directed edge from vertex v to vertex w with the given
weight.
:param v: the tail vertex
:param w: the head vertex
:param weight: the weight of the directed edge
:raises IllegalArgumentException: if either v or w is a negative integer
:raises IllegalArgumentException: if weight is NaN
"""
if v < 0:
raise IllegalArgumentException("Vertex names must be nonnegative integers")
if w < 0:
raise IllegalArgumentException("Vertex names must be nonnegative integers")
if math.isnan(weight):
raise IllegalArgumentException("Weight is NaN")
self._v = v
self._w = w
self._weight = weight
def from_vertex(self):
"""Returns the tail vertex of the directed edge.
:return: the tail vertex of the directed edge
:rtype: int
"""
return self._v
def to_vertex(self):
"""Returns the head vertex of the directed edge.
:return: the head vertex of the directed edge
:rtype: int
"""
return self._w
def weight(self):
"""Returns the weight of the directed edge.
:return: the weight of the directed edge
:rtype: float
"""
return self._weight
def __repr__(self):
"""Returns a string representation of the directed edge.
:return: a string representation of the directed edge
:rtype: str
"""
return "{}->{} {:5.2f}".format(self._v, self._w, self._weight)
def main():
"""Creates a directed edge and prints it.
:return:
"""
e = DirectedEdge(12, 34, 5.67)
print(e)
if __name__ == "__main__":
main()
================================================
FILE: itu/algs4/graphs/edge.py
================================================
import math
from itu.algs4.errors.errors import IllegalArgumentException
# Created for BADS 2018
# See README.md for details
# Python 3
class Edge:
"""The Edge class represents a weighted edge in an EdgeWeightedGraph.
Each edge consists of two integers (naming the two vertices) and a
real-value weight. The data type provides methods for accessing the
two endpoints of the edge and the weight. The natural order for this
data type is by ascending order of weight.
"""
def __init__(self, v, w, weight):
"""Initializes an edge between vertices v and w of the given weight.
:param v: one vertex
:param w: the other vertex
:param weight: the weight of this edge
:raises IllegalArgumentException: if either v or w is a negative integer
:raises IllegalArgumentException: if weight is NaN
"""
if v < 0:
raise IllegalArgumentException("vertex index must be a nonnegative integer")
if w < 0:
raise IllegalArgumentException("vertex index must be a nonnegative integer")
if math.isnan(weight):
raise IllegalArgumentException("Weight is NaN")
self._v = v
self._w = w
self._weight = weight
def weight(self):
"""Returns the weight of this edge.
:return: the weight of this edge
:rtype: float
"""
return self._weight
def either(self):
"""Returns either endpoint of this edge.
:return: either endpoint of this edge
:rtype: int
"""
return self._v
def other(self, vertex):
"""Returns the endpoint of this edge that is different from the given
vertex.
:param vertex: one endpoint of this edge
:return: the other endpoint of this edge
:rtype: int
:raises IllegalArgumentException: if the vertex is not one of the endpoints of this edge
"""
if vertex == self._v:
return self._w
elif vertex == self._w:
return self._v
else:
raise IllegalArgumentException("Illegal endpoint")
def __lt__(self, other):
"""Checks if this edge has smaller weight than other edge.
:param other: the edge to compare with
:return: True if weight of this edge is less than weight of other edge otherwise returns False
"""
return self.weight() < other.weight()
def __gt__(self, other):
"""Checks if this edge has greater weight than other edge.
:param other: the edge to compare with
:return: True if weight of this edge is greater than weight of other edge otherwise returns False
"""
return self.weight() > other.weight()
def __repr__(self):
"""Returns a string representation of this edge.
:return: a string representation of this edge
"""
return "{}-{} {:.5f}".format(self._v, self._w, self._weight)
def main():
"""Creates an edge and prints it."""
e = Edge(12, 34, 5.67)
print(e)
if __name__ == "__main__":
main()
================================================
FILE: itu/algs4/graphs/edge_weighted_digraph.py
================================================
import sys
from itu.algs4.errors.errors import IllegalArgumentException
from itu.algs4.fundamentals.bag import Bag
from itu.algs4.fundamentals.stack import Stack
from itu.algs4.graphs.directed_edge import DirectedEdge
from itu.algs4.stdlib.instream import InStream
# Created for BADS 2018
# See README.md for details
# Python 3
class EdgeWeightedDigraph:
"""The EdgeWeightedDigraph class represents an edge-weighted digraph of
vertices named 0 through V-1, where each directed edge is of type
DirectedEdge and has a real-valued weight.
It supports the following two primary operations: add a directed
edge to the digraph and iterate over all edges incident from a given
vertex. it also provides methods for returning the number of
vertices V and the number of edges E. Parallel edges and self-loops
are permitted. This implementation uses an adjacency-lists
representation, which is a vertex-indexed array of Bag objects. All
operations take constant time (in the worst case) except iterating
over the edges incident from a given vertex, which takes time
proportional to the number of such edges.
"""
def __init__(self, V):
"""Initializes an empty edge-weighted digraph with V vertices and 0
edges.
:param V: the number of vertices
:raises IllegalArgumentException: if V < 0
"""
if V < 0:
raise IllegalArgumentException(
"Number of vertices in a Digraph must be nonnegative"
)
self._V = V
self._E = 0
self._indegree = [0] * V
self._adj = [None] * V
for v in range(V):
self._adj[v] = Bag()
@staticmethod
def from_graph(G):
"""Initializes a new edge-weighted digraph that is a deep copy of G.
:param G: the edge-weighted digraph to copy
:return: a copy of graph G
:rtype: EdgeWeightedDigraph
"""
g = EdgeWeightedDigraph(G.V())
g._E = G.E()
for v in range(G.V()):
g._indegree[v] = G.indegree(v)
reverse = Stack()
for e in G.adj(v):
reverse.push(e)
for e in reverse:
g._adj[v].add(e)
return g
@staticmethod
def from_stream(stream):
"""Initializes an edge-weighted digraph from the specified input
stream. The format is the number of vertices V, followed by the number
of edges E, followed by E pairs of vertices and edge weights, with each
entry seperated by whitespace.
:param stream: the input stream
:raises IllegalArgumentException: if the endpoints of any edge are not in prescribed range
:raises IllegalArgumentException: if the number of vertices or edges is negative
:return: the edge-weighted digraph
:rtype: EdgeWeightedDigraph
"""
g = EdgeWeightedDigraph(stream.readInt())
E = stream.readInt()
if g._E < 0:
raise IllegalArgumentException("Number of edges must be nonnegative")
for _ in range(E):
v = stream.readInt()
w = stream.readInt()
g._validate_vertex(v)
g._validate_vertex(w)
weight = stream.readFloat()
g.add_edge(DirectedEdge(v, w, weight))
return g
def V(self):
"""Returns the number of vertices in this edge-weighted digraph.
:return: the number of vertices in this edge-weighted digraph
:rtype: int
"""
return self._V
def E(self):
"""Returns the number of edges in this edge-weighted digraph.
:return: the number of edges in this edge-weighted digraph
:rtype: int
"""
return self._E
gitextract_mlb3nvxv/
├── .github/
│ └── workflows/
│ ├── check.yml
│ └── python_publish.yml
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── create_html_doc.sh
├── docs/
│ ├── conf.py
│ ├── index.rst
│ ├── requirements.txt
│ └── source/
│ ├── itu.algs4.errors.rst
│ ├── itu.algs4.fundamentals.rst
│ ├── itu.algs4.graphs.rst
│ ├── itu.algs4.rst
│ ├── itu.algs4.searching.rst
│ ├── itu.algs4.sorting.rst
│ ├── itu.algs4.stdlib.rst
│ └── itu.algs4.strings.rst
├── examples/
│ ├── bst.py
│ ├── hello_world.py
│ ├── queue.py
│ ├── sort-numbers.py
│ └── stack.py
├── itu/
│ ├── __init__.py
│ └── algs4/
│ ├── __init__.py
│ ├── errors/
│ │ ├── __init__.py
│ │ └── errors.py
│ ├── fundamentals/
│ │ ├── __init__.py
│ │ ├── bag.py
│ │ ├── binary_search.py
│ │ ├── evaluate.py
│ │ ├── java_helper.py
│ │ ├── queue.py
│ │ ├── stack.py
│ │ ├── three_sum.py
│ │ ├── three_sum_fast.py
│ │ ├── two_sum_fast.py
│ │ └── uf.py
│ ├── graphs/
│ │ ├── Arbitrage.py
│ │ ├── CPM.py
│ │ ├── __init__.py
│ │ ├── acyclic_lp.py
│ │ ├── acyclic_sp.py
│ │ ├── bellman_ford_sp.py
│ │ ├── bipartite.py
│ │ ├── breadth_first_paths.py
│ │ ├── cc.py
│ │ ├── cycle.py
│ │ ├── degrees_of_separation.py
│ │ ├── depth_first_order.py
│ │ ├── depth_first_paths.py
│ │ ├── depth_first_search.py
│ │ ├── digraph.py
│ │ ├── dijkstra_all_pairs_sp.py
│ │ ├── dijkstra_sp.py
│ │ ├── dijkstra_undirected_sp.py
│ │ ├── directed_cycle.py
│ │ ├── directed_dfs.py
│ │ ├── directed_edge.py
│ │ ├── edge.py
│ │ ├── edge_weighted_digraph.py
│ │ ├── edge_weighted_directed_cycle.py
│ │ ├── edge_weighted_directed_cycle_anton.py
│ │ ├── edge_weighted_graph.py
│ │ ├── graph.py
│ │ ├── kosaraju_sharir_scc.py
│ │ ├── kruskal_mst.py
│ │ ├── lazy_prim_mst.py
│ │ ├── prim_mst.py
│ │ ├── symbol_digraph.py
│ │ ├── symbol_graph.py
│ │ ├── topological.py
│ │ └── transitive_closure.py
│ ├── searching/
│ │ ├── __init__.py
│ │ ├── binary_search_st.py
│ │ ├── bst.py
│ │ ├── file_index.py
│ │ ├── frequency_counter.py
│ │ ├── linear_probing_hst.py
│ │ ├── lookup_csv.py
│ │ ├── lookup_index.py
│ │ ├── red_black_bst.py
│ │ ├── seperate_chaining_hst.py
│ │ ├── sequential_search_st.py
│ │ ├── set.py
│ │ ├── sparse_vector.py
│ │ └── st.py
│ ├── sorting/
│ │ ├── __init__.py
│ │ ├── datafiles/
│ │ │ ├── tiny.txt
│ │ │ └── words3.txt
│ │ ├── heap.py
│ │ ├── index_min_pq.py
│ │ ├── insertion_sort.py
│ │ ├── max_pq.py
│ │ ├── merge.py
│ │ ├── merge_bu.py
│ │ ├── min_pq.py
│ │ ├── quick3way.py
│ │ ├── quicksort.py
│ │ ├── selection.py
│ │ └── shellsort.py
│ ├── stdlib/
│ │ ├── __init__.py
│ │ ├── binary_out.py
│ │ ├── binary_stdin.py
│ │ ├── binary_stdout.py
│ │ ├── color.py
│ │ ├── instream.py
│ │ ├── outstream.py
│ │ ├── picture.py
│ │ ├── stdarray.py
│ │ ├── stdaudio.py
│ │ ├── stddraw.py
│ │ ├── stdio.py
│ │ ├── stdrandom.py
│ │ └── stdstats.py
│ └── strings/
│ ├── __init__.py
│ ├── boyer_moore.py
│ ├── huffman_compression.py
│ ├── kmp.py
│ ├── lsd.py
│ ├── lzw.py
│ ├── msd.py
│ ├── nfa.py
│ ├── quick3string.py
│ ├── rabin_karp.py
│ ├── trie_st.py
│ └── tst.py
├── setup.cfg
├── setup.py
└── tests/
├── test_bst.py
├── test_red_black_bst.py
├── test_stack.py
└── test_symbol_tables.py
SYMBOL INDEX (969 symbols across 91 files)
FILE: itu/algs4/errors/errors.py
class NoSuchElementException (line 6) | class NoSuchElementException(Exception):
class IllegalArgumentException (line 10) | class IllegalArgumentException(Exception):
class UnsupportedOperationException (line 14) | class UnsupportedOperationException(Exception):
FILE: itu/algs4/fundamentals/bag.py
class Bag (line 13) | class Bag(Generic[T]):
class Node (line 26) | class Node(Generic[S]):
method __init__ (line 28) | def __init__(self):
method __init__ (line 32) | def __init__(self) -> None:
method is_empty (line 37) | def is_empty(self) -> bool:
method size (line 46) | def size(self) -> int:
method __len__ (line 54) | def __len__(self) -> int:
method add (line 57) | def add(self, item: T) -> None:
method __iter__ (line 69) | def __iter__(self) -> Iterator[T]:
method __repr__ (line 82) | def __repr__(self) -> str:
FILE: itu/algs4/fundamentals/binary_search.py
function index_of (line 19) | def index_of(a: List[T], key: T):
function main (line 40) | def main():
FILE: itu/algs4/fundamentals/evaluate.py
function evaluate (line 12) | def evaluate():
FILE: itu/algs4/fundamentals/java_helper.py
function java_string_hash (line 7) | def java_string_hash(key):
function trailing_zeros (line 19) | def trailing_zeros(i):
FILE: itu/algs4/fundamentals/queue.py
class Node (line 13) | class Node(Generic[T]):
method __init__ (line 14) | def __init__(self, item: T, next: Optional["Node[T]"]) -> None:
class Queue (line 25) | class Queue(Generic[T]):
method __init__ (line 38) | def __init__(self) -> None:
method enqueue (line 44) | def enqueue(self, item: T) -> None:
method dequeue (line 59) | def dequeue(self) -> T:
method is_empty (line 76) | def is_empty(self) -> bool:
method size (line 85) | def size(self) -> int:
method __len__ (line 94) | def __len__(self) -> int:
method peek (line 97) | def peek(self) -> T:
method __iter__ (line 109) | def __iter__(self) -> Iterator[T]:
method __repr__ (line 116) | def __repr__(self) -> str:
FILE: itu/algs4/fundamentals/stack.py
class Node (line 10) | class Node(Generic[T]):
method __init__ (line 12) | def __init__(self):
class Stack (line 17) | class Stack(Generic[T]):
method __init__ (line 32) | def __init__(self) -> None:
method is_empty (line 37) | def is_empty(self) -> bool:
method size (line 45) | def size(self) -> int:
method __len__ (line 53) | def __len__(self) -> int:
method push (line 56) | def push(self, item: T) -> None:
method pop (line 68) | def pop(self) -> T:
method peek (line 84) | def peek(self) -> T:
method __repr__ (line 99) | def __repr__(self) -> str:
method __iter__ (line 110) | def __iter__(self) -> Iterator[T]:
class FixedCapacityStack (line 125) | class FixedCapacityStack(Generic[T]):
method __init__ (line 126) | def __init__(self, capacity: int):
method is_empty (line 130) | def is_empty(self) -> bool:
method size (line 133) | def size(self) -> int:
method __len__ (line 136) | def __len__(self) -> int:
method push (line 139) | def push(self, item: T):
method pop (line 143) | def pop(self) -> T:
class ResizingArrayStack (line 150) | class ResizingArrayStack(Generic[T]):
method __init__ (line 151) | def __init__(self) -> None:
method is_empty (line 155) | def is_empty(self) -> bool:
method size (line 158) | def size(self) -> int:
method __len__ (line 161) | def __len__(self) -> int:
method resize (line 164) | def resize(self, capacity: int) -> None:
method push (line 170) | def push(self, item: T) -> None:
method pop (line 176) | def pop(self) -> T:
method __iter__ (line 185) | def __iter__(self) -> Iterator[T]:
FILE: itu/algs4/fundamentals/three_sum.py
class ThreeSum (line 1) | class ThreeSum:
method count (line 3) | def count(a):
FILE: itu/algs4/fundamentals/three_sum_fast.py
class ThreeSumFast (line 4) | class ThreeSumFast:
method count (line 6) | def count(a):
FILE: itu/algs4/fundamentals/two_sum_fast.py
class TwoSumFast (line 4) | class TwoSumFast:
method count (line 6) | def count(a):
FILE: itu/algs4/fundamentals/uf.py
class UF (line 24) | class UF:
method __init__ (line 38) | def __init__(self, n: int) -> None:
method _validate (line 49) | def _validate(self, p: int) -> None:
method union (line 55) | def union(self, p: int, q: int) -> None:
method find (line 79) | def find(self, p: int) -> int:
method connected (line 95) | def connected(self, p: int, q: int) -> bool:
method count (line 105) | def count(self) -> int:
class QuickUnionUF (line 109) | class QuickUnionUF:
method __init__ (line 122) | def __init__(self, n: int) -> None:
method _validate (line 132) | def _validate(self, p: int) -> None:
method union (line 138) | def union(self, p: int, q: int) -> None:
method find (line 155) | def find(self, p: int) -> int:
method connected (line 168) | def connected(self, p: int, q: int) -> bool:
method count (line 178) | def count(self) -> int:
class WeightedQuickUnionUF (line 182) | class WeightedQuickUnionUF:
method __init__ (line 196) | def __init__(self, n: int) -> None:
method _validate (line 207) | def _validate(self, p: int) -> None:
method union (line 213) | def union(self, p: int, q: int) -> None:
method find (line 237) | def find(self, p: int) -> int:
method connected (line 250) | def connected(self, p: int, q: int) -> bool:
method count (line 260) | def count(self) -> int:
class QuickFindUF (line 264) | class QuickFindUF:
method __init__ (line 276) | def __init__(self, n: int) -> None:
method _validate (line 286) | def _validate(self, p: int) -> None:
method union (line 292) | def union(self, p: int, q: int) -> None:
method find (line 315) | def find(self, p: int) -> int:
method connected (line 326) | def connected(self, p: int, q: int) -> bool:
method count (line 338) | def count(self):
FILE: itu/algs4/graphs/acyclic_lp.py
class AcyclicLp (line 21) | class AcyclicLp:
method __init__ (line 35) | def __init__(self, edge_weighted_digraph, s):
method dist_to (line 61) | def dist_to(self, v):
method has_path_to (line 74) | def has_path_to(self, v):
method path_to (line 78) | def path_to(self, v):
method _relax (line 96) | def _relax(self, edge):
method _validate_vertex (line 103) | def _validate_vertex(self, v):
FILE: itu/algs4/graphs/acyclic_sp.py
class AcyclicSP (line 11) | class AcyclicSP:
method __init__ (line 25) | def __init__(self, G, s):
method _relax (line 53) | def _relax(self, e):
method dist_to (line 61) | def dist_to(self, v):
method has_path_to (line 74) | def has_path_to(self, v):
method path_to (line 86) | def path_to(self, v):
method _validate_vertex (line 105) | def _validate_vertex(self, v):
FILE: itu/algs4/graphs/bellman_ford_sp.py
class BellmanFordSP (line 49) | class BellmanFordSP:
method __init__ (line 55) | def __init__(self, G, s):
method _relax (line 76) | def _relax(self, G, v):
method has_negative_cycle (line 94) | def has_negative_cycle(self):
method negative_cycle (line 101) | def negative_cycle(self):
method _find_negative_cycle (line 105) | def _find_negative_cycle(self):
method dist_to (line 122) | def dist_to(self, v):
method has_path_to (line 133) | def has_path_to(self, v):
method path_to (line 144) | def path_to(self, v):
method _check (line 162) | def _check(self, G, s):
method _validate_vertex (line 213) | def _validate_vertex(self, v):
function main (line 221) | def main(args):
FILE: itu/algs4/graphs/bipartite.py
class Bipartite (line 9) | class Bipartite:
class UnsupportedOperationException (line 26) | class UnsupportedOperationException(Exception):
method __init__ (line 29) | def __init__(self, G):
method _dfs (line 50) | def _dfs(self, G, v):
method is_bipartite (line 78) | def is_bipartite(self):
method color (line 86) | def color(self, v):
method odd_cycle (line 103) | def odd_cycle(self):
method _check (line 113) | def _check(self, G):
method _validateVertex (line 140) | def _validateVertex(self, v):
FILE: itu/algs4/graphs/breadth_first_paths.py
class BreadthFirstPaths (line 11) | class BreadthFirstPaths:
method __init__ (line 25) | def __init__(self, G, s):
method _bfs (line 55) | def _bfs(self, G, s):
method has_path_to (line 75) | def has_path_to(self, v):
method dist_to (line 86) | def dist_to(self, v):
method path_to (line 98) | def path_to(self, v):
method _check (line 117) | def _check(self, G, s):
method _validateVertex (line 155) | def _validateVertex(self, v):
class BreadthFirstPathsBook (line 166) | class BreadthFirstPathsBook:
method __init__ (line 167) | def __init__(self, G, s):
method _bfs (line 173) | def _bfs(self, G, s):
method has_path_to (line 186) | def has_path_to(self, v):
method path_to (line 189) | def path_to(self, v):
FILE: itu/algs4/graphs/cc.py
class CC (line 6) | class CC:
method __init__ (line 28) | def __init__(self, G):
method _dfs (line 44) | def _dfs(self, G, v):
method id (line 53) | def id(self, v):
method size (line 65) | def size(self, v):
method count (line 77) | def count(self):
method connected (line 85) | def connected(self, v, w):
method _validate_vertex (line 101) | def _validate_vertex(self, v):
class CCBook (line 108) | class CCBook:
method __init__ (line 109) | def __init__(self, G):
method _dfs (line 119) | def _dfs(self, G, v):
method connected (line 126) | def connected(self, v, w):
method id (line 129) | def id(self, v):
method count (line 132) | def count(self):
FILE: itu/algs4/graphs/cycle.py
class Cycle (line 8) | class Cycle:
method __init__ (line 21) | def __init__(self, G):
method _has_self_loop (line 39) | def _has_self_loop(self, G):
method _has_parallel_edges (line 51) | def _has_parallel_edges(self, G):
method has_cycle (line 70) | def has_cycle(self):
method cycle (line 78) | def cycle(self):
method _dfs (line 87) | def _dfs(self, G, u, v):
FILE: itu/algs4/graphs/degrees_of_separation.py
class DegreesOfSeparation (line 6) | class DegreesOfSeparation:
method __init__ (line 25) | def __init__(self):
method main (line 30) | def main(args):
FILE: itu/algs4/graphs/depth_first_order.py
class DepthFirstOrder (line 6) | class DepthFirstOrder:
method __init__ (line 20) | def __init__(self, digraph):
method post (line 44) | def post(self, v=None):
method pre (line 59) | def pre(self, v=None):
method reverse_post (line 74) | def reverse_post(self):
method _dfs (line 86) | def _dfs(self, digraph, v):
method _dfs_edge_weighted (line 99) | def _dfs_edge_weighted(self, graph, v):
method _validate_vertex (line 113) | def _validate_vertex(self, v):
method _check (line 119) | def _check(self):
FILE: itu/algs4/graphs/depth_first_paths.py
class DepthFirstPaths (line 8) | class DepthFirstPaths:
method __init__ (line 21) | def __init__(self, G, s):
method _dfs (line 35) | def _dfs(self, G, v):
method has_path_to (line 43) | def has_path_to(self, v):
method path_to (line 54) | def path_to(self, v):
method _validateVertex (line 76) | def _validateVertex(self, v):
FILE: itu/algs4/graphs/depth_first_search.py
class DepthFirstSearch (line 6) | class DepthFirstSearch:
method __init__ (line 18) | def __init__(self, G, s):
method _dfs (line 32) | def _dfs(self, G, v):
method marked (line 40) | def marked(self, v):
method count (line 51) | def count(self):
method _validateVertex (line 59) | def _validateVertex(self, v):
FILE: itu/algs4/graphs/digraph.py
class Digraph (line 20) | class Digraph:
method __init__ (line 40) | def __init__(self, V):
method from_stream (line 58) | def from_stream(stream):
method from_graph (line 87) | def from_graph(G):
method V (line 104) | def V(self):
method E (line 112) | def E(self):
method _validateVertex (line 120) | def _validateVertex(self, v):
method add_edge (line 125) | def add_edge(self, v, w):
method adj (line 136) | def adj(self, v):
method degree (line 147) | def degree(self, v):
method reverse (line 158) | def reverse(self):
method __repr__ (line 170) | def __repr__(self):
FILE: itu/algs4/graphs/dijkstra_all_pairs_sp.py
class DijkstraAllPairsSP (line 16) | class DijkstraAllPairsSP:
method __init__ (line 29) | def __init__(self, edge_weighted_digraph):
method path (line 40) | def path(self, source, target):
method has_path (line 55) | def has_path(self, source, target):
method dist (line 66) | def dist(self, source, target):
method _validateVertex (line 83) | def _validateVertex(self, v):
FILE: itu/algs4/graphs/dijkstra_sp.py
class DijkstraSP (line 14) | class DijkstraSP:
method __init__ (line 28) | def __init__(self, G, s):
method dist_to (line 52) | def dist_to(self, v):
method has_path_to (line 65) | def has_path_to(self, v):
method path_to (line 78) | def path_to(self, v):
method _relax (line 97) | def _relax(self, e):
method _validate_vertex (line 113) | def _validate_vertex(self, v):
function main (line 126) | def main():
FILE: itu/algs4/graphs/dijkstra_undirected_sp.py
class DijkstraUndirectedSP (line 14) | class DijkstraUndirectedSP:
method __init__ (line 28) | def __init__(self, G, s):
method dist_to (line 54) | def dist_to(self, v):
method has_path_to (line 67) | def has_path_to(self, v):
method path_to (line 79) | def path_to(self, v):
method _validate_vertex (line 102) | def _validate_vertex(self, v):
method _relax (line 114) | def _relax(self, e, v):
function main (line 131) | def main():
FILE: itu/algs4/graphs/directed_cycle.py
class DirectedCycle (line 20) | class DirectedCycle:
method __init__ (line 37) | def __init__(self, digraph):
method _dfs (line 53) | def _dfs(self, digraph, v):
method has_cycle (line 76) | def has_cycle(self):
method cycle (line 84) | def cycle(self):
FILE: itu/algs4/graphs/directed_dfs.py
class DirectedDFS (line 11) | class DirectedDFS:
method __init__ (line 26) | def __init__(self, G, *s):
method _dfs (line 41) | def _dfs(self, G, v):
method is_marked (line 48) | def is_marked(self, v):
method count (line 58) | def count(self):
method _validate_vertex (line 67) | def _validate_vertex(self, v):
function main (line 74) | def main():
FILE: itu/algs4/graphs/directed_edge.py
class DirectedEdge (line 10) | class DirectedEdge:
method __init__ (line 20) | def __init__(self, v, w, weight):
method from_vertex (line 41) | def from_vertex(self):
method to_vertex (line 50) | def to_vertex(self):
method weight (line 59) | def weight(self):
method __repr__ (line 68) | def __repr__(self):
function main (line 78) | def main():
FILE: itu/algs4/graphs/edge.py
class Edge (line 10) | class Edge:
method __init__ (line 20) | def __init__(self, v, w, weight):
method weight (line 40) | def weight(self):
method either (line 49) | def either(self):
method other (line 58) | def other(self, vertex):
method __lt__ (line 75) | def __lt__(self, other):
method __gt__ (line 84) | def __gt__(self, other):
method __repr__ (line 93) | def __repr__(self):
function main (line 102) | def main():
FILE: itu/algs4/graphs/edge_weighted_digraph.py
class EdgeWeightedDigraph (line 14) | class EdgeWeightedDigraph:
method __init__ (line 31) | def __init__(self, V):
method from_graph (line 51) | def from_graph(G):
method from_stream (line 71) | def from_stream(stream):
method V (line 98) | def V(self):
method E (line 107) | def E(self):
method _validate_vertex (line 116) | def _validate_vertex(self, v):
method add_edge (line 127) | def add_edge(self, e):
method adj (line 142) | def adj(self, v):
method outdegree (line 154) | def outdegree(self, v):
method indegree (line 167) | def indegree(self, v):
method edges (line 180) | def edges(self):
method __repr__ (line 193) | def __repr__(self):
function main (line 210) | def main():
FILE: itu/algs4/graphs/edge_weighted_directed_cycle.py
class EdgeWeightedDirectedCycle (line 30) | class EdgeWeightedDirectedCycle:
method __init__ (line 38) | def __init__(self, G):
method _dfs (line 52) | def _dfs(self, G, v):
method has_cycle (line 82) | def has_cycle(self):
method cycle (line 89) | def cycle(self):
method _check (line 93) | def _check(self):
function main (line 116) | def main(args):
FILE: itu/algs4/graphs/edge_weighted_directed_cycle_anton.py
class EdgeWeightedDirectedCycle (line 21) | class EdgeWeightedDirectedCycle:
method __init__ (line 38) | def __init__(self, edge_weighted_digraph):
method _dfs (line 54) | def _dfs(self, graph, v):
method has_cycle (line 78) | def has_cycle(self):
method cycle (line 86) | def cycle(self):
FILE: itu/algs4/graphs/edge_weighted_graph.py
class EdgeWeightedGraph (line 14) | class EdgeWeightedGraph:
method __init__ (line 32) | def __init__(self, V):
method from_graph (line 49) | def from_graph(G):
method from_stream (line 68) | def from_stream(stream):
method add_edge (line 95) | def add_edge(self, e):
method adj (line 109) | def adj(self, v):
method V (line 120) | def V(self):
method E (line 129) | def E(self):
method degree (line 138) | def degree(self, v):
method edges (line 150) | def edges(self):
method _validate_vertex (line 168) | def _validate_vertex(self, v):
method __repr__ (line 179) | def __repr__(self):
function main (line 196) | def main():
FILE: itu/algs4/graphs/graph.py
class Graph (line 9) | class Graph:
method __init__ (line 29) | def __init__(self, V):
method from_stream (line 47) | def from_stream(stream):
method from_graph (line 76) | def from_graph(G):
method V (line 93) | def V(self):
method E (line 101) | def E(self):
method _validateVertex (line 109) | def _validateVertex(self, v):
method add_edge (line 114) | def add_edge(self, v, w):
method adj (line 126) | def adj(self, v):
method degree (line 137) | def degree(self, v):
method __repr__ (line 148) | def __repr__(self):
FILE: itu/algs4/graphs/kosaraju_sharir_scc.py
class KosarajuSharirSCC (line 36) | class KosarajuSharirSCC:
method __init__ (line 43) | def __init__(self, G):
method _dfs (line 61) | def _dfs(self, G, v):
method count (line 73) | def count(self):
method strongly_connected (line 86) | def strongly_connected(self, v, w):
method id (line 98) | def id(self, v):
method _check (line 103) | def _check(self, G):
method _validate_vertex (line 114) | def _validate_vertex(self, v):
function main (line 122) | def main(args):
FILE: itu/algs4/graphs/kruskal_mst.py
class KruskalMST (line 14) | class KruskalMST:
method __init__ (line 32) | def __init__(self, G):
method edges (line 56) | def edges(self):
method weight (line 64) | def weight(self):
function main (line 74) | def main():
FILE: itu/algs4/graphs/lazy_prim_mst.py
class LazyPrimMST (line 10) | class LazyPrimMST:
method __init__ (line 29) | def __init__(self, G):
method _prim (line 48) | def _prim(self, G, s):
method _scan (line 67) | def _scan(self, G, v):
method edges (line 75) | def edges(self):
method weight (line 84) | def weight(self):
method _check (line 93) | def _check(self, G):
FILE: itu/algs4/graphs/prim_mst.py
class PrimMST (line 12) | class PrimMST:
method __init__ (line 31) | def __init__(self, G):
method _prim (line 58) | def _prim(self, G, s):
method _scan (line 65) | def _scan(self, G, v):
method edges (line 80) | def edges(self):
method weight (line 95) | def weight(self):
method _check (line 107) | def _check(self, G):
FILE: itu/algs4/graphs/symbol_digraph.py
class SymbolDigraph (line 11) | class SymbolDigraph:
method __init__ (line 29) | def __init__(self, filename, delimiter):
method contains (line 68) | def contains(self, s):
method index_of (line 77) | def index_of(self, s):
method name_of (line 86) | def name_of(self, v):
method digraph (line 97) | def digraph(self):
method _validateVertex (line 100) | def _validateVertex(self, v):
FILE: itu/algs4/graphs/symbol_graph.py
class SymbolGraph (line 11) | class SymbolGraph:
method __init__ (line 29) | def __init__(self, filename, delimiter):
method contains (line 68) | def contains(self, s):
method index_of (line 77) | def index_of(self, s):
method name_of (line 86) | def name_of(self, v):
method graph (line 97) | def graph(self):
method _validateVertex (line 100) | def _validateVertex(self, v):
FILE: itu/algs4/graphs/topological.py
class Topological (line 17) | class Topological:
method __init__ (line 37) | def __init__(self, digraph):
method order (line 60) | def order(self):
method has_order (line 70) | def has_order(self):
method rank (line 79) | def rank(self, v):
method _validate_vertex (line 93) | def _validate_vertex(self, v):
FILE: itu/algs4/graphs/transitive_closure.py
class TransitiveClosure (line 43) | class TransitiveClosure:
method __init__ (line 49) | def __init__(self, G):
method reachable (line 64) | def reachable(self, v, w):
method _validate_vertex (line 70) | def _validate_vertex(self, v):
function main (line 78) | def main(args):
FILE: itu/algs4/searching/binary_search_st.py
class BinarySearchST (line 8) | class BinarySearchST:
method __init__ (line 33) | def __init__(self, capacity=_INIT_CAPACITY):
method _resize (line 44) | def _resize(self, capacity):
method size (line 56) | def size(self):
method __len__ (line 64) | def __len__(self):
method is_empty (line 67) | def is_empty(self):
method contains (line 76) | def contains(self, key):
method get (line 89) | def get(self, key):
method rank (line 108) | def rank(self, key):
method put (line 132) | def put(self, key, val):
method delete (line 174) | def delete(self, key):
method deleteMin (line 212) | def deleteMin(self):
method deleteMax (line 223) | def deleteMax(self):
method min (line 237) | def min(self):
method max (line 248) | def max(self):
method select (line 259) | def select(self, k):
method floor (line 272) | def floor(self, key):
method ceiling (line 292) | def ceiling(self, key):
method size_between (line 310) | def size_between(self, lo, hi):
method keys (line 333) | def keys(self):
method keys_between (line 343) | def keys_between(self, lo, hi):
method _check (line 377) | def _check(self):
method _is_sorted (line 380) | def _is_sorted(self):
method _rank_check (line 389) | def _rank_check(self):
FILE: itu/algs4/searching/bst.py
class Comparable (line 35) | class Comparable(Protocol):
method __lt__ (line 37) | def __lt__(self: Key, other: Key) -> bool:
class Node (line 41) | class Node(Generic[Key, Val]):
method __init__ (line 42) | def __init__(self, key: Key, value: Optional[Val], size: int):
class BST (line 50) | class BST(Generic[Key, Val]):
method __init__ (line 51) | def __init__(self) -> None:
method is_empty (line 55) | def is_empty(self) -> bool:
method contains (line 59) | def contains(self, key: Key) -> bool:
method size (line 68) | def size(self) -> int:
method __len__ (line 72) | def __len__(self) -> int:
method _size (line 75) | def _size(self, node: Optional[Node[Key, Val]]) -> int:
method get (line 86) | def get(self, key: Key) -> Optional[Val]:
method _get (line 96) | def _get(self, node: Optional[Node[Key, Val]], key: Key) -> Optional[V...
method put (line 107) | def put(self, key: Key, value: Optional[Val]) -> None:
method _put (line 122) | def _put(
method delete_min (line 138) | def delete_min(self) -> None:
method _delete_min (line 147) | def _delete_min(self, node: Node[Key, Val]) -> Optional[Node[Key, Val]]:
method delete_max (line 155) | def delete_max(self) -> None:
method _delete_max (line 164) | def _delete_max(self, node: Node[Key, Val]) -> Optional[Node[Key, Val]]:
method delete (line 172) | def delete(self, key: Key) -> None:
method _delete (line 177) | def _delete(
method min (line 202) | def min(self) -> Key:
method _min (line 210) | def _min(self, node: Node[Key, Val]) -> Node[Key, Val]:
method max (line 216) | def max(self) -> Key:
method _max (line 224) | def _max(self, node: Node[Key, Val]) -> Node[Key, Val]:
method floor (line 230) | def floor(self, key: Key) -> Key:
method _floor (line 242) | def _floor(
method ceiling (line 256) | def ceiling(self, key: Key) -> Key:
method _ceiling (line 268) | def _ceiling(
method keys (line 282) | def keys(self) -> Queue[Key]:
method range_keys (line 288) | def range_keys(self, lo: Key, hi: Key) -> Queue[Key]:
method _range_keys (line 300) | def _range_keys(
method select (line 312) | def select(self, k: int) -> Key:
method _select (line 328) | def _select(self, x: Node[Key, Val], k: int) -> Node[Key, Val]:
method rank (line 343) | def rank(self, key: Key) -> int:
method _rank (line 357) | def _rank(self, key: Key, x: Optional[Node[Key, Val]]) -> int:
method size_range (line 372) | def size_range(self, lo: Key, hi: Key) -> int:
method height (line 394) | def height(self) -> int:
method _height (line 398) | def _height(self, node: Optional[Node[Key, Val]]) -> int:
method level_order (line 404) | def level_order(self) -> Queue[Key]:
FILE: itu/algs4/searching/linear_probing_hst.py
class LinearProbingHashST (line 8) | class LinearProbingHashST:
method __init__ (line 27) | def __init__(self, capacity=4):
method size (line 39) | def size(self):
method __len__ (line 47) | def __len__(self):
method is_empty (line 50) | def is_empty(self):
method contains (line 59) | def contains(self, key):
method _hash (line 72) | def _hash(self, key):
method _resize (line 76) | def _resize(self, capacity):
method put (line 86) | def put(self, key, value):
method get (line 116) | def get(self, key):
method delete (line 134) | def delete(self, key):
method key_list (line 172) | def key_list(self):
method _check (line 183) | def _check(self):
function main (line 202) | def main():
FILE: itu/algs4/searching/red_black_bst.py
class Comparable (line 20) | class Comparable(Protocol):
method __lt__ (line 22) | def __lt__(self: Key, other: Key) -> bool:
method __le__ (line 25) | def __le__(self: Key, other: Key) -> bool:
class Node (line 30) | class Node(Generic[Key, Val]):
method __init__ (line 33) | def __init__(self, key: Key, val: Val, color: bool, size: int):
class RedBlackBST (line 49) | class RedBlackBST(Generic[Key, Val]):
method __init__ (line 74) | def __init__(self) -> None:
method put (line 78) | def put(self, key: Key, val: Val) -> None:
method _put (line 100) | def _put(self, h: Optional[Node[Key, Val]], key: Key, val: Val) -> Nod...
method get (line 133) | def get(self, key: Key) -> Optional[Val]:
method _get (line 148) | def _get(self, x: Optional[Node[Key, Val]], key: Key) -> Optional[Val]:
method delete_min (line 166) | def delete_min(self) -> None:
method _delete_min (line 182) | def _delete_min(self, h: Node[Key, Val]) -> Optional[Node[Key, Val]]:
method delete_max (line 192) | def delete_max(self) -> None:
method _delete_max (line 208) | def _delete_max(self, h: Node[Key, Val]) -> Optional[Node[Key, Val]]:
method delete (line 220) | def delete(self, key: Key) -> None:
method _delete (line 241) | def _delete(self, h: Node[Key, Val], key: Key) -> Optional[Node[Key, V...
method size (line 269) | def size(self) -> int:
method __len__ (line 277) | def __len__(self) -> int:
method _size (line 280) | def _size(self, x: Optional[Node[Key, Val]]) -> int:
method contains (line 291) | def contains(self, key: Key) -> bool:
method is_empty (line 300) | def is_empty(self) -> bool:
method _is_red (line 309) | def _is_red(self, x: Optional[Node[Key, Val]]) -> bool:
method _rotate_left (line 320) | def _rotate_left(self, h: Node[Key, Val]) -> Node[Key, Val]:
method _rotate_right (line 337) | def _rotate_right(self, h: Node[Key, Val]) -> Node[Key, Val]:
method _flip_colors (line 354) | def _flip_colors(self, h: Node[Key, Val]) -> None:
method _move_red_left (line 366) | def _move_red_left(self, h: Node[Key, Val]) -> Node[Key, Val]:
method _move_red_right (line 381) | def _move_red_right(self, h: Node[Key, Val]) -> Node[Key, Val]:
method _balance (line 391) | def _balance(self, h: Node[Key, Val]) -> Node[Key, Val]:
method height (line 404) | def height(self) -> int:
method _height (line 412) | def _height(self, x: Optional[Node[Key, Val]]) -> int:
method min (line 418) | def min(self) -> Key:
method _min (line 430) | def _min(self, x: Node[Key, Val]) -> Node[Key, Val]:
method max (line 441) | def max(self) -> Key:
method _max (line 453) | def _max(self, x: Node[Key, Val]) -> Node[Key, Val]:
method keys (line 464) | def keys(self) -> Queue[Key]:
method keys_range (line 474) | def keys_range(self, lo: Key, hi: Key) -> Queue[Key]:
method _keys (line 491) | def _keys(
method select (line 505) | def select(self, k: int) -> Key:
method _select (line 521) | def _select(self, x: Node[Key, Val], k: int) -> Node[Key, Val]:
method rank (line 533) | def rank(self, key: Key) -> int:
method _rank (line 546) | def _rank(self, key: Key, x: Optional[Node[Key, Val]]) -> int:
method size_range (line 558) | def size_range(self, lo: Key, hi: Key) -> int:
method floor (line 579) | def floor(self, key: Key) -> Key:
method _floor (line 598) | def _floor(self, x: Optional[Node[Key, Val]], key: Key) -> Optional[No...
method ceiling (line 612) | def ceiling(self, key: Key) -> Key:
method _ceiling (line 631) | def _ceiling(
FILE: itu/algs4/searching/seperate_chaining_hst.py
class SeparateChainingHashST (line 9) | class SeparateChainingHashST:
method __init__ (line 28) | def __init__(self, M=997):
method _hash (line 33) | def _hash(self, key):
method get (line 37) | def get(self, key):
method put (line 51) | def put(self, key, value):
method size (line 73) | def size(self):
method is_empty (line 81) | def is_empty(self):
method contains (line 90) | def contains(self, key):
method delete (line 103) | def delete(self, key):
method keys (line 118) | def keys(self):
method __len__ (line 129) | def __len__(self):
function main (line 133) | def main():
FILE: itu/algs4/searching/sequential_search_st.py
class SequentialSearchST (line 6) | class SequentialSearchST:
class Node (line 27) | class Node:
method __init__ (line 29) | def __init__(self, key, val, next):
method __init__ (line 34) | def __init__(self):
method size (line 39) | def size(self):
method __len__ (line 47) | def __len__(self):
method is_empty (line 50) | def is_empty(self):
method contains (line 59) | def contains(self, key):
method get (line 72) | def get(self, key):
method put (line 91) | def put(self, key, val):
method delete (line 119) | def delete(self, key):
method _delete (line 131) | def _delete(self, x, key):
method keys (line 143) | def keys(self):
FILE: itu/algs4/searching/set.py
class SET (line 17) | class SET:
method __init__ (line 19) | def __init__(self, x=None):
method add (line 23) | def add(self, key):
method contains (line 29) | def contains(self, key):
method delete (line 35) | def delete(self, key):
method size (line 42) | def size(self):
method __len__ (line 45) | def __len__(self):
method is_empty (line 49) | def is_empty(self):
method __iter__ (line 55) | def __iter__(self):
method max (line 60) | def max(self):
method min (line 66) | def min(self):
method ceiling (line 72) | def ceiling(self, key):
method floor (line 86) | def floor(self, key):
method union (line 100) | def union(self, that):
method intersects (line 111) | def intersects(self, that):
method __eq__ (line 126) | def __eq__(self, other):
method hashCode (line 134) | def hashCode(self):
method __repr__ (line 140) | def __repr__(self):
function main (line 147) | def main():
FILE: itu/algs4/searching/sparse_vector.py
class SparseVector (line 9) | class SparseVector:
method __init__ (line 21) | def __init__(self, d):
method put (line 30) | def put(self, i, value):
method get (line 45) | def get(self, i):
method nnz (line 60) | def nnz(self):
method dimension (line 68) | def dimension(self):
method dot (line 76) | def dot(self, that):
method magnitude (line 99) | def magnitude(self):
method scale (line 108) | def scale(self, alpha):
method plus (line 121) | def plus(self, that):
method __repr__ (line 138) | def __repr__(self):
function main (line 142) | def main():
FILE: itu/algs4/searching/st.py
class ST (line 12) | class ST:
method __init__ (line 13) | def __init__(self):
method get (line 17) | def get(self, key):
method put (line 26) | def put(self, key, val):
method delete (line 36) | def delete(self, key):
method contains (line 42) | def contains(self, key):
method size (line 48) | def size(self):
method __len__ (line 51) | def __len__(self):
method is_empty (line 55) | def is_empty(self):
method keys (line 61) | def keys(self):
method __iter__ (line 64) | def __iter__(self):
method min (line 69) | def min(self):
method max (line 75) | def max(self):
method ceiling (line 81) | def ceiling(self, key):
method floor (line 96) | def floor(self, key):
FILE: itu/algs4/sorting/heap.py
function sort (line 12) | def sort(pq):
function _sink (line 27) | def _sink(pq, k, n):
function _less (line 44) | def _less(pq, i, j):
function _exch (line 57) | def _exch(pq, i, j):
function _show (line 69) | def _show(pq):
function main (line 79) | def main():
FILE: itu/algs4/sorting/index_min_pq.py
class IndexMinPQ (line 8) | class IndexMinPQ:
method __init__ (line 29) | def __init__(self, max_n):
method insert (line 43) | def insert(self, i, key):
method contains (line 62) | def contains(self, i):
method change_key (line 75) | def change_key(self, i, key):
method decrease_key (line 92) | def decrease_key(self, i, key):
method increase_key (line 113) | def increase_key(self, i, key):
method delete (line 134) | def delete(self, i):
method min_index (line 153) | def min_index(self):
method min_key (line 164) | def min_key(self):
method del_min (line 174) | def del_min(self):
method is_empty (line 192) | def is_empty(self):
method size (line 201) | def size(self):
method __len__ (line 210) | def __len__(self):
method key_of (line 213) | def key_of(self, i):
method _exch (line 228) | def _exch(self, i, j):
method _greater (line 239) | def _greater(self, i, j):
method _swim (line 251) | def _swim(self, k):
method _sink (line 261) | def _sink(self, k):
method __iter__ (line 276) | def __iter__(self):
function main (line 286) | def main():
FILE: itu/algs4/sorting/insertion_sort.py
function sort (line 20) | def sort(a: List[T]):
function _less (line 36) | def _less(v: T, w: T):
function _exch (line 40) | def _exch(a: List[T], i: int, j: int):
function _show (line 46) | def _show(a: List[T]):
function is_sorted (line 53) | def is_sorted(a: List[T]):
function main (line 66) | def main():
FILE: itu/algs4/sorting/max_pq.py
class MaxPQ (line 13) | class MaxPQ(Generic[Key]):
method __init__ (line 26) | def __init__(self, _max: int = 1):
method insert (line 35) | def insert(self, x: Key) -> None:
method max (line 47) | def max(self) -> Key:
method del_max (line 59) | def del_max(self) -> Key:
method is_empty (line 78) | def is_empty(self) -> bool:
method size (line 87) | def size(self) -> int:
method __len__ (line 96) | def __len__(self) -> int:
method _sink (line 99) | def _sink(self, k) -> None:
method _swim (line 114) | def _swim(self, k: int) -> None:
method _resize (line 124) | def _resize(self, capacity: int):
method _less (line 135) | def _less(self, i: int, j: int):
method _exch (line 145) | def _exch(self, i: int, j: int):
method __iter__ (line 154) | def __iter__(self) -> Iterator[Key]:
function main (line 165) | def main():
FILE: itu/algs4/sorting/merge.py
function _is_sorted (line 16) | def _is_sorted(a: List, lo: int = 0, hi: Optional[int] = None):
function _merge (line 29) | def _merge(a: List, aux: List, lo: int, mid: int, hi: int):
function _sort (line 60) | def _sort(a: List, aux: List, lo: int, hi: int):
function sort (line 69) | def sort(a: List):
FILE: itu/algs4/sorting/merge_bu.py
function _is_sorted (line 15) | def _is_sorted(a, lo=0, hi=None):
function _merge (line 28) | def _merge(a, aux, lo, mid, hi):
function sort (line 50) | def sort(a):
FILE: itu/algs4/sorting/min_pq.py
class MinPQ (line 12) | class MinPQ(Generic[Key]):
method __init__ (line 25) | def __init__(self, _max: int = 1) -> None:
method insert (line 34) | def insert(self, x: Key) -> None:
method min (line 46) | def min(self) -> Key:
method del_min (line 58) | def del_min(self) -> Key:
method is_empty (line 77) | def is_empty(self) -> bool:
method size (line 86) | def size(self) -> int:
method __len__ (line 95) | def __len__(self) -> int:
method _sink (line 98) | def _sink(self, k) -> None:
method _swim (line 113) | def _swim(self, k) -> None:
method _greater (line 123) | def _greater(self, i: int, j: int):
method _resize (line 134) | def _resize(self, capacity: int):
method _exch (line 145) | def _exch(self, i: int, j: int):
method __iter__ (line 154) | def __iter__(self):
function main (line 164) | def main():
FILE: itu/algs4/sorting/quick3way.py
function sort (line 10) | def sort(a):
function _sort (line 20) | def _sort(a, lo, hi):
function _compare (line 43) | def _compare(a, b):
function _less (line 47) | def _less(v, w):
function _exch (line 51) | def _exch(a, i, j):
function _show (line 57) | def _show(a):
function is_sorted (line 64) | def is_sorted(a):
function main (line 77) | def main():
FILE: itu/algs4/sorting/quicksort.py
function sort (line 19) | def sort(array):
function _sort (line 26) | def _sort(array, lo, hi):
function _partition (line 37) | def _partition(array, lo, hi):
function select (line 69) | def select(array, k):
function _exch (line 94) | def _exch(array, i, j):
function is_sorted (line 105) | def is_sorted(array):
function _is_sorted (line 109) | def _is_sorted(array, lo, hi):
function show (line 117) | def show(array):
FILE: itu/algs4/sorting/selection.py
function sort (line 13) | def sort(a):
function _exch (line 28) | def _exch(a, i, j):
function _show (line 39) | def _show(a):
function main (line 49) | def main():
FILE: itu/algs4/sorting/shellsort.py
function sort (line 9) | def sort(a):
function _less (line 30) | def _less(v, w):
function _exch (line 34) | def _exch(a, i, j):
function _show (line 40) | def _show(a):
function is_sorted (line 47) | def is_sorted(a):
function main (line 60) | def main():
FILE: itu/algs4/stdlib/binary_out.py
class BinaryOut (line 22) | class BinaryOut:
method __init__ (line 23) | def __init__(self, os=sys.stdout):
method _writeBit (line 34) | def _writeBit(self, x):
method _writeByte (line 42) | def _writeByte(self, x):
method _clearBuffer (line 53) | def _clearBuffer(self):
method flush (line 62) | def flush(self):
method close (line 66) | def close(self):
method write_bool (line 70) | def write_bool(self, x):
method write_byte (line 73) | def write_byte(self, x):
method write_int (line 76) | def write_int(self, x):
method write_char (line 82) | def write_char(self, x):
method write_string (line 87) | def write_string(self, s):
function main (line 92) | def main():
FILE: itu/algs4/stdlib/binary_stdin.py
class BinaryStdIn (line 21) | class BinaryStdIn:
method _initialize (line 29) | def _initialize():
method _fill_buffer (line 36) | def _fill_buffer():
method close (line 46) | def close():
method is_empty (line 54) | def is_empty():
method read_bool (line 60) | def read_bool():
method read_char (line 70) | def read_char():
method read_string (line 88) | def read_string():
method read_int (line 97) | def read_int(r=32):
function main (line 116) | def main():
FILE: itu/algs4/stdlib/binary_stdout.py
class BinaryStdOut (line 22) | class BinaryStdOut:
method _initialize (line 29) | def _initialize():
method _write_bit (line 35) | def _write_bit(x):
method _write_byte (line 46) | def _write_byte(x):
method _clear_buffer (line 60) | def _clear_buffer():
method flush (line 72) | def flush():
method close (line 77) | def close():
method write_bool (line 83) | def write_bool(x):
method write_byte (line 87) | def write_byte(x):
method write_int (line 91) | def write_int(x, r=32):
method write_char (line 107) | def write_char(x, r=8):
method write_string (line 121) | def write_string(s, r=8):
function main (line 126) | def main():
FILE: itu/algs4/stdlib/color.py
class Color (line 12) | class Color:
method __init__ (line 17) | def __init__(self, r=0, g=0, b=0):
method getRed (line 26) | def getRed(self):
method getGreen (line 32) | def getGreen(self):
method getBlue (line 38) | def getBlue(self):
method __str__ (line 44) | def __str__(self):
function _main (line 89) | def _main():
FILE: itu/algs4/stdlib/instream.py
class InStream (line 22) | class InStream:
method __init__ (line 42) | def __init__(self, fileOrUrl=None):
method _readRegExp (line 76) | def _readRegExp(self, regExp):
method isEmpty (line 98) | def isEmpty(self):
method readInt (line 112) | def readInt(self):
method readAllInts (line 143) | def readAllInts(self):
method readFloat (line 160) | def readFloat(self):
method readAllFloats (line 176) | def readAllFloats(self):
method readBool (line 193) | def readBool(self):
method readAllBools (line 211) | def readAllBools(self):
method readString (line 228) | def readString(self):
method readAllStrings (line 242) | def readAllStrings(self):
method hasNextLine (line 253) | def hasNextLine(self):
method readLine (line 267) | def readLine(self):
method readAllLines (line 282) | def readAllLines(self):
method readAll (line 293) | def readAll(self):
method __del__ (line 306) | def __del__(self):
function _main (line 317) | def _main():
FILE: itu/algs4/stdlib/outstream.py
class OutStream (line 14) | class OutStream:
method __init__ (line 21) | def __init__(self, f=None):
method writeln (line 38) | def writeln(self, x=""):
method write (line 53) | def write(self, x=""):
method writef (line 67) | def writef(self, fmt, *args):
method __del__ (line 84) | def __del__(self):
FILE: itu/algs4/stdlib/picture.py
class Picture (line 23) | class Picture:
method __init__ (line 32) | def __init__(self, arg1=None, arg2=None):
method save (line 83) | def save(self, f):
method width (line 99) | def width(self):
method height (line 105) | def height(self):
method get (line 111) | def get(self, x, y):
method set (line 118) | def set(self, x, y, c):
FILE: itu/algs4/stdlib/stdarray.py
function create1D (line 17) | def create1D(length, value=None):
function create2D (line 26) | def create2D(rowCount, colCount, value=None):
function write1D (line 40) | def write1D(a):
function write2D (line 66) | def write2D(a):
function readInt1D (line 96) | def readInt1D():
function readInt2D (line 112) | def readInt2D():
function readFloat1D (line 131) | def readFloat1D():
function readFloat2D (line 147) | def readFloat2D():
function readBool1D (line 166) | def readBool1D():
function readBool2D (line 182) | def readBool2D():
function _main (line 201) | def _main():
FILE: itu/algs4/stdlib/stdaudio.py
function wait (line 30) | def wait():
function playSample (line 46) | def playSample(s):
function playSamples (line 61) | def playSamples(a):
function playArray (line 67) | def playArray(a):
function playFile (line 77) | def playFile(f):
function save (line 87) | def save(f, a):
function read (line 110) | def read(f):
function _createTextAudioFile (line 138) | def _createTextAudioFile():
function _main (line 202) | def _main():
FILE: itu/algs4/stdlib/stddraw.py
function _pygameColor (line 106) | def _pygameColor(c):
function _scaleX (line 124) | def _scaleX(x):
function _scaleY (line 128) | def _scaleY(y):
function _factorX (line 132) | def _factorX(w):
function _factorY (line 136) | def _factorY(h):
function _userX (line 145) | def _userX(x):
function _userY (line 149) | def _userY(y):
function setCanvasSize (line 160) | def setCanvasSize(w=_DEFAULT_CANVAS_SIZE, h=_DEFAULT_CANVAS_SIZE):
function setXscale (line 188) | def setXscale(min=_DEFAULT_XMIN, max=_DEFAULT_XMAX):
function setYscale (line 202) | def setYscale(min=_DEFAULT_YMIN, max=_DEFAULT_YMAX):
function setPenRadius (line 216) | def setPenRadius(r=_DEFAULT_PEN_RADIUS):
function setPenColor (line 231) | def setPenColor(c=_DEFAULT_PEN_COLOR):
function setFontFamily (line 241) | def setFontFamily(f=_DEFAULT_FONT_FAMILY):
function setFontSize (line 247) | def setFontSize(s=_DEFAULT_FONT_SIZE):
function _makeSureWindowCreated (line 256) | def _makeSureWindowCreated():
function _pixel (line 268) | def _pixel(x, y):
function point (line 278) | def point(x, y):
function _thickLine (line 299) | def _thickLine(x0, y0, x1, y1, r):
function line (line 318) | def line(x0, y0, x1, y1):
function circle (line 349) | def circle(x, y, r):
function filledCircle (line 372) | def filledCircle(x, y, r):
function rectangle (line 395) | def rectangle(x, y, w, h):
function filledRectangle (line 419) | def filledRectangle(x, y, w, h):
function square (line 440) | def square(x, y, r):
function filledSquare (line 447) | def filledSquare(x, y, r):
function polygon (line 454) | def polygon(x, y):
function filledPolygon (line 474) | def filledPolygon(x, y):
function text (line 492) | def text(x, y, s):
function picture (line 505) | def picture(pic, x=None, y=None):
function clear (line 528) | def clear(c=WHITE):
function save (line 539) | def save(f):
function _show (line 559) | def _show():
function _showAndWaitForever (line 566) | def _showAndWaitForever():
function show (line 581) | def show(msec=float("inf")):
function _saveToFile (line 612) | def _saveToFile():
function _checkForEvents (line 662) | def _checkForEvents():
function hasNextKeyTyped (line 708) | def hasNextKeyTyped():
function nextKeyTyped (line 717) | def nextKeyTyped():
function mousePressed (line 730) | def mousePressed():
function mouseX (line 740) | def mouseX():
function mouseY (line 753) | def mouseY():
function _getFileName (line 784) | def _getFileName():
function _confirmFileSave (line 794) | def _confirmFileSave():
function _reportFileSaveError (line 804) | def _reportFileSaveError(msg):
function _regressionTest (line 819) | def _regressionTest():
function _main (line 938) | def _main():
FILE: itu/algs4/stdlib/stdio.py
function eprint (line 42) | def eprint(*args, **kwargs):
function writeln (line 51) | def writeln(x=""):
function write (line 68) | def write(x=""):
function writef (line 84) | def writef(fmt, *args):
function _readRegExp (line 109) | def _readRegExp(regExp):
function isEmpty (line 133) | def isEmpty():
function readInt (line 153) | def readInt():
function readAllInts (line 185) | def readAllInts():
function readFloat (line 204) | def readFloat():
function readAllFloats (line 221) | def readAllFloats():
function readBool (line 240) | def readBool():
function readAllBools (line 264) | def readAllBools():
function readString (line 283) | def readString():
function readAllStrings (line 298) | def readAllStrings():
function hasNextLine (line 311) | def hasNextLine():
function readLine (line 332) | def readLine():
function readAllLines (line 349) | def readAllLines():
function readAll (line 362) | def readAll():
function _testWrite (line 379) | def _testWrite():
function _main (line 398) | def _main():
FILE: itu/algs4/stdlib/stdrandom.py
function seed (line 17) | def seed(i=None):
function uniform (line 31) | def uniform(hi):
function uniformInt (line 37) | def uniformInt(lo, hi):
function uniformFloat (line 45) | def uniformFloat(lo, hi):
function bernoulli (line 53) | def bernoulli(p=0.5):
function binomial (line 61) | def binomial(n, p=0.5):
function gaussian (line 74) | def gaussian(mean=0.0, stddev=1.0):
function discrete (line 98) | def discrete(a):
function shuffle (line 116) | def shuffle(a):
function exp (line 133) | def exp(lambd):
function _main (line 146) | def _main():
FILE: itu/algs4/stdlib/stdstats.py
function mean (line 45) | def mean(a):
function var (line 53) | def var(a):
function stddev (line 65) | def stddev(a):
function median (line 73) | def median(a):
function plotPoints (line 87) | def plotPoints(a):
function plotLines (line 99) | def plotLines(a):
function plotBars (line 111) | def plotBars(a):
function _main (line 122) | def _main():
FILE: itu/algs4/strings/boyer_moore.py
class BoyerMoore (line 7) | class BoyerMoore:
method __init__ (line 16) | def __init__(self, pat):
method search (line 29) | def search(self, txt):
function main (line 57) | def main():
FILE: itu/algs4/strings/huffman_compression.py
class _Node (line 21) | class _Node:
method __init__ (line 22) | def __init__(self, ch, freq, left, right):
method is_leaf (line 28) | def is_leaf(self):
method __gt__ (line 34) | def __gt__(self, that):
function compress (line 38) | def compress():
function _build_trie (line 70) | def _build_trie(freq):
function _write_trie (line 91) | def _write_trie(x):
function _build_code (line 102) | def _build_code(st, x, s):
function expand (line 110) | def expand():
function _read_trie (line 128) | def _read_trie():
function main (line 136) | def main():
FILE: itu/algs4/strings/kmp.py
class KMP (line 16) | class KMP:
method __init__ (line 17) | def __init__(self, pat):
method search (line 36) | def search(self, txt):
function main (line 58) | def main():
FILE: itu/algs4/strings/lsd.py
function sort (line 13) | def sort(a, w, radix=256):
FILE: itu/algs4/strings/lzw.py
function compress (line 23) | def compress():
function expand (line 44) | def expand():
function main (line 75) | def main():
FILE: itu/algs4/strings/msd.py
function _less (line 16) | def _less(a, b, d):
function _insertion (line 21) | def _insertion(a, lo, hi, d):
function _sort (line 30) | def _sort(a, lo, hi, d, aux, radix):
function sort (line 60) | def sort(a, radix=256):
FILE: itu/algs4/strings/nfa.py
class NFA (line 13) | class NFA:
method __init__ (line 34) | def __init__(self, regex):
method recognizes (line 70) | def recognizes(self, txt):
function main (line 111) | def main():
FILE: itu/algs4/strings/quick3string.py
function sort (line 9) | def sort(a):
function _sort (line 18) | def _sort(a, lo, hi, d):
function _char_at (line 42) | def _char_at(s, d):
function _show (line 49) | def _show(a):
function is_sorted (line 54) | def is_sorted(a):
function _less (line 67) | def _less(v, w):
function _exch (line 71) | def _exch(a, i, j):
function main (line 77) | def main():
FILE: itu/algs4/strings/rabin_karp.py
function _rabin_miller (line 10) | def _rabin_miller(n):
function _is_prime (line 35) | def _is_prime(n):
function long_random_prime (line 219) | def long_random_prime(k):
class RabinKarp (line 239) | class RabinKarp:
method __init__ (line 248) | def __init__(self, pat):
method search (line 262) | def search(self, txt):
method _check (line 288) | def _check(self, i):
method _hash (line 293) | def _hash(self, key, M):
function main (line 301) | def main():
FILE: itu/algs4/strings/trie_st.py
class TrieST (line 42) | class TrieST(object):
class Node (line 46) | class Node(object):
method __init__ (line 49) | def __init__(self):
method __init__ (line 53) | def __init__(self):
method get (line 63) | def get(self, key):
method contains (line 73) | def contains(self, key):
method _get (line 76) | def _get(self, x, key, d):
method put (line 91) | def put(self, key, val):
method _put (line 97) | def _put(self, x, key, val, d):
method size (line 110) | def size(self):
method __len__ (line 113) | def __len__(self):
method is_empty (line 118) | def is_empty(self):
method keys (line 126) | def keys(self):
method keys_with_prefix (line 134) | def keys_with_prefix(self, prefix):
method _collect (line 140) | def _collect(self, x, prefix, results):
method keys_that_match (line 154) | def keys_that_match(self, pattern):
method _collect_match (line 159) | def _collect_match(self, x, prefix, pattern, results):
method longest_prefix_of (line 181) | def longest_prefix_of(self, query):
method _longest_prefix_of (line 193) | def _longest_prefix_of(self, x, query, d, length):
method delete (line 207) | def delete(self, key):
method _delete (line 210) | def _delete(self, x, key, d):
function test (line 230) | def test():
FILE: itu/algs4/strings/tst.py
class TST (line 40) | class TST(object):
class Node (line 41) | class Node:
method __init__ (line 42) | def __init__(self):
method __init__ (line 49) | def __init__(self):
method size (line 54) | def size(self):
method __len__ (line 57) | def __len__(self):
method contains (line 65) | def contains(self, key):
method get (line 77) | def get(self, key):
method _get (line 92) | def _get(self, x, key, d):
method put (line 114) | def put(self, key, val):
method _put (line 123) | def _put(self, x, key, val, d):
method longest_prefix_of (line 146) | def longest_prefix_of(self, query):
method keys (line 172) | def keys(self):
method keys_with_prefix (line 183) | def keys_with_prefix(self, prefix):
method _collect (line 198) | def _collect(self, x, prefix, queue):
method keys_that_match (line 213) | def keys_that_match(self, pattern):
method _collect_match (line 218) | def _collect_match(self, x, prefix, i, pattern, queue):
function test (line 234) | def test():
FILE: tests/test_bst.py
class TestBSTMethods (line 8) | class TestBSTMethods(unittest.TestCase):
method setUp (line 9) | def setUp(self):
method test_empty (line 12) | def test_empty(self):
method test_size (line 17) | def test_size(self):
method test_floor_and_ceiling (line 32) | def test_floor_and_ceiling(self):
method test_rank_select (line 44) | def test_rank_select(self):
method test_exceptions (line 52) | def test_exceptions(self):
class LargerBSTMethods (line 64) | class LargerBSTMethods(unittest.TestCase):
method setUp (line 67) | def setUp(self):
method test_put_and_get (line 72) | def test_put_and_get(self):
method test_keys (line 84) | def test_keys(self):
method test_min (line 90) | def test_min(self):
method test_max (line 93) | def test_max(self):
method test_delete_min (line 96) | def test_delete_min(self):
method test_delete_max (line 100) | def test_delete_max(self):
method test_range (line 104) | def test_range(self):
class HugeBSTMethods (line 112) | class HugeBSTMethods(unittest.TestCase):
method setUp (line 113) | def setUp(self):
method test_put_and_get (line 122) | def test_put_and_get(self):
method test_keys (line 131) | def test_keys(self):
method test_min (line 137) | def test_min(self):
method test_max (line 140) | def test_max(self):
method test_delete_min (line 143) | def test_delete_min(self):
method test_delete_max (line 147) | def test_delete_max(self):
method test_min_priority_queue (line 151) | def test_min_priority_queue(self):
method test_max_priority_queue (line 158) | def test_max_priority_queue(self):
FILE: tests/test_red_black_bst.py
class TestRedBlackBSTMethods (line 8) | class TestRedBlackBSTMethods(unittest.TestCase):
method setUp (line 9) | def setUp(self):
method test_empty (line 12) | def test_empty(self):
method test_size (line 17) | def test_size(self):
method test_rank_select (line 32) | def test_rank_select(self):
method test_floor_and_ceiling (line 40) | def test_floor_and_ceiling(self):
method test_exceptions (line 52) | def test_exceptions(self):
class LargerRedBlackBSTMethods (line 68) | class LargerRedBlackBSTMethods(unittest.TestCase):
method setUp (line 71) | def setUp(self):
method test_put_and_get (line 76) | def test_put_and_get(self):
method test_keys (line 88) | def test_keys(self):
method test_min (line 94) | def test_min(self):
method test_max (line 97) | def test_max(self):
method test_delete_min (line 100) | def test_delete_min(self):
method test_delete_max (line 104) | def test_delete_max(self):
method test_range (line 108) | def test_range(self):
class HugeRedBlackBSTMethods (line 116) | class HugeRedBlackBSTMethods(unittest.TestCase):
method setUp (line 117) | def setUp(self):
method test_put_and_get (line 126) | def test_put_and_get(self):
method test_keys (line 135) | def test_keys(self):
method test_min (line 141) | def test_min(self):
method test_max (line 144) | def test_max(self):
method test_delete_min (line 147) | def test_delete_min(self):
method test_delete_max (line 151) | def test_delete_max(self):
method test_min_priority_queue (line 155) | def test_min_priority_queue(self):
method test_max_priority_queue (line 162) | def test_max_priority_queue(self):
method test_flights (line 169) | def test_flights(self):
FILE: tests/test_stack.py
function test_is_empty (line 18) | def test_is_empty(stack):
function test_push_pop_once (line 26) | def test_push_pop_once(stack):
function test_error_beyond_capacity (line 34) | def test_error_beyond_capacity(capacity):
function test_random_pushpop_sequence (line 49) | def test_random_pushpop_sequence(stack, seed):
FILE: tests/test_symbol_tables.py
function test_is_empty (line 28) | def test_is_empty(st):
function test_delete (line 36) | def test_delete(st):
function old_tests (line 50) | def old_tests(st):
Condensed preview — 133 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (550K chars).
[
{
"path": ".github/workflows/check.yml",
"chars": 943,
"preview": "name: check\n\non: [push, pull_request]\n\njobs:\n build:\n runs-on: ubuntu-latest\n strategy:\n max-parallel: 4\n "
},
{
"path": ".github/workflows/python_publish.yml",
"chars": 707,
"preview": "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"
},
{
"path": ".gitignore",
"chars": 91,
"preview": "*.pyc\n.vs/\nalgs4-data/\n.mypy_cache\n.pytest_cache\n.ruff_cache\nitu.algs4.egg-info\n__pycache__"
},
{
"path": "CONTRIBUTING.md",
"chars": 2981,
"preview": "# Development\n\n## Testing\n\nBefore you can run tests, you should clone the repository, and install the\npackage in \"editab"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 8662,
"preview": "# Algs4 library for Python 3\n\n`itu.algs4` is a Python 3 port of the Java code in [Algorithms, 4th Edition](https://algs4"
},
{
"path": "create_html_doc.sh",
"chars": 658,
"preview": "DIR=~/WorkSpace/bads-code/AlgorithmsInPython/algs4/\nDEST=/home/rikj/WorkSpace/riko/html_templ_tum/itu_dest/AlgorithmsInP"
},
{
"path": "docs/conf.py",
"chars": 1912,
"preview": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common op"
},
{
"path": "docs/index.rst",
"chars": 641,
"preview": ".. itu.algs4 documentation master file, created by\n sphinx-quickstart on Mon Jul 6 13:50:43 2020.\n You can adapt th"
},
{
"path": "docs/requirements.txt",
"chars": 31,
"preview": "pygame\ntyping_extensions\ncolor\n"
},
{
"path": "docs/source/itu.algs4.errors.rst",
"chars": 353,
"preview": "itu.algs4.errors package\n========================\n\nSubmodules\n----------\n\nitu.algs4.errors.errors module\n---------------"
},
{
"path": "docs/source/itu.algs4.fundamentals.rst",
"chars": 2053,
"preview": "itu.algs4.fundamentals package\n==============================\n\nSubmodules\n----------\n\nitu.algs4.fundamentals.bag module\n"
},
{
"path": "docs/source/itu.algs4.graphs.rst",
"chars": 6457,
"preview": "itu.algs4.graphs package\n========================\n\nSubmodules\n----------\n\nitu.algs4.graphs.Arbitrage module\n------------"
},
{
"path": "docs/source/itu.algs4.rst",
"chars": 357,
"preview": "itu.algs4 package\n=================\n\nSubpackages\n-----------\n\n.. toctree::\n :maxdepth: 4\n\n itu.algs4.errors\n itu.a"
},
{
"path": "docs/source/itu.algs4.searching.rst",
"chars": 2645,
"preview": "itu.algs4.searching package\n===========================\n\nSubmodules\n----------\n\nitu.algs4.searching.binary\\_search\\_st m"
},
{
"path": "docs/source/itu.algs4.sorting.rst",
"chars": 2056,
"preview": "itu.algs4.sorting package\n=========================\n\nSubmodules\n----------\n\nitu.algs4.sorting.heap module\n--------------"
},
{
"path": "docs/source/itu.algs4.stdlib.rst",
"chars": 2348,
"preview": "itu.algs4.stdlib package\n========================\n\nSubmodules\n----------\n\nitu.algs4.stdlib.binary\\_out module\n----------"
},
{
"path": "docs/source/itu.algs4.strings.rst",
"chars": 2010,
"preview": "itu.algs4.strings package\n=========================\n\nSubmodules\n----------\n\nitu.algs4.strings.boyer\\_moore module\n------"
},
{
"path": "examples/bst.py",
"chars": 659,
"preview": "#!/usr/bin/env python3\nimport sys\n\nfrom itu.algs4.searching.bst import BST\nfrom itu.algs4.stdlib import stdio\n\nif __name"
},
{
"path": "examples/hello_world.py",
"chars": 89,
"preview": "#!/usr/bin/env python3\nfrom itu.algs4.stdlib import stdio\n\nstdio.write(\"Hello World!\\n\")\n"
},
{
"path": "examples/queue.py",
"chars": 551,
"preview": "#!/usr/bin/env python3\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.stdlib import stdio\n\n\"\"\"\nReads stri"
},
{
"path": "examples/sort-numbers.py",
"chars": 344,
"preview": "#!/usr/bin/env python3\nfrom itu.algs4.sorting import merge\nfrom itu.algs4.stdlib import stdio\n\n\"\"\"\nReads a list of integ"
},
{
"path": "examples/stack.py",
"chars": 526,
"preview": "#!/usr/bin/env python3\nimport sys\n\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.stdlib import stdio\n\nif"
},
{
"path": "itu/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "itu/algs4/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "itu/algs4/errors/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "itu/algs4/errors/errors.py",
"chars": 228,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\nclass NoSuchElementException(Exception):\n pass\n\n\ncla"
},
{
"path": "itu/algs4/fundamentals/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "itu/algs4/fundamentals/bag.py",
"chars": 2868,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\n# See ResizingArrayBag for a version that use"
},
{
"path": "itu/algs4/fundamentals/binary_search.py",
"chars": 1354,
"preview": "import sys\nfrom typing import List, TypeVar\n\nfrom itu.algs4.stdlib import stdio\n\nT = TypeVar(\"T\")\n\n# Created for BADS 20"
},
{
"path": "itu/algs4/fundamentals/evaluate.py",
"chars": 1371,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nimport math\nimport sys\n\nfrom itu.algs4.fundamentals.stac"
},
{
"path": "itu/algs4/fundamentals/java_helper.py",
"chars": 625,
"preview": "# Created for BADS 2018\n# See README.md for details\n# this one is not inspired by algorithms from the book, but useful f"
},
{
"path": "itu/algs4/fundamentals/queue.py",
"chars": 3538,
"preview": "from typing import Generic, Iterator, Optional, TypeVar\n\nfrom ..errors.errors import NoSuchElementException\n\n# Created f"
},
{
"path": "itu/algs4/fundamentals/stack.py",
"chars": 5083,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nfrom typing import Generic, Iterator, List, Optional, Ty"
},
{
"path": "itu/algs4/fundamentals/three_sum.py",
"chars": 338,
"preview": "class ThreeSum:\n @staticmethod\n def count(a):\n # Count triples that sum to 0\n n = len(a)\n cou"
},
{
"path": "itu/algs4/fundamentals/three_sum_fast.py",
"chars": 380,
"preview": "from itu.algs4.fundamentals import binary_search\n\n\nclass ThreeSumFast:\n @staticmethod\n def count(a):\n # Cou"
},
{
"path": "itu/algs4/fundamentals/two_sum_fast.py",
"chars": 328,
"preview": "from itu.algs4.fundamentals import binary_search\n\n\nclass TwoSumFast:\n @staticmethod\n def count(a):\n # Count"
},
{
"path": "itu/algs4/fundamentals/uf.py",
"chars": 12098,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"The UF module implements several versions of the unio"
},
{
"path": "itu/algs4/graphs/Arbitrage.py",
"chars": 1725,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nimport math\nimport sys\n\nfrom itu.algs4.graphs.bellman_fo"
},
{
"path": "itu/algs4/graphs/CPM.py",
"chars": 2128,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nimport sys\n\nfrom itu.algs4.graphs.acyclic_lp import Acyc"
},
{
"path": "itu/algs4/graphs/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "itu/algs4/graphs/acyclic_lp.py",
"chars": 4088,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nimport sys\n\nfrom itu.algs4.fundamentals.stack import Sta"
},
{
"path": "itu/algs4/graphs/acyclic_sp.py",
"chars": 4291,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nimport math\n\nfrom itu.algs4.fundamentals.stack im"
},
{
"path": "itu/algs4/graphs/bellman_ford_sp.py",
"chars": 9986,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.errors.errors import (\n Ill"
},
{
"path": "itu/algs4/graphs/bipartite.py",
"chars": 5547,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.stack import Stack\nfr"
},
{
"path": "itu/algs4/graphs/breadth_first_paths.py",
"chars": 7831,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nimport math\n\nfrom itu.algs4.fundamentals.queue im"
},
{
"path": "itu/algs4/graphs/cc.py",
"chars": 5051,
"preview": "# 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 "
},
{
"path": "itu/algs4/graphs/cycle.py",
"chars": 3658,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.stack import Stack\n\n\n"
},
{
"path": "itu/algs4/graphs/degrees_of_separation.py",
"chars": 2601,
"preview": "from itu.algs4.graphs.breadth_first_paths import BreadthFirstPaths\nfrom itu.algs4.graphs.symbol_graph import SymbolGraph"
},
{
"path": "itu/algs4/graphs/depth_first_order.py",
"chars": 4490,
"preview": "from itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.digr"
},
{
"path": "itu/algs4/graphs/depth_first_paths.py",
"chars": 3183,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.stack import Stack\n\n\n"
},
{
"path": "itu/algs4/graphs/depth_first_search.py",
"chars": 2529,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\n\nclass DepthFirstSearch:\n \"\"\"The DepthFirstSea"
},
{
"path": "itu/algs4/graphs/digraph.py",
"chars": 5967,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module implements the directed graph data struct"
},
{
"path": "itu/algs4/graphs/dijkstra_all_pairs_sp.py",
"chars": 3461,
"preview": "# 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 a"
},
{
"path": "itu/algs4/graphs/dijkstra_sp.py",
"chars": 4896,
"preview": "import sys\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\nfrom itu.algs4.fundamentals.stack import Stack\n"
},
{
"path": "itu/algs4/graphs/dijkstra_undirected_sp.py",
"chars": 4738,
"preview": "import sys\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\nfrom itu.algs4.fundamentals.stack import Stack\n"
},
{
"path": "itu/algs4/graphs/directed_cycle.py",
"chars": 3335,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module implements the directed cycle algorithm d"
},
{
"path": "itu/algs4/graphs/directed_dfs.py",
"chars": 2647,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport sys\n\nfrom itu.algs4.fundamentals.bag import"
},
{
"path": "itu/algs4/graphs/directed_edge.py",
"chars": 2247,
"preview": "import math\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\n\n# Created for BADS 2018\n# See README.md for d"
},
{
"path": "itu/algs4/graphs/edge.py",
"chars": 3119,
"preview": "import math\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\n\n# Created for BADS 2018\n# See README.md for d"
},
{
"path": "itu/algs4/graphs/edge_weighted_digraph.py",
"chars": 6800,
"preview": "import sys\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\nfrom itu.algs4.fundamentals.bag import Bag\nfrom"
},
{
"path": "itu/algs4/graphs/edge_weighted_directed_cycle.py",
"chars": 5034,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.fundamentals.stack import Stac"
},
{
"path": "itu/algs4/graphs/edge_weighted_directed_cycle_anton.py",
"chars": 3628,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module implements the directed cycle algorithm f"
},
{
"path": "itu/algs4/graphs/edge_weighted_graph.py",
"chars": 6269,
"preview": "import sys\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\nfrom itu.algs4.fundamentals.bag import Bag\nfrom"
},
{
"path": "itu/algs4/graphs/graph.py",
"chars": 5414,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.bag import Bag\nfrom i"
},
{
"path": "itu/algs4/graphs/kosaraju_sharir_scc.py",
"chars": 4229,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"\n * Execution: python kosaraju_sharir_scc.py file"
},
{
"path": "itu/algs4/graphs/kruskal_mst.py",
"chars": 2754,
"preview": "import sys\n\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.fundamentals.uf import WeightedQuickUnionUF\nfr"
},
{
"path": "itu/algs4/graphs/lazy_prim_mst.py",
"chars": 5543,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.queue import Queue\nfr"
},
{
"path": "itu/algs4/graphs/prim_mst.py",
"chars": 5716,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\nimport math\nimport sys\n\nfrom itu.algs4.fundamental"
},
{
"path": "itu/algs4/graphs/symbol_digraph.py",
"chars": 4187,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.graphs.digraph import Digraph\nfrom"
},
{
"path": "itu/algs4/graphs/symbol_graph.py",
"chars": 4157,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.graphs.graph import Graph\nfrom itu"
},
{
"path": "itu/algs4/graphs/topological.py",
"chars": 3885,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\"\"\"This module implements the topological order algorithm"
},
{
"path": "itu/algs4/graphs/transitive_closure.py",
"chars": 2987,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"\n * Execution: python transitive_closure.py filen"
},
{
"path": "itu/algs4/searching/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "itu/algs4/searching/binary_search_st.py",
"chars": 12531,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.queue import Queue\n\n\n"
},
{
"path": "itu/algs4/searching/bst.py",
"chars": 14002,
"preview": "# Created for BADS 2018\n# see README.md for details\n# Python 3\n\nimport sys\nfrom abc import abstractmethod\nfrom typing im"
},
{
"path": "itu/algs4/searching/file_index.py",
"chars": 1344,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.stdlib import stdio\n\n# Execut"
},
{
"path": "itu/algs4/searching/frequency_counter.py",
"chars": 1772,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.stdlib import stdio\n\n# Execut"
},
{
"path": "itu/algs4/searching/linear_probing_hst.py",
"chars": 6987,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\nimport sys\n\n\nclass LinearProbingHashST:\n \"\"\"Th"
},
{
"path": "itu/algs4/searching/lookup_csv.py",
"chars": 2388,
"preview": "# 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 fi"
},
{
"path": "itu/algs4/searching/lookup_index.py",
"chars": 2092,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.fundamentals.queue import Queu"
},
{
"path": "itu/algs4/searching/red_black_bst.py",
"chars": 22217,
"preview": "from abc import abstractmethod\nfrom typing import Generic, Optional, TypeVar\n\nfrom typing_extensions import Protocol\n\nfr"
},
{
"path": "itu/algs4/searching/seperate_chaining_hst.py",
"chars": 4673,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport sys\n\nfrom itu.algs4.searching.sequential_se"
},
{
"path": "itu/algs4/searching/sequential_search_st.py",
"chars": 5251,
"preview": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\n\nclass SequentialSearchST:\n \"\"\"The Sequential"
},
{
"path": "itu/algs4/searching/set.py",
"chars": 6072,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nfrom itu.algs4.errors.errors import (\n IllegalArgumen"
},
{
"path": "itu/algs4/searching/sparse_vector.py",
"chars": 4599,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nfrom math import sqrt\n\nfrom itu.algs4.searching.se"
},
{
"path": "itu/algs4/searching/st.py",
"chars": 3683,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nfrom itu.algs4.errors.errors import IllegalArgumentExcept"
},
{
"path": "itu/algs4/sorting/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "itu/algs4/sorting/datafiles/tiny.txt",
"chars": 22,
"preview": "S O R T E X A M P L E\n"
},
{
"path": "itu/algs4/sorting/datafiles/words3.txt",
"chars": 141,
"preview": "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"
},
{
"path": "itu/algs4/sorting/heap.py",
"chars": 1919,
"preview": "# 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 "
},
{
"path": "itu/algs4/sorting/index_min_pq.py",
"chars": 10570,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nfrom itu.algs4.errors.errors import IllegalArgumentExcep"
},
{
"path": "itu/algs4/sorting/insertion_sort.py",
"chars": 1752,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The Insertion module provides static methods fo"
},
{
"path": "itu/algs4/sorting/max_pq.py",
"chars": 5468,
"preview": "# Created for BADS 2018\n# see README.md for details\n# Python 3\n\nfrom typing import Generic, Iterator, List, Optional, Ty"
},
{
"path": "itu/algs4/sorting/merge.py",
"chars": 2440,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nfrom typing import List, Optional\n\n\"\"\"\nThis module provi"
},
{
"path": "itu/algs4/sorting/merge_bu.py",
"chars": 2067,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module provides functions for sorting an array u"
},
{
"path": "itu/algs4/sorting/min_pq.py",
"chars": 5355,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nfrom typing import Generic, List, Optional, TypeVa"
},
{
"path": "itu/algs4/sorting/quick3way.py",
"chars": 1624,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The Quick3Way module provides static methods fo"
},
{
"path": "itu/algs4/sorting/quicksort.py",
"chars": 3099,
"preview": "# Created for BADS 2018\n# see README.md for details\n# Python 3\n\n\"\"\"The quicksort module provides methods for sorting an "
},
{
"path": "itu/algs4/sorting/selection.py",
"chars": 1079,
"preview": "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 mo"
},
{
"path": "itu/algs4/sorting/shellsort.py",
"chars": 1465,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The Shellsort module provides static methods fo"
},
{
"path": "itu/algs4/stdlib/__init__.py",
"chars": 150,
"preview": "\"\"\"This module is based on the code at\nhttps://introcs.cs.princeton.edu/python/code/ written by Robert Sedgewick,\nKevin "
},
{
"path": "itu/algs4/stdlib/binary_out.py",
"chars": 2568,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport struct\nimport sys\n\n\"\"\"\nBinary output. This "
},
{
"path": "itu/algs4/stdlib/binary_stdin.py",
"chars": 3351,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport struct\nimport sys\n\nfrom itu.algs4.stdlib.bi"
},
{
"path": "itu/algs4/stdlib/binary_stdout.py",
"chars": 3876,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport struct\nimport sys\n\n\"\"\"\nBinary standard outp"
},
{
"path": "itu/algs4/stdlib/color.py",
"chars": 2741,
"preview": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"color.py.\n\n"
},
{
"path": "itu/algs4/stdlib/instream.py",
"chars": 11562,
"preview": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"instream.py"
},
{
"path": "itu/algs4/stdlib/outstream.py",
"chars": 2577,
"preview": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"outstream.p"
},
{
"path": "itu/algs4/stdlib/picture.py",
"chars": 4145,
"preview": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"picture.py."
},
{
"path": "itu/algs4/stdlib/stdarray.py",
"chars": 5328,
"preview": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stdarray.py"
},
{
"path": "itu/algs4/stdlib/stdaudio.py",
"chars": 5867,
"preview": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stdaudio.py"
},
{
"path": "itu/algs4/stdlib/stddraw.py",
"chars": 24460,
"preview": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stddraw.py."
},
{
"path": "itu/algs4/stdlib/stdio.py",
"chars": 11042,
"preview": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stdio.py.\n\n"
},
{
"path": "itu/algs4/stdlib/stdrandom.py",
"chars": 4427,
"preview": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stdrandom.p"
},
{
"path": "itu/algs4/stdlib/stdstats.py",
"chars": 3318,
"preview": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stdstats.py"
},
{
"path": "itu/algs4/strings/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "itu/algs4/strings/boyer_moore.py",
"chars": 2067,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport sys\n\n\nclass BoyerMoore:\n \"\"\"The BoyerMoo"
},
{
"path": "itu/algs4/strings/huffman_compression.py",
"chars": 4201,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The Huffman compression module provides static "
},
{
"path": "itu/algs4/strings/kmp.py",
"chars": 2269,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\n\"\"\"\nThe KMP (Knuth-Morris-Pratt) class finds the "
},
{
"path": "itu/algs4/strings/lsd.py",
"chars": 1536,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module provides functions for sorting arrays of "
},
{
"path": "itu/algs4/strings/lzw.py",
"chars": 2365,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The LSW module provides static methods for comp"
},
{
"path": "itu/algs4/strings/msd.py",
"chars": 2025,
"preview": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module provides functions for sorting arrays of "
},
{
"path": "itu/algs4/strings/nfa.py",
"chars": 4004,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\nimport sys\n\nfrom itu.algs4.fundamentals.bag impor"
},
{
"path": "itu/algs4/strings/quick3string.py",
"chars": 1593,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The Quick3String module provides functions for "
},
{
"path": "itu/algs4/strings/rabin_karp.py",
"chars": 6519,
"preview": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport math\nimport random\n\n\n# The following part i"
},
{
"path": "itu/algs4/strings/trie_st.py",
"chars": 8970,
"preview": "# created for BADS 2018\n# See README.md for details\n# Python 3\n\nimport sys\n\nfrom itu.algs4.fundamentals.queue import Que"
},
{
"path": "itu/algs4/strings/tst.py",
"chars": 9386,
"preview": "# created for BADS 2018\n# see README.md for details\n# Python 3\n\nimport sys\n\nfrom itu.algs4.fundamentals.queue import Que"
},
{
"path": "setup.cfg",
"chars": 739,
"preview": "[flake8]\nignore = E203, E266, E501, W503\nmax-line-length = 88\nmax-complexity = 18\nselect = B,C,E,F,W,T4\n\n[isort]\nmulti_l"
},
{
"path": "setup.py",
"chars": 1391,
"preview": "from setuptools import find_packages, setup\n\nsetup(\n name=\"itu.algs4\",\n version=\"0.2.5\",\n description='Python 3"
},
{
"path": "tests/test_bst.py",
"chars": 4751,
"preview": "import random\nimport unittest\n\nfrom itu.algs4.errors.errors import NoSuchElementException\nfrom itu.algs4.searching.bst i"
},
{
"path": "tests/test_red_black_bst.py",
"chars": 5919,
"preview": "import random\nimport unittest\n\nfrom itu.algs4.errors.errors import NoSuchElementException\nfrom itu.algs4.searching.red_b"
},
{
"path": "tests/test_stack.py",
"chars": 1320,
"preview": "import random\n\nimport pytest\n\nfrom itu.algs4.fundamentals.stack import FixedCapacityStack, ResizingArrayStack, Stack\n\n\n@"
},
{
"path": "tests/test_symbol_tables.py",
"chars": 1725,
"preview": "# import random\n#\nimport pytest\n\nfrom itu.algs4.searching.binary_search_st import BinarySearchST\nfrom itu.algs4.searchin"
}
]
About this extraction
This page contains the full source code of the itu-algorithms/itu.algs4 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 133 files (507.2 KB), approximately 131.1k tokens, and a symbol index with 969 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.