Repository: AsciiKay/Beginners-Python-Examples
Branch: master
Commit: 37af7e647f3f
Files: 191
Total size: 201.1 KB
Directory structure:
gitextract_3zhv_6_4/
├── CONTRIBUTING.md
├── Display ASCII Value of a Character.py
├── Double the number pattern
├── Drawing_With_Turtle.py
├── LICENSE
├── Medium level python program
├── Pattern Program
├── Pattern Python Program
├── README.md
├── Turtle_Drawing.py
├── _config.yml
├── algorithms/
│ ├── README.md
│ ├── analysis/
│ │ ├── README.md
│ │ ├── bigo_notation.py
│ │ ├── count.py
│ │ ├── enum.py
│ │ ├── length.py
│ │ ├── max.py
│ │ ├── mean.py
│ │ ├── median.py
│ │ ├── min.py
│ │ ├── mode.py
│ │ ├── sort.py
│ │ ├── sum.py
│ │ └── useful_function_mapping.py
│ ├── numbers/
│ │ ├── README.md
│ │ ├── binary_to_decimal_converter.py
│ │ ├── collatz_sequence.py
│ │ ├── compare_array_elements.py
│ │ └── factorial.py
│ ├── searching/
│ │ └── binary_search.py
│ ├── sorting/
│ │ ├── README.md
│ │ ├── bubble_sort.py
│ │ ├── insertion_sort.py
│ │ └── selection_sort.py
│ └── string/
│ ├── README.md
│ ├── caesars_cipher_encryption.py
│ ├── check_anagram.py
│ ├── is_palindrome.py
│ ├── is_palindrome_two_liner.py
│ └── vowel_count.py
├── ansi-colors.py
├── armstrong_number.py
├── bell_number.py
├── bigo_notation.py
├── bubble sort.py
├── cartesian_plane_quadrant.py
├── client_file.py
├── conways.py
├── count_algorithm_execution_time.py
├── days_you_lived.py
├── deMorgans_law.py
├── decimal_to_binary_converter.py
├── decrypting_caesars_cipher.py
├── dictionary.py
├── difference_testing.py
├── discount.py
├── discountPercent.py
├── distance_on_number_line.py
├── euclids_algorithm.py
├── factorial.py
├── figure determiner.py
├── findLcm.py
├── find_cube_root.py
├── find_roots.py
├── find_square_root.py
├── find_square_root_of_imperfect_square.py
├── geometric_progression_builder.py
├── healthScore.py
├── hello_world.py
├── html_source.py
├── identity_matrix_recognizer.py
├── image_downloader.py
├── in_the_something.py
├── item_index.py
├── kay_sort.py
├── lessThanMoreThan.py
├── linear_search.py
├── listOperations.py
├── listOperationsMethods.py
├── listReverse.py
├── list_comprehensions.py
├── logarithm_integer.py
├── madLibs.py
├── magicball_8.py
├── map_example.py
├── math/
│ ├── Binary_to_decimal
│ ├── FreefallCalculator
│ ├── README.md
│ ├── aircraft_thrust.py
│ ├── area_volume_calculator.py
│ ├── arithmetic_progression_builder.py
│ ├── calculator.py
│ ├── decimal_to_binary_converter.py
│ ├── eulers_python.py
│ ├── geoMean.py
│ └── number_lesser_greater.py
├── mathoperators.py
├── max_by_alphabetical_order.py
├── max_int_in_list.py
├── min_by_alphabetical_order.py
├── min_int_in_list.py
├── mod_example.py
├── modified_selection_sort.py
├── morse_code_decoder.py
├── multiplicationTables.py
├── my_name.py
├── nearest_square_and_its_root.py
├── network/
│ └── are_you_connected_to_world.py
├── newOnContacts.py
├── non_multiples.py
├── ordered_binary_search.py
├── otherAngle.py
├── password_creator.py
├── percentageCalc.py
├── percentage_increase_decrease.py
├── physics.py
├── pigLatin.py
├── piggyBank.py
├── ping_host.py
├── primeNumbers.py
├── profitLoss.py
├── pyKeywords.py
├── pythagoras.py
├── python_files_compiler.py
├── randomModule.py
├── readFiles.py
├── reverse_sort.py
├── rock,paper,scissor.py
├── selection_sort.py
├── sendingEmailsInPython.py
├── server_file.py
├── shell_games/
│ ├── README.md
│ ├── battleship.py
│ ├── battleship_info.txt
│ ├── dice_rolling_simulator.py
│ ├── dice_rolling_simulator_info.txt
│ └── number_guessing_game.py
├── simple_scripts/
│ ├── ListExample.py
│ ├── README.md
│ ├── args_example.py
│ ├── args_example_1.py
│ ├── class_animal_attributes_examples.py
│ ├── class_example_movies.py
│ ├── class_movies.py
│ ├── conditionals_examples.py
│ ├── for_loop_fibonnaci
│ ├── for_loop_mountain.py
│ ├── personality_teller.py
│ ├── unicode.py
│ └── website_opener.py
├── sleepWellAlarm.py
├── snake game/
│ ├── .idea/
│ │ ├── .gitignore
│ │ ├── inspectionProfiles/
│ │ │ └── profiles_settings.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ └── snake game.iml
│ ├── index.html
│ └── main.py
├── snake_game.py
├── sortString.py
├── sortingFunctions.py
├── squareTurtle.py
├── square_root_algorithm.py
├── squarecube.py
├── star_turtle.py
├── stringIndexing.py
├── stringOperations.py
├── stringReverse.py
├── sumAverage.py
├── sum_array.py
├── sum_of_arithmetic_sequence.py
├── swap_case.py
├── systemInfo.py
├── table_maker.py
├── take-a-break.py
├── testofdivisibility.py
├── time_conversion.py
├── tuplesExample.py
├── turtleRandomWeb.py
├── useful_scripts/
│ ├── Diffe_Hellman.py
│ ├── binary_to_decimal_conversion.py
│ ├── bmi_body_mass_index_calculator.py
│ ├── caesars_cipher_encryption.py
│ ├── calculator.py
│ ├── calendar.py
│ ├── password_generator.py
│ ├── pinger.py
│ └── timer.py
├── videodownloader.py
└── writingFiles.py
================================================
FILE CONTENTS
================================================
================================================
FILE: CONTRIBUTING.md
================================================
# What You Waiting For Fork it!
Feel free to fork the repository and make changes!
If you feel there is need to change something pull request!
I'll check and review the changed program if it adds any value to the repo i'll definitely merge it!
================================================
FILE: Display ASCII Value of a Character.py
================================================
# ASCII Value of Character
# Simply ender a character from the keyboard
user_input = input('Give me a character: ')
# Print the ASCII value of assigned character
print("The ASCII value of '" + user_input + "' is", ord(user_input))
================================================
FILE: Double the number pattern
================================================
rows = 9
for i in range(1, rows):
for j in range(-1+i, -1, -1):
print(format(2**j, "4d"), end=' ')
print("")
================================================
FILE: Drawing_With_Turtle.py
================================================
#This is a example for turtle
#This shows how to draw a star
#For more tutorials visit https://www.tutorialspoint.com/turtle-programming-in-python
# import turtle library
import turtle
my_pen = turtle.Turtle()
for i in range(50):
my_pen.forward(50)
my_pen.right(144)
turtle.done()
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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.
Copyright (C)
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 .
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:
Copyright (C)
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
.
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
.
================================================
FILE: Medium level python program
================================================
rows = 6
for row in range(1, rows):
for column in range(row, 0, -1):
print(column, end=' ')
print("")
================================================
FILE: Pattern Program
================================================
rows = 6
for num in range(rows):
for i in range(num):
print(num, end=" ") # print number
print(" ")
================================================
FILE: Pattern Python Program
================================================
rows = 5
for i in range(rows, 0, -1):
num = i
for j in range(0, i):
print(num, end=' ')
print("\r")
================================================
FILE: README.md
================================================
# Beginners-Python-Programs
[18 Nov 2025] Final Update: This was my first Repo and I created it when I was fairly young and completely new to computer programming. I no longer have time to update/maintain it in anyway. Thus, starting today, This Repository will be available as a Public Archive only.
Basic python CLI programs as examples.
All the examples are useful examples.
These examples are of beginner level.
Note: In 2.x versions input isn't useful. Similarly, in 3.x versions raw_input isn't useful. Also, xrange() and other methods are discontinued or changed in 3.x versions of Python. Change the keywords accordingly.
Update: I wrote these programs when I was just starting out with programming, now I realize that many of them seem quite amateur in their rendering so I've decided to audit through all of them and update them according to my current capabilities.
Files outside particular directories have not been checked yet
Files inside, directories offer better code and explanation
Also see this : Beginners-Python-Examples/CONTRIBUTING.md
================================================
FILE: Turtle_Drawing.py
================================================
import turtle
ninja = turtle.Turtle()
ninja.speed(10)
for i in range(180):
ninja.forward(100)
ninja.right(30)
ninja.forward(20)
ninja.left(60)
ninja.forward(50)
ninja.right(30)
ninja.penup()
ninja.setposition(0, 0)
ninja.pendown()
ninja.right(2)
turtle.done()
================================================
FILE: _config.yml
================================================
theme: jekyll-theme-minimal
================================================
FILE: algorithms/README.md
================================================
'algorithms' Sub-directory contains all algorithms
further separated in different particular sub directories
The programs have been re-checked and re-mastered by me!
Although i've tried to keep it as orignal as possible.
Keep Patience It'll take time to go through every program!! Thanks
================================================
FILE: algorithms/analysis/README.md
================================================
'analysis' Sub-directory contains all
analysis related algorithms.
Thanks
================================================
FILE: algorithms/analysis/bigo_notation.py
================================================
from math import log
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('bmh')
# Set up runtime comparisons
n = np.linspace(1,10,1000)
labels = ['Constant','Logarithmic','Linear','Log Linear','Quadratic','Cubic','Exponential']
big_o = [np.ones(n.shape),np.log(n),n,n*np.log(n),n**2,n**3,2**n]
# Plot setup
plt.figure(figsize=(12,10))
plt.ylim(0,50)
for i in range(len(big_o)):
plt.plot(n,big_o[i],label = labels[i])
plt.legend(loc=0)
plt.ylabel('Relative Runtime')
plt.xlabel('n')
================================================
FILE: algorithms/analysis/count.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Simple algorithm to count
# number of occurrences of (n) in (ar)
# Sudo: Algorithm
# each time (n) is found in (ar)
# (count) varible in incremented (by 1)
# I've put spaces to separate different
# stages of algorithms for easy understanding
# however isn't a good practise
def count(ar, n):
count = 0
for element in ar:
# More complex condition could be
# => (not element != n)
if element == n:
count += 1
return count
# Testing
# add your test cases in list below
test_cases = [([1, 1, 2, 3, 5, 8, 13, 21, 1], 1), ("Captain America", "a")]
for test_case in test_cases:
print("TestCase: {}, {}".format(test_case[0], test_case[1]))
print("Results: {}\n".format(count(test_case[0], test_case[1])))
# You can add condition to check weather output is correct
# or not
================================================
FILE: algorithms/analysis/enum.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Enum function
# yields a tuple of element and it's index
def enum(ar):
for index in range(len(ar)):
yield((index, ar[index]))
# Test
case_1 = [19, 17, 20, 23, 27, 15]
for tup in list(enum(case_1)):
print(tup)
# Enum function is a generator does not
# return any value, instead generates
# tuple as it encounters element of array
# Tuples can be appended to list
# and can be returned after iteration
# However,
# Generator is a good option
================================================
FILE: algorithms/analysis/length.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import math
# Length of array(number of elements in array)
# is simple algorithm
# Iterates through array
# at each iteration (count) variable
# is incremented
#
# This solution is ideal for small array
# But not that good for bigger array's
# There are many ways to do same thing
# but always go with solution that is
# simple, and has least instructions
# for computer to execute, making
# process faster
# is_ap parameter indicates weather array
# is an arithmetic progression or not
#
# Similarly,
# is_gp indicates weather array is an geometric progression or not
# If array is either ap or gp then it's length can be
# found by derivation of it's general term formula
# e.g. ap's general term,
# tn = a + (n - 1)d
# thus, n = (tn - a) / d + 1
def length(ar, is_ap = False, is_gp = False, big_data = False, data_outline = []):
# Length of data if it is an arithmetic progression
# using derived formula, n = (tn - a) / d + 1
if is_ap:
return ((ar[-1] - ar[0]) / (ar[1] - ar[0])) + 1
# Length of data if it is an geometric progression
# using derived formula, n = ((log base 10 an / a1) / log 10 r) + 1
elif is_gp:
# length is never a float
return int(math.log10((ar[-1] / ar[0])) / math.log10((ar[1] / ar[0])) + 1)
# Length of big data using data outline
# data outline is selective elements to be counted from entire
# data
elif big_data:
count = 0
for element in data_outline:
count += ar.count(element)
return count
# Sequential counting
# of elements in array
else:
res = 0
for item in ar:
res += 1
return res
# Test
# Geometric progression Test
if length([1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096], None, is_gp = True) == 13:
print("\nLength of geometric progression: " + str(13))
print("--> geometric progression counting works!\n")
else:
print("Something's wrong with gp feature")
# Arithmetic progression test
if length([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43], is_ap = True) == 15:
print("Length of arithmetic progression: " + str(15))
print("--> arithmetic progression counting works!\n")
else:
print("Something's wrong with ap feature")
# Big data test
# Passing only useful numbers in outline array
if length([1, 1, 4, 5, 7, 1, 9, 5, 2, 4, 3, 5, 9], None, None, True, [1, 4, 5, 7, 9]) == 11:
print("Length of arithmetic progression: " + str(11))
print("--> big data counting works!\n")
else:
print("Something's wrong with ap feature")
# Small data
print("Length: " + str(length([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])))
print("Everything Works!\n")
================================================
FILE: algorithms/analysis/max.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Finds the maximum number
# in un-sorted data
# Sudo Algo:
# Iterate through data
# each time a number(say k) greater than, previous
# consideration(say p) is found, replace previous
# consideration(p) with that greater number(k)
# By this way,
# At last we get the maximum number from data
def max_(seq):
max_n = seq[0]
for item in seq[1:]:
if item > max_n:
max_n = item
return max_n
# Test
# Add your tests too!
tests = [[9017289, 782367, 736812903, 9367821, 71256716278, 676215, 2398, 0, 1],
[19208, 9239, 4376, 738, 78, 51, 5, 6, 12, 78, 123, 65765, 1999999999],
[1, 2, 4, 7, 9]]
# checking our functions results
# with python's built-in max() function
for test_i in range(len(tests)):
m = max_(tests[test_i])
if m == max(tests[test_i]):
print("Max number in array({}) -> ".format(test_i + 1) + str(m))
else:
print("Oops! Someting went wrong!")
================================================
FILE: algorithms/analysis/mean.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# f(x) = s(x) / l(x) ______(e1)
# Functions below same principle as (e1)
#
# Here,
# Mean value can be float
# 'er is need to declare float values
# Function to get mean of given args
def mean_(*args):
sum_ = 0.0
length_ = 0.0
for arg in args:
sum_ += arg
length_ += 1.0
return sum_ / length_
# Function to get mean of array
def mean_ar(ar):
return float(sum(ar))/float(len(ar))
# Another feature can be start index
# and end index of array
# Test
# First function
if mean_(12, 445, 76, 23, 7, 9, 17, 19, 100) == 78.66666666666667:
print("First Function Works!")
# Second function
if mean_ar([12, 445, 76, 23, 7, 9, 17, 19, 10]) == 68.66666666666667:
print("Second Function Works!")
================================================
FILE: algorithms/analysis/median.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Median
# Median is the middle value of data
# Data of odd length has a mid value
# but, data of even length has 2 mid values
# so their median is mean of these 2 values
# ranked parameter is to tell function
# weather data is ranked(sorted) or not
#
def median(ar, ranked = False):
if not ranked:
data = sorted(ar[:])
else:
# Don't need an else block still
# but to map program properly
# i've added it
data = ar[:]
# Data with odd length
if len(data) % 2 != 0:
# f(x) = (l(x) + 1) / 2 th term is the median of data
# but since computer starts counting from 0
# and not from 1, there is no need to add 1
# to length of data, otherwise results are
# not accurate
return data[len(data) / 2]
# Data with even length
# f(x) = [l(x) / 2 th term + (l(x) + 2) / 2th term] / 2
# 2.0 is to declare that median can be a float
# in case of even length data
return (data[len(data) / 2 - 1] + data[(len(data) + 1) / 2]) / 2.0
# Test
odd = [123, 456, 789, 101112, 131415, 161718, 192021, 222324, 252627]
even = [8, 7, 5, 2, 1, 3, 4, 6]
if median(odd, ranked = True) == 131415 and median(even) == 4.5:
# Print statements on separate lines look better
print("Median of odd data: " + str(131415))
print("Median of even data: " + str(4.5))
print("Yeah, it works!")
else:
# If algo didn't work
print("There's something wrong!")
# This median is for un-distributed/un-grouped data
# i.e. no frequencies
# plain numbers in an array
================================================
FILE: algorithms/analysis/min.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Finds the minium number
# in un-sorted data
# Sudo Algo:
# Iterate through data
# each time a number(say k) is less than previous
# consideration(say p), replace previous
# consideration(p) with that smaller number(k)
# By this way,
# At last we get the smallest(minium) number from data
def min_(seq):
min_n = seq[0]
for item in seq[1:]:
if item < min_n:
min_n = item
return min_n
# Test
# Add your tests too!
tests = [[9017289, 782367, 736812903, 9367821, 71256716278, 676215, 2398, 0, 1],
[19208, 9239, 4376, 738, 78, 51, 5, 6, 12, 78, 123, 65765, 1999999999],
[1, 2, 4, 7, 9]]
# checking our functions results
# with python's built-in min() function
for test_i in range(len(tests)):
m = min_(tests[test_i])
if m == min(tests[test_i]):
print("Min number in array({}) -> ".format(test_i + 1) + str(m))
else:
print("Oops! Someting went wrong!")
================================================
FILE: algorithms/analysis/mode.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Mode
# mode or modal value, is the number in data
# that has highest frequency, or occurs in data/array
# maximum number of times
# This function produces an outline of data
# each element occurs only once in outline
# that means no repeats of same numbers
def reduce_data(data):
# Simplest way to do this, just 1 line of code:
# return list(set(data))
# since set data structure does not have repeats
# But below code is much more
# illustrative and easier to understand
data_outline = []
for item in data:
if item not in data_outline:
data_outline.append(item)
return data_outline
# To find mode, we apply same principle, that works
# behind finding the maximum or minimum number(see max.py, min.py)
def mode(data):
mode_ = data[0]
max_frequency = data.count(data[0])
# Insted of iterating through every repeat of
# same number, then counting multiple repeats
# of number multiple times, iterating through outline
# of data is convinient, less time consuming.
for value in reduce_data(data[1:]):
if data.count(value) > max_frequency:
mode_ = value
max_frequency = data.count(value)
# instead of just mode, it's freq
# can also be helpful
return (mode_, max_frequency)
# Test
# Add your test cases
tests = [
[19, 17, 25, 34, 57, 17, 25, 52, 47, 42, 25, 17, 3, 0, 3, 41, 17],
[1917, 2534, 5717, 1725, 5247, 1917, 4117, 5717, 17303, 1917],
]
# Function does work,
# Check yourself
for test in tests:
modal_v = mode(test)
print("\nData outline: {}".format(reduce_data(test)))
print("Mode: {}\nFrequency: {}".format(modal_v[0], modal_v[1]))
print("")
# Mode for un-grouped data
================================================
FILE: algorithms/analysis/sort.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Bubble Sort
# Ideal sorting algorithm for
# small data/array
# temporary parameter tells
# function to sort a copy of
# orignal array, and not the array itself
# reverse parameter tells func
# to sort array in reverse/decending
# order
def sort_(arr, temporary = False, reverse = False):
# Making copy of array if temporary is true
if temporary:
ar = arr[:]
else:
ar = arr
# To blend every element
# in correct position
# length of total array is required
length = len(ar)
# After each iteration right-most
# element is completed sorted
while length > 0:
# So every next time we iterate only
# through un-sorted elements
for i in range(0, length - 1):
if reverse:
# Swapping greater elements to left
# and smaller to right
# decending order
if ar[i] < ar[i+1]:
tmp = ar[i]
ar[i] = ar[i + 1]
ar[i + 1] = tmp
else:
# Swapping greater elements to right
# and smaller to left
# accending order
if ar[i] > ar[i+1]:
tmp = ar[i]
ar[i] = ar[i + 1]
ar[i + 1] = tmp
# making sure loop breaks
length = length - 1
# if temporary, then returning
# copied arr's sorted form
# cuz if not returned, then function
# is literally of no use
if temporary:
return ar
# See proper explaination
# at: https://www.geeksforgeeks.org/bubble-sort/
# a good site!
# Testing
tests = [[7, 8, 9, 6, 4, 5, 3, 2, 1, 15], [1, 90, 1110, 1312, 1110, 98, 76, 54, 32, 10], ] # Add your test cases
for test in tests:
accend, decend = sort_(test, True), sort_(test, True, True)
if accend == sorted(test) and decend == sorted(test, reverse = True):
print("Orignal: {}".format(test))
print("Sorted: {}".format(accend))
print("Sorted(reverse): {}\n".format(decend))
else:
print("Something went wrong!\n")
# Seems our bubble sort works
# however for small data/array!
================================================
FILE: algorithms/analysis/sum.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Sudo ALgorithm:
# both functions work on same principle
# Iterate through array/arguments
# add each element to variable(res)
# return sum
def sum_(*args):
res = 0.0
for arg in args:
res += arg
return res
def sum_ar(ar, end_i):
# end_i is the last index of array
# till which function should add
# array's elements
if end_i > 0 and end_i <= len(ar):
if end_i == len(ar):
end_i = end_i - 1
else:
end_i = len(ar) - 1
res = 0.0
for elem in ar[:end_i + 1]:
res += elem
return res
# Simple Algorithm
# Testing
# First Function
if sum_(1, 2, 3, 4, 5, 6, 7, 8, 9) == 45:
print("First Function Works!")
# Second Function
if sum_ar([1, 2, 3, 4, 5, 6, 7, 8, 9], -1) == 45:
print("Second Function Partially Works!")
if sum_ar([1, 2, 3, 4, 5, 6, 7, 8, 9], 6) == 28:
print("Second Function Completely Works!")
================================================
FILE: algorithms/analysis/useful_function_mapping.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
def squared(n):
return n * n
def cubed(n):
return n * n * n
def raise_power(n, power):
for t in range(power):
n *= n
return n
def is_divisible(n, t):
return n % t == 0
def is_even(n):
return n % 2 == 0
def is_odd(n):
return n % 2 != 0
# These all functions are extremely
# helpful when used with map method of python
# map(func, list) basically applies given function
# to every element of list and appends results to a new
# list
# e.g.
print(map(squared, [1, 3, 5, 7, 9, 11, 13, 15]))
# for functions with multiple args
# see: https://www.quora.com/How-do-I-put-multiple-arguments-into-a-map-function-in-Python
================================================
FILE: algorithms/numbers/README.md
================================================
'numbers' Sub-directory contains all
numbers/math/sequences(arrays) related algorithms.
Thanks
================================================
FILE: algorithms/numbers/binary_to_decimal_converter.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# Binary to decimal conversion
# See explaination: https://i.imgur.com/heAT0PB.gif ,
# https://www.electronics-tutorials.ws/binary/bin_2.html
# Pesudo code:
# Iterate through binary num
# if 0 then pass
# else result = result + bit(1) * 2 ** index of bit(1)
def binary_to_decimal_conv(binary_string):
res = 0
binary_l = list(binary_string)
for bit_i in range(len(binary_l)):
res += int(binary_l[bit_i]) * (2 ** bit_i)
return res
# Test
# Testing interface
i = 0
while True:
if raw_input("\n[{}] Exit(press e) or Continue(press c): ".format(i)).strip().lower() == "c":
print("Decimal form: " + str(binary_to_decimal_conv(raw_input("\nBinary?: "))))
else:
print("\nHope you enjoyed!")
sys.exit()
i += 1
================================================
FILE: algorithms/numbers/collatz_sequence.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# Collatz conjecture
# is a series of numbers
# where the orignal number is manipulated, until
# one is obtained
# if n is even n // 2 is the next number
# else n * 3
# No matter what the value of n we'll,
# always reach 1.
# See: https://en.wikipedia.org/wiki/Collatz_conjecture
# Collatz series generator
def collatz_conjecture(n):
if n < 1:
raise Exception("\n Expected a value greater than 1")
while n != 1:
if n % 2 == 0:
n = n // 2
else: n = 3*n + 1
yield n
# If n will be negative then
# sequence will be infinite
# Interface
# Test/Play
i = 0
while True:
if raw_input("\n[%i] Continue[Y/n]?: " % i).strip().lower() == "y":
for v in collatz_conjecture(int(raw_input("N?: "))):
print(" > " + str(v))
i += 1
else:
print("\nSee you soon!")
sys.exit(0)
================================================
FILE: algorithms/numbers/compare_array_elements.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Compares elements at same
# index in 2 different arrays
# and so called generates tuple of
# that value, index, array number
# however if both numbers are equal
# returns zero simply
# Prime condition for correct results
# length(arr1) == length(arr2)
def compare_array_elements(arr1, arr2):
for l in range(len(arr1)):
if arr1[l] > arr2[l]:
yield (arr1[l], l, 1)
elif arr1[l] < arr2[l]:
yield (arr2[l], l, 2)
else:
yield(0)
# Tests
tests = [
[
[21, 3454, 12, 77, 21, 90, 235],
[123, 54, 21, 7, 23, 987, 21312]
],
[
[1223, 8273, 17732, 7127],
[12989, 2131223, 129, 10]
]
]
# Does not test last condition of function
for test in tests:
for n, index, array_n in compare_array_elements(test[0], test[1]):
print(" [ %i ] is biggest value at index(%i) from array(%i)" %(n, index, array_n))
================================================
FILE: algorithms/numbers/factorial.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Factorial
# is a mathematical function which
# determines number of all possibilities
# you can arrange 'n' number of objects!
#
# If there are 5 options in total
# At first: there are 5 to choose from
# 5 X
# then, after choosing 1 from those 5 we'd have
# 4 remaining, 5 x 4 x
# then 3 remaining, 5 x 4 x 3
# then 2, 5 x 4 x 3 x 2
# then 1, 5 x 4 x 3 x 2 x 1 = 120
# n is total number of objects
def factorial(n):
if n <= 1:
return 1
else:
n = n * factorial(n - 1)
return n
# Recursion is the easiest way to
# solve this problem
# but, to make sure recursion's depth ends, above
# condition is necessary, otherwise
# errors occur
# Another way to solve problem
def factorial_(n):
if n <= 1:
return 1
else:
m = 1
# range function produces inclusive range
for integer in range(1, n + 1):
m *= integer
return m
# This solution is bigger
# and looks much more complex
# than the recursion one
# Both work the same however
# Test
if factorial(5) == factorial_(5) == 120:
print("(" + str(5) + ")! == " + str(120))
print("Both functions work!\n-Try it yourself-")
x = int(raw_input("\nNumber: "))
print("(" + str(x) + ")! == " + str(factorial(x)))
else:
print("Someting went wrong!")
================================================
FILE: algorithms/searching/binary_search.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# I'm too lazy to explain how it works,
# instead check below sites out:
# https://en.wikipedia.org/wiki/Binary_search_algorithm
# https://www.geeksforgeeks.org/binary-search/
# Make sure you know concept of Recursion
# Function explaination:
# ar is the array
# f is starting index for divided search array
# l is ending index for divided search array
# v is the query to search in array data space
# sorted_ar tells the func, if array is sorted or not
# as binary search won't work on an un-sorted array
def binary_search(arr, f, l, v, sorted_ar = False):
# need an ordered/sorted array for search,
# else search won't produce desirable results
if not sorted_ar:
arr.sort()
# If input is invalid
if l - f < 0:
return -1
else:
# Index of mid-term of array[f:l+1]
mid_element_i = (f + l) // 2
# If mid-term matches the query
if arr[mid_element_i] == v:
return mid_element_i
# If query is bigger than that mid-term
# then we'll look at next_half of array
elif v > arr[mid_element_i]:
return binary_search(arr, mid_element_i+1, l, v, True)
# else query is smaller than mid-term
# so we'll look at lesser half of array
else:
return binary_search(arr, f, mid_element_i-1, v, True)
# Tests
# Add your tests
# Arrays below are not sorted or are un-ordered
# Index returned by function is for sorted array
# thus index might differ for same element, array below and in sorted array!
tests = [
[10, 29, 38, 47, 56, 19, 28, 37, 46, 50],
[1, 92, 83, 74, 65, 29, 84, 75],
[1, 21, 32, 43, 54, 65, 79],
[7, 7],
]
# Play as long as you can
# Searches query in all of arrays in tests
i = 0
while True:
if raw_input("\n[%i] Exit(press e) or Continue(press c): " % i) == "e":
sys.exit()
q = int(raw_input("\nSearch?: "))
print("Results:")
for test in tests:
find_i = binary_search(test, 0, len(test) - 1, q, False)
if test[find_i] == q:
print(" Found [{}] at index({}) in array({})".format(q, find_i, tests.index(test) + 1))
else:
# else is executed means,
# something is wrong with the algorithm
print(" No results for [{}] in array({}). Try another search!".format(q, tests.index(test) + 1))
i += 1
================================================
FILE: algorithms/sorting/README.md
================================================
'sorting' Sub-directory contains all
sorting algorithms.
Thanks
================================================
FILE: algorithms/sorting/bubble_sort.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Bubble Sort
# Ideal sorting algorithm for
# small data/array
# temporary parameter tells
# function to sort a copy of
# orignal array, and not the array itself
# reverse parameter tells func
# to sort array in reverse/decending
# order
def sort_(arr, temporary = False, reverse = False):
# Making copy of array if temporary is true
if temporary:
ar = arr[:]
else:
ar = arr
# To blend every element
# in correct position
# length of total array is required
length = len(ar)
# After each iteration right-most
# element is completed sorted
while length > 0:
# So every next time we iterate only
# through un-sorted elements
for i in range(0, length - 1):
if reverse:
# Swapping greater elements to left
# and smaller to right
# decending order
if ar[i] < ar[i+1]:
tmp = ar[i]
ar[i] = ar[i + 1]
ar[i + 1] = tmp
else:
# Swapping greater elements to right
# and smaller to left
# accending order
if ar[i] > ar[i+1]:
tmp = ar[i]
ar[i] = ar[i + 1]
ar[i + 1] = tmp
# making sure loop breaks
length = length - 1
# if temporary, then returning
# copied arr's sorted form
# cuz if not returned, then function
# is literally of no use
if temporary:
return ar
# See proper explaination
# at: https://www.geeksforgeeks.org/bubble-sort/
# a good site!
#can add flag to reduce time complexity
# Testing
tests = [[7, 8, 9, 6, 4, 5, 3, 2, 1, 15], [1, 90, 1110, 1312, 1110, 98, 76, 54, 32, 10], ] # Add your test cases
for test in tests:
accend, decend = sort_(test, True), sort_(test, True, True)
if accend == sorted(test) and decend == sorted(test, reverse = True):
print("Orignal: {}".format(test))
print("Sorted: {}".format(accend))
print("Sorted(reverse): {}\n".format(decend))
else:
print("Something went wrong!\n")
# Seems our bubble sort works
# however for small data/array!
================================================
FILE: algorithms/sorting/insertion_sort.py
================================================
# -*- coding: utf-8 -*-
# Insertion Sort
# Ideal sorting algorithm for
# small/small-medium data/array
# temporary parameter tells
# function to sort a copy of
# orignal array, and not the array itself
# reverse parameter tells func
# to sort array in reverse/decending
# order
def sort_(arr,temporary=False,reverse=False):
# Making copy of array if temporary is true
if temporary:
ar = arr[:]
else:
ar = arr
# To blend every element
# in correct position
# length of total array is required
length = len(ar)
# After each iteration left-most
# sub-array is completed sorted
for i in range(1,length):
# In each iteration we place
# the current element to its
# proper position in left sorted
# sub array
tmp = ar[i]
j = i-1
if reverse:
while j>=0 and tmp>ar[j]:
ar[j+1]=ar[j]
j-=1
ar[j+1]=tmp
else:
while j>=0 and tmpar[j]:
min = j
# Replacing minimum/maximum
# with current element
tmp = ar[i]
ar[i]=ar[min]
ar[min]=tmp
# if temporary, then returning
# copied arr's sorted form
# cuz if not returned, then function
# is literally of no use
if temporary:
return ar
# See proper explaination
# at: https://www.hotdogcode.com/selection-sort/
# Testing
tests = [[7, 8, 9, 6, 4, 5, 3, 2, 1, 15], [1, 90, 1110, 1312, 1110, 98, 76, 54, 32, 10], ] # Add your test cases
for test in tests:
accend, decend = sort_(test, True), sort_(test, True, True)
if accend == sorted(test) and decend == sorted(test, reverse = True):
print("Orignal: {}".format(test))
print("Sorted: {}".format(accend))
print("Sorted(reverse): {}\n".format(decend))
else:
print("Something went wrong!\n")
# Seems our selection sort works
# however for small/small-medium data/array!
================================================
FILE: algorithms/string/README.md
================================================
'string' Sub-directory contains all
string related algorithmsThanks
================================================
FILE: algorithms/string/caesars_cipher_encryption.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import string, sys
# Caesar's cipher is type of shift cipher,
# an encryption technique
# First used by roman rular Julius Caesar
# To see how it works refer:
# web-page/article: https://en.wikipedia.org/wiki/Caesar_cipher OR
# https://www.khanacademy.org/computing/computer-science/cryptography/crypt/v/caesar-cipher
def caesars_cipher_encoding(s, k, lowercase = True, uppercase = False):
# To encrypt plain text in either
# uppercase letters or lowercase letters
if lowercase:
alphas = list(string.lowercase)
elif uppercase:
alphas = list(string.uppercase)
encrypted = ""
# List characters in orignal string
char_s = list(s)
# Shifting of each single
# character in orignal string
# using given key
for char in char_s:
# avoid encryption of spaces
if char == " ":
encrypted += " "
else:
# n_index or new index is
# the index of encrypted character
n_index = k + alphas.index(char)
# if encrypted character is greater than
# length of english alphabets
if n_index > 25:
# Read explaination on line 59
while not n_index <= 25:
n_index = n_index - 26
encrypted += alphas[n_index]
# simple shift
else:
encrypted += alphas[n_index]
return encrypted
# Explaination of key bigger than 26:
# say we have key 54,
# we add index of char(say 'a') to key, i.e. key = 54 + 1 = 55
# so after first iteration over array of length(26),
# i.e. 55(total iterations to perform) - 26(iterations completed) = 29(iterations left)
# but, 29 is still a big index i.e. 29 > length of array(26)
# so we continue to subtract more 26(iterations),
# i.e. 29(iterations to perform) - (26 iterations done) = 3(remaining)
# so 3 is smaller than length of array and can be used as key,
# i.e. 3 < 26(length of array)
# thus, we reached at index of 3 after 54 iterations over an array of length 26
# bit complicated but read it twice, you'll master it!
# Test, Playing UI
i = 0
while True:
if raw_input("[{}] Exit(press e), To continue(press c): ".format(i)).lower() == "c":
# Number of times
i += 1
# Input for String and key for char shift
S, K = raw_input("\nString: "), int(raw_input("Key: "))
# Results
print("\nOrignal string: " + S + " , Key: " + str(K))
print("Encrypted text: " + caesars_cipher_encoding(S, K, True, False) + "\n")
else:
sys.exit()
================================================
FILE: algorithms/string/check_anagram.py
================================================
'''An anagram is a word or phrase created by rearranging the letters of another word or phrase.
For example, the word "heart" can be rearranged to form the word "earth".
So, "heart" and "earth" are anagrams of each other.'''
def check_anagram(str1,str2):
# Remove all spaces from both the strings
# and convert them to lowercase
str1 = str1.replace(" ","").lower()
str2 =str2.replace(" ","").lower()
# if the length of both strings are not equal then return false
if len(str1) != len(str2):
return False
count1 = {}
count2 = {}
for i in range(len(str1)):
count1[str1[i]] = 1+count1.get(str1[i],0)
count2[str2[i]] = 1+count2.get(str2[i],0)
for c in count1:
if count1[c] != count2.get(c,0):
return False
str1 = input()
str2 = input()
if check_anagram(str1,str2):
print(f"{str1} and {str2} are anagrams")
else:
print(f"{str1} and {str2} are anagrams")
================================================
FILE: algorithms/string/is_palindrome.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Palindrome is a special string, is same if reversed
# e.g. noon, racecar, et cetera
# Notice in above strings, there is no difference between
# string and it's reversed form
# Function checks if given string is a palindrome or not
# string[::-1] is a clever way to reverse string
# string from start index to end index
# whose difference is -1(reverse)
# found on stack overflow, very pythonic
def is_palindrome(s) :
if s[::-1] == s:
return True
return False
# Test
S = raw_input("String: ")
if is_palindrome(S):
print("Results:\n " +S + " is a palindrome string.")
else:
print("Results:\n " + S + " is not a palindrome string.")
# add a loop to play many times(maybe infinite)
================================================
FILE: algorithms/string/is_palindrome_two_liner.py
================================================
import string
def is_palindrome(s):
# String Clenasing
s = "".join([char for char in list(s.lower()) if char in list(string.ascii_lowercase)])
# (index+1) * -1 gives negative index of corresponding counterpart
# for e.g. s = "noon" s[0] = s[-1] = "n" and so on
# all() and list comprehensions make task so easy!!
return all([s[index]==s[(index+1)*-1] for index in range(0, len(s))])
# Tests
print(is_palindrome("racecar"))
print(is_palindrome("ra cec, a?r ")) // True
print(is_palindrome("noooonnn"))
print(is_palindrome("cool..eh")
================================================
FILE: algorithms/string/vowel_count.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# The function
# counts number of occurrences of vowels
# in given string
# Principle:
# Loop through list of vowels
# count occurrences of each vowel in given string
# yield/generate the occurrences of that vowel
def vowel_count(S):
vowels = ['a', 'e', 'i', 'o', 'u']
for vowel in vowels:
counter = 0
for char in S:
if char == vowel:
counter += 1
yield(vowel, counter)
# CLI
# Testing or Playing Interface
while True:
usr_input = raw_input("\nPress (e) to Exit\nor Enter string: ").strip().lower()
if not usr_input == "e":
print("> Results: ")
for vow, counter in vowel_count(usr_input):
print(" " + vow + " > occurred " + str(counter) + " times.")
else:
print("\nHope you enjoyed!")
sys.exit()
================================================
FILE: ansi-colors.py
================================================
"""
ansi-colors.py
Print 256 ANSI(8bit) color chart
Reference : https://en.wikipedia.org/wiki/ANSI_escape_code
*** Warning!
In some terminal/OS environments,
this code may display different colors or color may not be displayed properly
"""
START_ESCAPE_8BIT = "\033[38;5;"
END_ESCAPE = "\033[0;0m"
SQUARE_CHAR = '\u25A0'
def print_square_8bit(color):
print(START_ESCAPE_8BIT + str(color) + 'm' + SQUARE_CHAR + END_ESCAPE, end="")
print("System standard colors: ", end="")
for i in range(8):
print_square_8bit(i)
print()
print("System high intensity colors: ", end="")
for i in range(8, 16):
print_square_8bit(i)
print()
step = 0
print("216 Colors: ")
for i in range(16, 232):
print_square_8bit(i)
step += 1
if step % 24 == 0: # Make newline every 24 colors
print()
print()
print("Grayscale colors: ", end="")
for i in range(232, 256):
print_square_8bit(i)
print()
================================================
FILE: armstrong_number.py
================================================
# Python program to check if the number is an Armstrong number with the index of 3 or not
# for input try numbers 153, 370, 371, 407
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# finding the length of num
n = len(str(num))
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** n # power of n
temp //= 10
# display the result
if num == sum:
print(num, "is an Armstrong number.")
else:
print(num, "is not an Armstrong number.")
# Originally contribution by denz647
================================================
FILE: bell_number.py
================================================
# Contribution by https://github.com/nightwarriorftw
#Python program to print bell number
#Bell Number:-Let S(n, k) be total number of partitions of n elements into k sets. The value of n’th Bell Number is sum of S(n, k) for k = 1 to n. Value of S(n, k) can be defined recursively as, S(n+1, k) = k*S(n, k) + S(n, k-1)
A sample Bell triangle is as follows:
1
1 3
3 8 13
13 23 33 43
#The code to print the bell triangle is as follows-
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
n=int(input("enter the number of bell")) #taking value from the user
bell=0 #initialising bell to 'zero'
k=0 #initialising k to 'zero'
for i in range(0,n): #loop for changing rows from 0 to n
for j in range(0,i+1): #printing columns
if j==0 and i>0: #repeating the last number of previous row in new row
print(bell,'',end='') #printing first number of each line
else:
k=(i**2)+1+bell #to generate other numbers of line
print(k,'',end='') #printing other number in lines
bell=k #updating value of bell
print('\n') #for moving into next lines
print("last number of bell is",bell)
================================================
FILE: bigo_notation.py
================================================
# Contribution from https://github.com/Alok070899
from math import log
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('bmh')
# Set up runtime comparisons
n = np.linspace(1,10,1000)
labels = ['Constant','Logarithmic','Linear','Log Linear','Quadratic','Cubic','Exponential']
big_o = [np.ones(n.shape),np.log(n),n,n*np.log(n),n**2,n**3,2**n]
# Plot setup
plt.figure(figsize=(12,10))
plt.ylim(0,50)
for i in range(len(big_o)):
plt.plot(n,big_o[i],label = labels[i])
plt.legend(loc=0)
plt.ylabel('Relative Runtime')
plt.xlabel('n')
================================================
FILE: bubble sort.py
================================================
'''Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )'''
# Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),
================================================
FILE: cartesian_plane_quadrant.py
================================================
# quadrant determiner
# I(+,+) II(-,+) III(-,-) IV(+,-)
def determine_quadrant(x, y):
try:
if x > 0 and y > 0:
return 'I(+,+)'
elif x < 0 and y > 0:
return 'II(-,+)'
elif x < 0 and y < 0 :
return 'III(-,-)'
elif x > 0 and y < 0 :
return 'IV(+,-)'
else :
return 'Invalid parameters were provided'
except TypeError:
return "X and Y co-ords must be integers and not X {}, Y{}".format(type(x), type(y))
# Test
result = determine_quadrant(float(input('X co-ordinate: ')), float(input('Y co-ordinate: ')))
print("Quadrant is " + result)
================================================
FILE: client_file.py
================================================
import socket
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12345
x = input("Enter file name : ")
server_socket.connect((host,port))
name = server_socket.recv(1024).decode()
name = name.split('.')[-1]
name = x+'.'+name
f = open(name,'wb')
while True :
c_msg = server_socket.recv(1024)
if c_msg == 'EOF'.encode() :
f.close()
server_socket.close()
break
f.write(c_msg)
================================================
FILE: conways.py
================================================
'''
-conway's game of life
-made by Tzara Northcut @Mecknavorz
-requires pygame
'''
#import the stuff we need
import pygame, sys, time
#-----------------------------------------
#initalize some variables and other things
#-----------------------------------------
width = 6 #cell size width
height = 6 #cell size height
space = 2 #thickness of world lines
#create the 2d array where we actually store vairables of cells
world = [[0 for x in range(100)] for y in range(100)]
#initialzie pygame
pygame.init()
size = [100*(width+space)+space, 100*(height+space)+space] #window size
screen = pygame.display.set_mode(size) #make the window the right size
#set spme colors
BLACK = ( 0, 0, 0) #background color
WHITE = (255, 255, 255) #color of world
GREEN = ( 0, 0, 0) #color of cells that are alive and well
RED = (255, 0, 0) #colors of the cells about to die
#speed stuff
clock = pygame.time.Clock() #clock used to manage game speed
pause = True #used to control the steps, might not need this
laststep = time.time()
#used to keep runing until the game is closed
done = False
#-------------------------------------
#some functions to be used in the game
#-------------------------------------
#determine #of cells nearby
def getclose(x, y):
nearby = 0
#avoid out of bounds error and make the grid a torroid
if(x+1) > 99:
x = 0
if(y+1) > 99:
y = 0
#swcan nearby squares and if there's something there add 1 to the count
if world[x-1][y-1]:
nearby += 1
if world[x][y-1]:
nearby += 1
if world[x+1][y-1]:
nearby += 1
if world[x-1][y]:
nearby += 1
if world[x+1][y]:
nearby += 1
if world[x-1][y+1]:
nearby += 1
if world[x][y+1]:
nearby += 1
if world[x+1][y+1]:
nearby += 1
return nearby
#calculate next step
def nextStep():
for x in range(len(world)):
for y in range(len(world[0])):
near = getclose(x, y)
if near < 2: #if there are less than two neighbors then kill the cell
world[x][y] = 0
if near > 3: #if there are more than three neighbors then kill the cell
world[x][y] = 0
if (world[x][y] == 0) and (near == 3): #if there are 3 neighbors near a dead cell, revive it
world[x][y] = 1
#clear the board
def clear():
for x in range(len(world)):
for y in range(len(world[0])):
world[x][y] = 0
#---------------------
#the initale game loop
#---------------------
while not done:
#to make sure the game quits when we need it to
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN: #if we get a click
pos = pygame.mouse.get_pos() #find where the click was
#change the pixel coords into game coords
x = pos[1] // (height+space)
y = pos[0] // (width+space)
#add or remove the cell that's there
if world[x][y] == 0: #if the tile is empty add a cell
world[x][y] = 1
#print("nearby: ", getclose(x, y)) #used for debugging
else: #else if there's something there, remove the cell
world[x][y] = 0
#print("click: ", pos, "grid coord: ", x, y) #debug stuff
elif event.type == pygame.KEYDOWN: #pause the game when space is pressed
if event.key == pygame.K_SPACE:
#print('space pressed')
if pause:
pause = False
elif not pause:
pause = True
elif event.key == pygame.K_RIGHT: #if we presws the right key go forward a step
nextStep() #calculate the next
elif event.key == pygame.K_ESCAPE:
clear()
#draw the world
screen.fill(BLACK)
#maybe move this to a seprate function to help with effeciency?
for x in range(len(world)):
for y in range(len(world[0])):
color = WHITE
if world[x][y] == 1:
color = GREEN
pygame.draw.rect(screen, color, [(space+width)*y+space, (space+height)*x+space, width, height])
#set frame rate
clock.tick(60)
if (not pause) and ((time.time() - laststep) > .1):
laststep = time.time()
#print(laststep)
nextStep()
#update screen
pygame.display.flip()
#if we;ve gotten this far (eg out of the while loop) we know it's time to quit
pygame.quit()
================================================
FILE: count_algorithm_execution_time.py
================================================
from datetime import datetime
# Don't confuse this is "Main" algorithm
# Time calculated is near accurate because of some extra instructions
# before actually executing the algorithm
def count_cpu_microtime(func_name, *args):
tmp = [i for i in args]
t1 = datetime.now().microsecond
func_name(*tmp)
time_took = datetime.now().microsecond - t1
return round(time_took, 5)
# Testing
# "Test" algorithm
def binary_search(array, n):
arr = sorted(array)
to_return = False
first_elem = 0
last_elem = len(arr) - 1
while (first_elem <= last_elem):
mid = (first_elem + last_elem) // 2
if (arr[mid] == n):
to_return = True
break
else:
if (n > arr[mid]):
first_elem = mid + 1
else:
last_elem = mid - 1
return to_return
result = count_cpu_microtime(binary_search, [12,324,23,213,3,2,1], 1)
print(str(result) + " microsecs")
================================================
FILE: days_you_lived.py
================================================
# We assume that given dates are correct
# and
# solved for problem set in cs course on udacity.com
from calendar import isleap
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
dom = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
domleap = [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (isleap(year1) and isleap(year2)):
e1 = sum(domleap) + sum(domleap[:month1 - 1]) + day1
e2 = sum(domleap) + sum(domleap[:month2 - 1]) + day2
return e2 - e1
days = 0
if isleap(year1):
days += (sum(domleap[month1 - 1:]) - day1) + sum(dom[:month2 - 1]) + day2
elif isleap(year2):
days += (sum(dom[month1 - 1:]) - day1) + sum(domleap[:month2 - 1]) + day2
else:
days += (sum(dom[month1 - 1:]) - day1) + sum(dom[:month2 - 1]) + day2
for year in range(year1 + 1, year2):
if isleap(year):
days += sum(domleap)
else:
days += sum(dom)
return days
date1=input("Enter a first date in YYYY-MM-DD format")
year1,month1,day1=map(int,date1.split('-'))
date2=input("Enter a second date in YYYY-MM-DD format")
year2,month2,day2=map(int,date2.split('-'))
days=daysBetweenDates(year1, month1, day1, year2, month2, day2)
print("Number of days between {} and {} is \n {}".format(date1,date2,abs(days)))
================================================
FILE: deMorgans_law.py
================================================
# Morgans Formula In Algebra Set operations
# number(set A) + number(set B) - number(set A interaction B)
# n(a)+ n(b) - n(anb)
# you can add sets or increase the number elements of sets The formula still works
a = { 1 , 23 , 55 , 76 , 13 , 90 , 34 , 78 }
b = { 12 , 345 , 8 , 4 , 0 , 7 , 4 , 3 , 53 , 4 , 6 , 3 }
abInteraction = a & b # & operator interacts two sets
abUnion = a | b # | operator makes union of two sets
eqn = len(a) + len(b) - len(abInteraction)
print(str(eqn) + ' = ' + str(len(abUnion)))
================================================
FILE: decimal_to_binary_converter.py
================================================
# For concatenation
def concat(S):
res = ""
for i in S:
if not isinstance(i, str):
res += str(i)
else:
res += i
return res
# Simple Base 10 number(Decimal) number converter to Base 2 number(binary) number
# Function returns answer in str datatype
# For understanding steps: http://www.electronics-tutorials.ws/binary/bin_2.html
def decimal_to_binary(n):
res = []
while n != 0:
res.append(n % 2)
n = n // 2
final = concat(res) + "0"
return final[::-1]
# Test
cases = [123, 23455, 253552, 87985, 3479434, 76, 246572, 231, 69, 2, 7, 2, 543]
for case in cases:
built_in = str(bin(case))[2:]
my_func = decimal_to_binary(case)[1:] # For test purposes
if built_in == my_func:
print("Decimal: " + str(case))
print("Binary: " + my_func + "\nTest Passed!\n")
else:
print("Test Failed! Badly!!\n")
================================================
FILE: decrypting_caesars_cipher.py
================================================
import string
# Note: this decryption function is designed to decrypt messages encrypted by encryption function i wrote(avaliable in this repo)
def concat_elements(n):
res = ""
for i in n:
res += i
return res
def decrypt(message, key):
string_chars = list(string.ascii_uppercase) + list(string.ascii_lowercase) + list(string.digits) + list(string.punctuation) + [" "]
try:
splitted_message = list(message)
except TypeError:
return "Expected an string for text!"
for char in splitted_message:
try:
tmp = string_chars[string_chars.index(char) - key]
except IndexError:
tmp_key = (string_chars.index(char) + key) + len(string_chars)
tmp = string_chars[tmp_key]
splitted_message[splitted_message.index(char)] = tmp
final = concat_elements(splitted_message)
return final
def decrypt_generator(message, n):
# range(0, 96) because len(string_chars) == 95
for i in range(0, n + 1):
case = decrypt(message, i)
yield case
# Test
test_case = "lq01Ir1I2xyI1ncrn2*"
result = decrypt(test_case, 9)
print("Decrypted Text: " + result, "\n")
_result = list(decrypt_generator(test_case, 95))
for res in _result:
print("Possible text: " + res)
# Look at ninth result
================================================
FILE: dictionary.py
================================================
global dictionary
dictionary = {}
class Dict:
def __init__(self, word, meaning):
self.word = word
self.meaning = meaning
def add_new(self):
dictionary[self.word] = self.meaning
print("Word Successfully Added")
def delete_word(self):
try:
del dictionary[self.word]
print("Word Successfully Deleted")
except KeyError:
print("The Word Does Not Exist in Dictionary. Try Again!")
def edit_word(self):
try:
dictionary[self.word] = self.meaning
print("Word Was Successfully Edited")
except KeyError:
print("The Word You Trying To Edit Does Not Exist in Dictionary!")
def view_word(self):
try:
print(dictionary[self.word])
except KeyError:
print("The Word is not in Dictionary.")
def view_all(self):
for i in dictionary.keys():
print(f"{i} : {dictionary[i]}")
def start():
get_op = input("Add, Delete, Edit, View, View all : ")
if get_op in ["add", "Add"]:
get_word = input("Word to add : ")
get_meaning = input("Meaning : ")
new = Dict(get_word, get_meaning)
new.add_new()
elif get_op in ["delete", "Delete"]:
get_word_to_del = input("Word to delete : ")
delete = Dict(get_word_to_del, None)
delete.delete_word()
elif get_op in ["edit", "Edit"]:
get_word_to_edit = input("Word to edit : ")
get_new_meaning = input("New meaning : ")
mean = Dict(get_word_to_edit, get_new_meaning)
mean.edit_word()
elif get_op in ["view", "View"]:
get_word_to_view = input("Word to view : ")
view = Dict(get_word_to_view, None)
view.view_word()
elif get_op in ["view all", "View All", "View all"]:
nothing = Dict(None, None)
nothing.view_all()
else:
print("Invalid Input. Try again!")
def end():
quit()
def main():
while True:
s_or_e = input("Start or End : ")
if s_or_e.lower() == "start":
start()
print(" ")
continue
else:
end()
if __name__ == "__main__":
main()
================================================
FILE: difference_testing.py
================================================
# We assume that the input always be find_difference_matching(list, list, integer)
def find_difference_matching(x , y , diff = 0):
res = []
for i in range(len(x)):
if abs(x[i] - y[i]) == diff:
res.append((x[i], y[i]))
return res
# Test
a = [12, 10, 123, 76, 9990]
b = [2, 0, 45,66, 10000]
result = find_difference_matching(a, b, 10)
print("Matches:")
for i in result:
print(" " + str(i))
================================================
FILE: discount.py
================================================
def percToDiscount(percent , mp):
discount = percent / 100 * mp
return('Discount is : ' + str(discount))
print('Hello\n')
print('Press Enter to exit')
while(True): # I've put counting discount in a loop cause if you want to count on multiple items
more = str(input('Count or End : '))
if more == 'Count':
disCountPerc = float(input('Discount Percent : '))
marketPrice = float(input('Market Price : '))
print(percToDiscount(disCountPerc , marketPrice))
continue
else:
quit()
================================================
FILE: discountPercent.py
================================================
def iLoveDiscount(discount , mp): # mp is market price
discountPerc = discount / mp * 100
return('Discount is ' + str(discountPerc) + '%')
print('Hello\n')
print('Press Enter to exit')
while(True): # I've put counting discount in a loop cause if you want to count on multiple items
more = str(input('Count or End : '))
if more == 'Count':
disCount = float(input('Discount : '))
marketPrice = float(input('Market Price : '))
print(iLoveDiscount(disCount , marketPrice))
continue
else:
quit()
================================================
FILE: distance_on_number_line.py
================================================
# this is a simple geometric distance formula
# d(x,y) = |x-y| = distance
# where x and y are co-ordinates on a number line
def distance(x,y):
return abs(x-y)
flag = True
while flag:
usr = str(input("start [Y/n]: ")).strip().lower()
if usr == "y":
print(distance(float(input("Value of X co-ordinate: ")), float(input("Value of Y co-ordinate: ")) ), "\n")
else:
flag = False
================================================
FILE: euclids_algorithm.py
================================================
# Recursive implementation of Euclidean algorithm
def gcd(m, n):
"""
Calculates the greatest common divisor (GCD) of two positive integers using the Euclidean algorithm.
Args:
m (int): First positive integer.
n (int): Second positive integer.
Returns:
int: The GCD of m and n.
"""
(a, b) = (max(m, n), min(m, n))
while b != 0:
a, b = b, a % b
return a
================================================
FILE: factorial.py
================================================
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))
================================================
FILE: figure determiner.py
================================================
while(2==2):
print("_________________________________________________")
print("""Program can determine till 6 angles only.
and remember if you have angles less than 6 simply enter 0""")
print("_________________________________________________")
get = int(input("Enter first angle:"))
print("_________________________________________________")
get_again = int(input("Enter second angle:"))
print("_________________________________________________")
get_again_again = int(input("Enter third angle:"))
print("_________________________________________________")
get_it = int(input("Enter fourth angle:"))
print("_________________________________________________")
get_it_it = int(input("Enter fifth angle:"))
print("_________________________________________________")
getting = int(input("Enter sixth angle:"))
print("_________________________________________________")
if get + get_again + get_again_again + get_it + get_it_it + getting == 180:
print("The figure is Triangle or linear pair of angles")
print("_________________________________________________")
elif get + get_again + get_again_again + get_it + get_it_it + getting == 360:
print("The figure is Quadrilateral ")
elif get + get_again + get_again_again + get_it + get_it_it + getting == 540:
print("The figure is Pentagon")
elif get + get_again + get_again_again + get_it + get_it_it + getting == 720:
print("The figure is Hexagon")
feature = raw_input("Start again or End:")
if feature == "Start again":
print("Starting again...")
print("Started again")
continue
elif feature == "End":
print("Program Ended...")
print("_________________________________________________")
print(" ")
break
================================================
FILE: findLcm.py
================================================
# function to find lcm of two numbers
def findLcm(i,v):
if i > v:
x = i
else:
x = v
while True:
if (x % i == 0) and (x % v == 0):
lcm = x
return(x)
break
x = x + 1
# Main code
while(True):
startOrEnd = str(input('Count lcm or End : '))
if startOrEnd == 'Count lcm':
getFirst = float(input('First num : '))
getSecond = float(input('Second num : '))
print(findLcm(getFirst , getSecond))
else:
quit()
================================================
FILE: find_cube_root.py
================================================
# This method is called exhaustive numeration!
# I am checking every possible value
# that can be root of given x systematically
# Kinda brute forcing
def find_cube_root(x):
if type(x) == str:
return "Expected an integer! Cannot find cube root of an string!"
for i in range(0, x):
if i ** 3 == x:
return i
return "{} is not a perfect cube".format(x)
# Test
x = 27
result = find_cube_root(x)
print("Cube root of {} is {}".format(x, result))
================================================
FILE: find_roots.py
================================================
"""
How it works:
Thing is simple first we determine the variable in equation;
Then we iterate through given range by user or default range;
For each iteration we replace the variables in equation to the number;
At last we return the roots found;
"""
from string import ascii_letters
def find_variable(string):
splitted = string.split()
for i in splitted:
if (i in ascii_letters):
return i
else: continue
return None
# Input format for function:
# "z ** 2 + 97 * z + (-4)"
def find_roots(S, rng = [-10000, 10000]):
res = []
for v in range(rng[0], rng[1]):
try:
test_case = S.replace(find_variable(S), str(v))
except Exception as e:
print(e)
return ""
if (eval(test_case) == 0):
res.append(v)
else:
continue
if (len(res) == 0):
return None
return res
#testing
"""
test_str = "x ** 2 + 5 * x - 6"
result = find_roots(test_str, [-10, -2])
for i in result:
print("Root of the equation is {}".format(i))
"""
================================================
FILE: find_square_root.py
================================================
# This method is called exhaustive numeration!
# I am checking every possible value
# that can be root of given x systematically
# Kinda brute forcing
def find_square_root(x):
if type(x) == str:
return "Expected an integer! Cannot find square root of an string!"
for i in range(0, (x/2 )+2):
if i ** 2 == x:
return i
return "{} is not a perfect square".format(x)
# Test
x = 2
result = find_square_root(x)
print("Square root of {} is {}".format(x, result))
================================================
FILE: find_square_root_of_imperfect_square.py
================================================
# Here I've implemented a method of finding square root of imperfect square
# Steps (Pseudocode): visit http://burningmath.blogspot.in/2013/12/finding-square-roots-of-numbers-that.html
# Read the steps carefully or you'll not understand the program!
# To check is number is a perfect square or not
def is_perfect_square(n):
if isinstance(n, float):
return (False, None)
for i in range(n + 1):
if i * i == n:
return (True, i)
return (False, None)
# Average
def average(*args):
hold = list(args)
return sum(hold) / len(hold)
# Method
# Just implementation of steps on above webpage
def sqrt_of_imperfect_square(a, certainty = 6):
is_square = is_perfect_square(a)
if is_square[0]:
return "{} is a perfect square .It's root is {}.".format(a, is_square[1])
else:
a = int(a)
tmp = None
s1 = max([float(x * x) for x in range(0,a)])
while True:
s2 = a / s1
tmp = average(s1, s2)
if not(round(tmp * tmp, certainty) == float(a)):
s1 = tmp
continue
else:
return tmp
return -1 # This condition will normally never occur
# Test
case = 2613
res = sqrt_of_imperfect_square(case, 9)
print("Test case: " + str(case))
print("Root: " + str(res))
print("Root Squared: " + str(res * res))
================================================
FILE: geometric_progression_builder.py
================================================
"""
Simply it just builds a geometric progression on given conditions.
Iterates through t1 till n
multiplies last values in list to constant
append it back to list
COOL!
"""
def build_geo_sequence(start, end, constant):
temp = [start]
try:
for i in range(start, end):
temp.append(temp[-1] * constant)
except TypeError as te:
print(te)
except Exception as e:
print(e)
else:
return temp
# Test
res = build_geo_sequence(1, 10, 3)
print("Geo Sequence:")
for i in res:
print(" " + str(i))
# Expected -> 1, 3, 9, 27, 81, ....
# Here a = 1, d = 3
================================================
FILE: healthScore.py
================================================
# Health Calculator
# func to show health score of user
def healthScore():
print(' ')
numberOfFruits = int(input('Number Of Fruits You Eat in Week : '))
numberOftimesFastFood = int(input('Number of Times You Eat FastFood in a Week : '))
cigars = int(input('Cigars You Smoke In A Week : '))
workoutTime = int(input('How Much minutes You Workout EveryDay : '))
bodyMassIndex = int(input('Whats Your BodyMassIndex(BMI) : '))
if 18 < bodyMassIndex < 26 :
print(' ')
healthScore = (numberOfFruits + workoutTime + bodyMassIndex ) - (cigars + numberOftimesFastFood)
print(healthScore)
else :
print(' ')
healthScore = (numberOfFruits + workoutTime) - (cigars + numberOftimesFastFood + bodyMassIndex )
print(healthScore)
# main code
while True:
startOrEnd = str(input('Start or End : '))
if startOrEnd == 'Start':
print(healthScore())
continue
else :
quit()
================================================
FILE: hello_world.py
================================================
# printing hello world is a tradition in beginners
# it is normally used to if check everything is okay
import sys
#type 1 sys.stdout.write()
sys.stdout.write("Hello, ")
sys.stdout.write("World!")
sys.stdout.write("\n")
#type 2 print()
print("Hello, World!")
#type 3 - format()
word1 = "Hello"
word2 = "World"
print("{} {}".format(word1, word2))
#type 4 - f-strings
word1 = "Hello"
word2 = "World"
print(f"{word1} {word2} ")
#type 5 - join
characters = ['H','e','l','l','o',' ','W','o','r','l','d']
message = "".join(characters)
print(message)
#type 6 - Dict
words = {"Eng_greeting": "Hello", "Eng_world": "World"}
message = " ".join(words.values())
print(message)
================================================
FILE: html_source.py
================================================
# Tested in python2.7
# Getting Html text and saving it to a file.
import urllib
def get_html(url , fname):
try:
responsive = urllib.urlopen(url)
save_file = open(fname + '.html' , 'w')
save_file.write(responsive.read())
save_file.close()
except IOError:
return "Make sure url entered is correct and valid!"
except Exception as e:
return "An Error occured, make sure information enerted is correct!"
else:
return "Html Successfully received and saved in file {}.html".format(fname)
# if you want to read the file uncomment this code
# emp = open(name + ".html", 'r').read()
# openFile.close()
# return emp
print('Hello,')
while(True):
start_or_end = str(raw_input('start or end: ')).strip().lower()
if start_or_end == 'start':
print(get_html(raw_input('URL: ').strip() , raw_input('file name: ').strip()), "\n")
continue
quit()
================================================
FILE: identity_matrix_recognizer.py
================================================
# from cs 101 course of udacity.com (problem set solved solution)
# Given a list of lists representing a n * n matrix as input,
# define a procedure that returns True if the input is an identity matrix
# and False otherwise.
# An IDENTITY matrix is a square matrix in which all the elements
# on the principal/main diagonal are 1 and all the elements outside
# the principal diagonal are 0.
# (A square matrix is a matrix in which the number of rows
# is equal to the number of columns)
def is_identity_matrix(matrix):
total_elems = 0
last_pos = 0
for row in matrix:
total_elems += len(row)
if row[last_pos] == 1 and row.count(0) == len(row) - 1:
last_pos += 1
else:
return False
if total_elems == len(matrix[0]) * len(matrix[0]):
return True
else:
return False
# Test Cases:
matrix1 = [[1,0,0,0],
[0,1,0,0],
[0,0,1,0],
[0,0,0,1]]
print is_identity_matrix(matrix1)
#>>>True
matrix2 = [[1,0,0],
[0,1,0],
[0,0,0]]
print is_identity_matrix(matrix2)
#>>>False
matrix3 = [[2,0,0],
[0,2,0],
[0,0,2]]
print is_identity_matrix(matrix3)
#>>>False
matrix4 = [[1,0,0,0],
[0,1,1,0],
[0,0,0,1]]
print is_identity_matrix(matrix4)
#>>>False
matrix5 = [[1,0,0,0,0,0,0,0,0]]
print is_identity_matrix(matrix5)
#>>>False
matrix6 = [[1,0,0,0],
[0,1,0,1],
[0,0,1,0],
[0,0,0,1]]
print is_identity_matrix(matrix6)
#>>>False
matrix7 = [[1, -1, 1],
[0, 1, 0],
[0, 0, 1]]
print is_identity_matrix(matrix7)
#>>>False
================================================
FILE: image_downloader.py
================================================
import random
import urllib.request
get = str(input("Enter url of image to download : "))
def download_image(url):
name = random.randrange(1, 1000)
full_name = str(name) + ".jpg"
urllib.request.urlretrieve(url, full_name)
print(download_image(get))
================================================
FILE: in_the_something.py
================================================
import random
# "The something in something" program
noun_lib = ["cat","dog","lizard","bald","insane guy","CEO","monkey","teacher","ballerina","old man","nerd","lion","alien","elephant"]
place_lib = ["in Hungary","in the toilet","in a car","in a zoo","in a lions cave","in a park","in Norway","in Rio","on Mars","on a tree","on the roof of Burj-Khalifa"]
flag = True
while flag:
inp = str(input("\nDo you want more? [Y/n] "))
if inp.strip().lower() == "y":
print("-> The" + " " + random.choice(noun_lib) + " " + random.choice(place_lib) + ".")
else:
flag = False
================================================
FILE: item_index.py
================================================
"""Algorithm for finding index of element in an array"""
def index(array, item):
index = 0
found = False
while (not found):
if (array[index] == item):
found = True
else:
index = index + 1
return index
print index([12, 34], 34)
================================================
FILE: kay_sort.py
================================================
"""
This sort is same as reverse sort by me.
Except minor changes in first for loop, and
comparison sign on line 11
And function is called kay_sort because
kay is my nickname
"""
def kay_sort(array):
print "Orignal List : {}".format(array)
for i in range(len(array)):
for n in range(len(array) - 1):
a = array[n]
if (a > array[i]):
tem = array[i]
array[i] = a
array[n] = tem
return "Sorted List : {}".format(array)
print kay_sort([123, 4, 123, 4])
================================================
FILE: lessThanMoreThan.py
================================================
nums = [12,34,65,43,21,97,13,57,10,32]
finalNums = []
moreFinalNums = []
def compareMore(a):
for x in nums:
if x > a :
c = finalNums.append(x)
def compareLess(d):
for x in nums:
if x < d :
c = moreFinalNums.append(x)
get = int(input('To Compare More Than : '))
getAgain = int(input('To Compare Less Than : '))
print('\nMore Than Values : ')
print(compareMore(get))
print(finalNums , '\n')
print('\nLess Than Values : ')
print(compareLess(getAgain))
print(moreFinalNums,'\n')
================================================
FILE: linear_search.py
================================================
# Linear Search or Sequential Search Algorithm
def linear_search(array, to_find):
pos = 0 # Starting position or index
to_return = (False, 0)
while (pos < len(array)): # while index is less than length of array
if (array[pos] == to_find): # if array with index of var pos is equal to find
to_return = (True, pos) # no need to break loop cuz return appends func
return to_return
else:
pos = pos + 1 # if elem not found continue to next pos
return to_return
nums = [12, 34, 54, 88, 21]
print linear_search(nums, 88)
================================================
FILE: listOperations.py
================================================
# list operations
# You can create a list by putting elements inside square brackets[]
# lists are capable of containing any type of data
# a list can contain datas of different datatypes
numsAndAlphas = ['a',1,'hello',3.14159265359,'are you okay',True,'good',False]
# this is going to work
print(numsAndAlphas)
# list accessing
# You can access single items from the list similar to string indexing
# if you dont know string indexing look for my program called stringOperations.py
print(numsAndAlphas[0])
print(numsAndAlphas[1:5])
print(numsAndAlphas[0:])
print(numsAndAlphas[:6])
print(numsAndAlphas[:])
print(numsAndAlphas[2:7:2])
print(numsAndAlphas[::3])
# you can add lists too...
list2 = [2,9,16,25,36,49,64,81,100,144]
newList = numsAndAlphas + list2
================================================
FILE: listOperationsMethods.py
================================================
# list operations part 2
siliconValley = ['Google','Apple','Dropbox','Facebook','Cisco','Adobe','Oracle','Samsung']
print(siliconValley)
# hmm seems like i forgot to add Electronic Arts in the list siliconValley
# This will add the element at the end of the list
siliconValley.append('Electronic Arts')
print(siliconValley)
# thats cool but I want my element at specific position
siliconValley.insert(5, 'AMD')
# 5 is the position and whatever you add after comma is element
# Okay enough I want to pop out an element from list and I want to use it in a string
# you have to provide the index of elementyou want to pop out
poppedElement = siliconValley.pop(4)
print('Popped element is ' + poppedElement)
# Oops I Samsung isnt in silicon valley, I have to remove Samsung from list
# How am I gonna do thats
# You have to enter the element in parenthesis and not it's index
siliconValley.remove('Samsung')
print(siliconValley)
# I want to sort the list in alphabetical order
# How to do thats
# simple
siliconValley.sort()
# or
sorted(siliconValley)
print(siliconValley)
# I wanted list in reverse alphabetical order
# simple
siliconValley.sort(reverse = True)
# or
sorted(siliconValley , reverse = True) # seperate the reverse with comma
print(siliconValley)
# Okay what if i dont know about the index of an element but i want to print only that element
googleIndex = siliconValley.index('Google')
print(siliconValley[googleIndex])
# I am tired of watching those elements again and again
# How I am going to do thats
# easy
del siliconValley
print(siliconValley) # this should probably give you an NameError
================================================
FILE: listReverse.py
================================================
getLi = [12,43,7,43,87,89,56,9809,9878,56,78,98,True,56,76]
reverseList = getLi[::-1] # [::-1] tells to step from end without difference
print(reverseList)
================================================
FILE: list_comprehensions.py
================================================
list_of_even_squares = [num ** 2 for num in range(0,101,2)]
print(list_of_even_squares , "\n")
list_of_odd_squares = [num ** 2 for num in range(1,102,2)]
print(list_of_odd_squares , "\n")
list_of_even_cubes = [num ** 3 for num in range(0,101,2)]
print(list_of_even_cubes , "\n")
list_of_odd_cubes = [num ** 3 for num in range(1,102,2)]
print(list_of_odd_cubes , "\n")
================================================
FILE: logarithm_integer.py
================================================
# Exhaustive numeration (iteration)
# Simple implementation of logarithmic function
# I love math!
# log(b, x) <=> b ** y = x
# So we have to find y!
# Don't use it for decimal numbers
# log(1000) or log(e, x) is not automatically avaliable
def logarithm_integer(b, x):
if (b > 0 and b != 1) and x > 0:
for i in range(x):
if b ** i == x:
return i
return -1
else:
return "Invalid input for logarithm"
# Test
print("log(6, 216) -> " + str(logarithm_integer(6, 216)))
print("log(5, 625) -> " + str(logarithm_integer(5, 25)))
print("log(4, 16) -> " + str(logarithm_integer(4, 16)))
print("log(2, 8) -> " + str(logarithm_integer(2, 8)))
print("log(3, 6) -> " + str(logarithm_integer(3, 6)))
print("log(0, 16) -> " + str(logarithm_integer(0, 16)))
================================================
FILE: madLibs.py
================================================
# my code may not work with python 3.5 cause it is made for 2.7 version
libs =["Dragon Freak","Excuses"]
# precode
def dragonFreak():
colorDrag = raw_input("Color : ")
superLatDrag = raw_input("Superlative (ending in est) : ")
adj1Drag = raw_input("Adjective : ")
bodyDragPlu = raw_input("Body Part Plural : ")
bodyDrag = raw_input("Body Part : ")
nounDrag = raw_input("Noun : ")
animalDrag = raw_input("Animal(Plural) : ")
adj2Drag = raw_input("Adjective : ")
adj3Drag = raw_input("Adjective : ")
adj4Drag = raw_input("Adjective : ")
# creating madlib
fMadLib = '''
The %s Dragon is the %s Dragon of all. It has %s %s,
and a %s shaped like a %s. It loves to eat %s,
although it will feast on nearly anything. It is %s and %s.
You must be %s around it, or you may end up as it`s meal!
'''%(colorDrag , superLatDrag , adj1Drag , bodyDragPlu , bodyDrag , nounDrag , animalDrag , adj2Drag , adj3Drag , adj4Drag)
print(fMadLib)
def excuses():
place = raw_input("Place : ")
adjExcuse = raw_input("Adjective : ")
bodyPart = raw_input("Bodypart : ")
fMadLib = '''
I cannot come to %s ,
because there is %s %s flu
''' %(place , adjExcuse , bodyPart)
print(fMadLib)
# main code for user interaction
while True:
startOrEnd = raw_input("Start or End : ")
if startOrEnd.strip() == "Start":
print(libs)
whichLib = raw_input("Which one :")
if whichLib.strip() == "Dragon Freak":
print(dragonFreak())
continue
elif whichLib.strip() == "Excuse":
print(excuses())
continue
else :
print("Not avaliable")
continue
elif startOrEnd.strip() == "End":
print("Progarm Ended...")
break
================================================
FILE: magicball_8.py
================================================
import random
def magic():
input("Ask me a question . Try me: ")
return random.choice([ "It is certain" , "Outlook good" , "You may rely on it" , "Ask again later" , "Concentrate and ask again" , "Reply hazy, try again" , "My reply is no" , "My sources say no" ])
# main Sector
print("Hello,")
while True:
if input("start or end: ").strip().lower() == "start":
print(magic(), "\n")
continue
else:
quit()
================================================
FILE: map_example.py
================================================
# Contribution by https://github.com/tyadav4268
#This is to demonstrate the use of map function in python
#Problem Statement: Using the function Map, count the number of words that start with ‘S’ in input_list.
#Sample Input: ['Santa Cruz','Santa fe','Mumbai','Delhi']
#Sample Output: 2
#Solution:
input_list = ['Santa Cruz','Santa fe','Mumbai','Delhi']
count = sum(map(lambda x: x[0] == 'S', input_list))
print(count) # Output: 2
================================================
FILE: math/Binary_to_decimal
================================================
# binary_to_decimal.py
#
# Description: A program to evaluate binary to decimal.
#
# Author: Chaitanya Mittal
# Date: 2023-11-17 10:14:20.288913
"""Idea:
- def a function to decode 1 byte:
- get the list
- get value by multiplying each element with 2** its index from reverse (pattern observation)
.... (instead of this we can multiply index to list reversed)......
- return the sum of value
- get input
- split it to get rid of spaces (assume user is well behaved and will enter 1-space separated string only)
- convert each byte and compile result in a list
- print the converted bytes separated by space
"""
def byte_decode(binary):
# Convert binary string to list
lst = list(binary)[::-1]
# Initialize variables
length = len(binary)
sum = 0
# Loop through each character in the binary string
for i in range(length):
# Calculate value of each bit
value = int(lst[i]) * (2 ** i)
# Add value to the sum
sum += value
# Return the final sum
return sum
# ____ Main Program ____ #
# Get input of the required binary string
binary = input("Binary: ").split(" ")
""" TESTING PURPOSES
string = ("01010101 01101110 01100100 01100101 0110010 00100000 01011001 01101111 01110101 01110010 00100000 01010011 01100101 01100001 01110100").split()
binary = list(string)"""
# Initialize an empty list to store 'evaluated' bytes
bytes_translated = list()
#translate the byte and append it to the list
for byte in binary:
bytes_translated.append(byte_decode(byte))
# Print the output
print(f'Evaluated: ', end = "")
for byte in bytes_translated:
print(byte, end = " ")
print()
================================================
FILE: math/FreefallCalculator
================================================
# Gravity Simulation
import math
import numpy as np
# Welcome
print("Welcome to a 1D Free Fall Simulation. Please enter only in metric integers. ")
print("You will enter the amount of time you want to simulate, it includes information about impact, \n"
"even if the simulation stops before impact.")
# Constants
g = 9.81
# Variables
height = int(input("Drop Height: "))
timeElapsed = 1
runTime = int(input("How long do you want to record data from the fall? "))
location = 0
mass = int((input("Mass: ")))
timeToImpact = 0
# Simulation
print("Second by second info of free fall in given time.")
while timeElapsed <= runTime and timeToImpact >= 0 and location >= 0:
# Equations
distanceTraveled = (g * timeElapsed ** 2) / 2
velocity = distanceTraveled / timeElapsed
location = height - distanceTraveled
momentum = mass * velocity
timeToImpact = math.sqrt((2 * height) / g)
# Print Stats
print("\nTime to simulation end: " + str(runTime - timeElapsed))
print('Y Location: ' + str(location) + 'M')
print('Velocity: ' + str(velocity) + 'M/S')
print('Distance Traveled: ' + str(distanceTraveled) + 'M')
print('Momentum: ' + str(momentum) + 'N')
print('Time Elapsed: ' + str(timeElapsed))
print('Rough time to impact: ' + str(timeToImpact - timeElapsed))
print()
# Add to time elapsed
timeElapsed = timeElapsed + 1
# Print impact results
print("\n The Simulation is done. \n")
print("*This is printed even if the object fell past the ground, or never hit it.* \n Info on impact: ")
print('Y Location: 0M')
print('Velocity: ' + str(height / runTime) + 'M/S')
print('Distance Traveled: ' + str(height) + 'M')
print('Momentum: ' + str(mass * (height / runTime)) + 'N')
print('Time Spent in free fall: ' + str(timeToImpact))
print()
================================================
FILE: math/README.md
================================================
'math' Sub-directory contains all the math related scripts
This dir does not contain mathematical algorithms,
only math related scripts
The programs have been re-checked and re-mastered by me!
Although i've tried to keep it as orignal as possible.
Keep Patience It'll take time to go through every program!! Thanks
================================================
FILE: math/aircraft_thrust.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import math
# Calculating thrust of Aircraft Propeller
def thrust_props(diameter , velocity , velocity1 , density):
# According to formula
return math.pi / 4 * diameter ** 2 * (velocity + velocity1/2) * density * velocity1
print('Hello Aircraft Lovers,\n')
while(True):
# Loop for continous calculation
start_or_end = str(raw_input('start or end : ')).strip().lower()
# Main interface
if start_or_end == 'start':
res = thrust_props(float(input('\nDiameter of propeller: ')) , float(input('Velocity of air flow: ')) , float(input('Additional propeller acceleration, velocity: ')) , float(input('Fluid density: ')))
print("\nThrust of propeller: {}".format(res))
else:
quit()
print("")
# found formula on nasa's website
================================================
FILE: math/area_volume_calculator.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import math
import sys
# Perimeter
# or sum of span of all sides of figure
# perimeter of square f(s) = 4 * s
# where s is the side of square
peri_of_square = lambda s: 4 * s
# perimeter of rectangle, f(L, W) = 2 * (L + W) or 2L + 2W
# where L is length, and W is width(breadth) of rectangle
peri_of_rectangle = lambda l, w: 2 * (l + w)
# perimeter of triangle, f(s1, s2, s3) = s1 + s2 + s3
# where s1, s2, s3, are the sides of a regular triangle
peri_of_triangle = lambda s1, s2, s3: s1 + s2 + s3
# peri of right angled triangle, f(a, b) = a + b + square_root(a ** 2 + b ** 2)
# since, by pythagoras theoram,
# a ** 2 + b ** 2 = c ** 2 or a squared + b squared = c squared
peri_of_rt_triangle = lambda a, b: a + b + math.sqrt(a ** 2 + b ** 2)
# perimeter of circle(or circumference), f(r) = 2 * r * pi
# or f(d) = d * pi, where r is radius, pi is pi ratio(3.14159......),
# d is diameter
peri_of_circle = lambda r: 2 * r * math.pi
peri_of_circle1 = lambda d: d * math.pi
# Areas
# or surface area of figure
# how many lengths into widths and vice versa
# area of square, f(s) = s * s or (s)squared or s ** 2
# where s is the side of square, s is same as both
# length and width of square
area_of_square = lambda s: s ** 2
# area of rectangle, f(L, W) = L * W
# or length multiplied by width(breadth)
area_of_rectangle = lambda l, w: l * w
# area of triangle, f(b, h) = b * h / 2
# where, b is base, and h is the height of triangle
# see: explaination of area of triangle
# here:
area_of_triangle = lambda b, h: (b * h) / 2
# Heron's formula
# see for more info: https://en.wikipedia.org/wiki/Heron%27s_formula
area_of_triangle1 = lambda a, b, c: math.sqrt((a+b+c)/2 * ((a+b+c)/2 - a) ((a+b+c)/2 - b) ((a+b+c)/2 - c))
# area of parallelogram, f(b, h) = b * h
# where b is base, h is height of parallelogram
area_of_parallelogram = lambda b, h: b * h
# area of trapezoid(trapezium), f(b1, b2, h) (b1 + b2) / 2 * h
# where, b1 is base 1, b2 is base 2, and h is height
area_of_trapezoid = lambda b1, b2, h: (b1 + b2) / 2 * h
# area of circle, f(r) = pi * r ** 2
# where r is radius, pi is math constant of pi(C/D)
# see explaination of formula:
# http://pythagoreanmath.com/complete-explanation-for-area-of-a-circle-formula/
area_of_circle = lambda r: math.pi * r ** 2
# Terminal UI
i = 0
while True:
if raw_input("\n[{}] Exit(press e), Continue(press c): ".format(i)).lower() == "c":
which_fig = raw_input("\nSquare(s), Rectangle(r), Triangle(t), right(|_)led triangle(rt), Parallelogram(pa), Cricle(ci), Trapezoid(tr): ").lower()
if which_fig == "s":
if raw_input("\nArea(press a) or Perimeter(press p): ").lower() == "a":
print("\tArea of square: " + str(area_of_square(float(raw_input("Side of square: ")))))
else:
print("\tPerimeter of square: " + str(peri_of_square(float(raw_input("Side: ")))))
elif which_fig == "r":
if raw_input("\nArea(press a) or Perimeter(press p): ").lower() == "a":
print("\tArea of rectangle: " + str(area_of_rectangle(float(raw_input("Length: ")), float(raw_input("Width: ")))))
else:
print("\tPerimeter of rectangle: " + str(peri_of_rectangle(float(raw_input("Length: ")), float(raw_input("Width: ")))))
elif which_fig == "t":
if raw_input("\nArea(press a) or Perimeter(press p): ").lower() == "a":
if raw_input("\nBy Heron's Formula[y/n]: ").lower() == "y":
print("\tArea of triangle(Heron's Formula): " + str(area_of_triangle1(float(raw_input("A: ")), float(raw_input("B: ")), float(raw_input("C: ")))))
else:
print("\tArea of triangle: " + str(area_of_triangle(float(raw_input("Base: ")), float(raw_input("Height: ")))))
else:
print("\tPerimeter of triangle: " + str(peri_of_triangle(float(raw_input("A: ")), float(raw_input("B: ")), float(raw_input("C: ")))))
elif which_fig == "rt":
if raw_input("\nArea(press a) or Perimeter(press p): ").lower() == "a":
print("\tArea of triangle: " + str(area_of_triangle(float(raw_input("Base: ")), float(raw_input("Height: ")))))
else:
print("\tPerimeter or right angled triangle: " + str(peri_of_rt_triangle(float(raw_input("A: ")), float(raw_input("B: ")))))
elif which_fig == "pa":
if raw_input("\nArea(press a) or Perimeter(press p): ").lower() == "a":
print("\tArea of parallelogram: " + str(area_of_parallelogram(float(raw_input("Base: ")), float(raw_input("Height: ")))))
else:
print("\tPerimeter of parallelogram: " + str(peri_of_rectangle(float(raw_input("Length: ")), float(raw_input("Width: ")))))
elif which_fig == "tr":
if raw_input("\nArea(press a) or Perimeter(press p): ").lower() == "a":
print("\tArea of trapezoid: " + str(area_of_trapezoid(float(raw_input("Base 1: ")), float(raw_input("Base 2: ")), float(raw_input("Height: ")))))
else:
print("\tPerimeter of trapezoid: " + str(peri_of_triangle(float(raw_input("Side1: ")), float(raw_input("Side4: ")), float(raw_input("Side3: "))) + float(raw_input("Side1: "))))
elif which_fig == "c":
if raw_input("\nArea(press a) or Perimeter(press p): ").lower() == "a":
print("\tArea of circle: " + str(area_of_circle(float(raw_input("Radius: ")))))
else:
if raw_input("\nUsing Radius(r) or Diameter(d): ").lower() == "r":
print("\tCircumference of circle: " + str(peri_of_circle(float(raw_input("Radius: ")))))
else:
print("\tCircumference of circle: " + str(peri_of_circle1(float(raw_input("Diameter: ")))))
i += 1
else:
sys.exit()
================================================
FILE: math/arithmetic_progression_builder.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Arithmetic progressions
# are special types of sets(more of a series)
# where the difference between every consecutive
# numbers of series is constant or common
# for more refer: https://en.wikipedia.org/wiki/Arithmetic_progression
# formula for general term of arithmetic prog.
# tn = a + (n - 1) * d
# where,
# tn -> is the n(th) term,
# a -> if the first term,
# d -> is the common difference
# Third param 'n_last' refers to limit or length or index of last term
def arithmetic_p_sequence_builder(a, d, n_last):
# To generate an A.P. length should be
# greater than or equal to 1
if n_last < 1:
return -1
seq = []
# Every item is obtained by
# applying the general term formula
for n in range(1, n_last + 1):
seq.append(a + (n - 1) * d)
return seq
# Test
print("Arithmetic progression: {}".format(arithmetic_p_sequence_builder(int(raw_input("A(a, first term): ")), int(raw_input("D(d, common difference): ")), int(raw_input("N(n, length): ")))))
# Although big line, but works just fine!
================================================
FILE: math/calculator.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# Functions to apply basic arithmetic
# operations on 2 numbers
# Each func, takes 2 numbers as input
add = lambda a, b: a + b
subtract = lambda a, b: a - b
multiply = lambda a, b: a * b
divide = lambda a, b: a / b
modulus = lambda a, b: a % b
# CLI
# Testing/Playing Interface
i = 0
while True:
if raw_input("\n\n[{}] Exit(press e) or Calculate(press c): ".format(i)) == "c":
op = raw_input("\nAdd(press a), Subtract(press s), Multiply(press m),\nDivide(press d), Modulus(press mo): ").strip().lower()
if op == "a":
print(" Sum: " + str(add(float(raw_input("\nN1: ")), float(raw_input("N2: ")))))
elif op == "s":
print(" Subtracted: " + str(subtract(float(raw_input("\nN1: ")), float(raw_input("N2: ")))))
elif op == "m":
print(" Multiplied: " + str(multiply(float(raw_input("\nN1: ")), float(raw_input("N2: ")))))
elif op == "d":
print(" Divided: " + str(divide(float(raw_input("\nN1: ")), float(raw_input("N2: ")))))
else:
print(" Modulus: " + str(modulus(float(raw_input("\nN1: ")), float(raw_input("N2: ")))))
i += 1
else:
print("\nHope you enjoyed!")
sys.exit()
================================================
FILE: math/decimal_to_binary_converter.py
================================================
"""
I came up with this algorithm to convert decimal(natural numbers only xd) to binary completely from scratch and
therefore it might not be the best most efficient implementation.
Optimizations are welcome.
"""
def dec_to_bin(n):
quo = n
binary = 0
while (quo>0):
tmp = quo
pows = 0
while (quo > 1):
quo = quo // 2
pows = pows + 1
quo = tmp-pow(2,pows)
binary = binary+pow(10,pows)
return binary
for i in range(0,101):
print("Natural Number:"+str(i)+" Binary:"+str(dec_to_bin(i)))
================================================
FILE: math/eulers_python.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# By formula derived by Euler(A great mathematician)
print("Euler's Formula: F(faces) + V(vertices) = E(Edges)+2\n")
# Further derivation
print("Derivation 1: E(Edges) = F(faces)+V(vertices) - 2")
print("Derivation 2: V(vertices) = E(edges)+2 - F(Faces)")
print("Derivation 3: F(faces) = E(edges)+2 - V(vertices)")
# By order of operations, parenthesis can be added
# for ensuring, but not needed
def E(f, v):
return f+v - 2
def V(e, f):
return e+2 - f
def F(e, v):
return e+2 - v
# function to evaluate
# By default datatype of raw_input() is string
user = raw_input("\nE, V or F: ").upper()
print(" ")
# evaluating function asked by user
if user == "E":
print("\nEdges: " + str(E(input("Faces: "), input("Vertices: "))))
elif user == "V":
print("\nVertices: " + str(V(input("Edges: "), input("Faces: "))))
elif user == "F":
print("\nFaces: " + str(F(input("Edges: "), input("Vertices: "))))
else:
print("Invalid Input, Try again!")
# A while loop can be added
# to perform multiple calculations
================================================
FILE: math/geoMean.py
================================================
# Add path, encoding
import math
# Geometric Mean:
# Calculates the geometric mean of
# two numbers
# formula: f(x, y) = square_root(x*y)
geoMean = lambda x, y: math.sqrt(x*y)
while True:
if input("Start [Y/n]? ").strip().lower() == "y":
print(" [Res] = " + str(geoMean(float(input("\nX? ")), float(input("Y? ")))) + "\n\n")
else:
print("\n\nGoodBye!")
break
================================================
FILE: math/number_lesser_greater.py
================================================
import sys
# Use of
# Conditionals in python
# Determines weather the number is positive negative or zero
def pos_neg_zero(x):
if x < 0: return "Negative"
elif x > 0: return "Positive"
return "Zero"
while True:
if str(raw_input(" Start [Y/n]? ")).strip().lower()== "y":
print(" [Num] = " + pos_neg_zero(float(raw_input(" Number: "))) + "\n")
else:
print("Bye!")
sys.exit(0)
================================================
FILE: mathoperators.py
================================================
# maths sucks make it cool with python
# math operators
# INTEGERS
# integers are whole numbers positive or negative
# + operator adds numbers
add = 24 + 1004
# - operator subtracts second number from First
subtract = 546 - 132
# * multiplies numbers
multiply = 90 * 4
# / divides numbers
divide = 36/6
# returns the remainder of the division
modulo = 17 % 3
# FLOAT
# floats are decimal point numbers positive or negative
addFloat = 24.5 + 1004.005
subtractFloat = 546.90 - 132.56
multiplyFloat = 90.0 * 4.2
divideFloat = 36.6 / 6.6
moduloFloat = 17.0 % 3.0
# all operators work same on both floats or integers
================================================
FILE: max_by_alphabetical_order.py
================================================
import string
def lower_(arr):
"""
For conversion of every element in list to lower
"""
for i in range(len(arr)):
arr[i] = arr[i].lower()
def max_alphabetical_order(s):
"""
Useful on lists containing strings that start from alphabets,
because the algorithm is written for it in the first place!
"""
copy = s[:]
useful = list(string.ascii_lowercase)
lower_(s)
res = s[0]
for word in s[1:]:
tmp = word[0]
if useful.index(tmp) > useful.index(res[0]):
res = word
return copy[s.index(res)]
# Test
case1 = ["Alpha", "Beta", "Gist", "exotic", "hells kitchen", "word", "Ultra", "zip"]
call = max_alphabetical_order(case1)
print("Max element in list by alphabet order:\n" + call)
================================================
FILE: max_int_in_list.py
================================================
def compare(li):
res = 0
for i in range(len(li) - 1):
a = li[i]
b = li[i + 1]
if (a > b):
if (a > res):
res = a
else:
if (b > res):
res = b
return res
def convert():
get_input = raw_input("Enter Space Seperated Numbers : ")
raw = get_input.split()
nums = []
for i in raw:
nums.append(float(i))
return nums
if __name__ == "__main__":
print compare(convert())
================================================
FILE: min_by_alphabetical_order.py
================================================
import string
def lower_(arr):
"""
For conversion of every element in list to lower
"""
for i in range(len(arr)):
arr[i] = arr[i].lower()
def min_alphabetical_order(s):
"""
Useful on lists containing strings that start from alphabets,
because the algorithm is written for it in the first place!
"""
copy = s[:]
useful = list(string.ascii_lowercase)
lower_(s)
res = s[0]
for word in s[1:]:
tmp = word[0]
if useful.index(tmp) < useful.index(res[0]):
res = word
return copy[s.index(res)]
# Test
case1 = ["Alpha", "Beta", "Gist", "exotic", "hells kitchen", "word", "Ultra", "zip"]
call = min_alphabetical_order(case1)
print("Max element in list by alphabet order:\n" + call)
================================================
FILE: min_int_in_list.py
================================================
def compare(li):
if (len(li) == 1):
return "Single Value To Compare {} in List".format(li[0])
res = 0
for i in range(len(li) - 1):
a = li[i]
b = li[i + 1]
if (a < b):
if (i != 0):
if (a < res):
res = a
else:
res = a
else:
if (i != 0):
if (b < res):
res = b
else:
res = b
return res
def convert():
get_input = raw_input("Enter Space Seperated Numbers : ")
raw = get_input.split()
nums = []
for i in raw:
nums.append(float(i))
return nums
if __name__ == "__main__":
print compare(convert())
================================================
FILE: mod_example.py
================================================
import random
import urllib.request
def downloadImage(url):
filename = str(random.randrange(1,1000))
download = urllib.request.urlretrieve(url, filename)
downloadImage()
================================================
FILE: modified_selection_sort.py
================================================
"""
My Modified Solution to Selection Sort Algorithm,
instead of swapping elem it is appended to another
temporary array. This makes algotrihm less complicated.
"""
def selection_sort(array):
temp_num = len(array)
temp_arr = []
while (len(temp_arr) != temp_num):
a = min(array)
temp_arr.append(a)
del array[array.index(a)]
return temp_arr
# Test
test_case = [100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90]
print("By Builtin method: {}".format(sorted(test_case)))
print("By SelectionSort method: {}".format(selection_sort(test_case)))
================================================
FILE: morse_code_decoder.py
================================================
def decodeMorse(morseCode):
# ToDo: Accept dots, dashes and spaces, return human-readable message
morse_code = {".-" : "A",
"-..." : "B",
"-.-." : "C",
"-.." : "D",
"." : "E",
"..-." : "F",
"--." : "G",
"...." : "H",
".." : "I",
".---" : "J",
"-.-" : "K",
".-.." : "L",
"--" : "M",
"-." : "N",
"---" : "O",
".--." : "P",
"--.-" : "Q",
".-." : "R",
"..." : "S",
"-" : "T",
"..-" : "U",
"...-" : "V",
".--" : "W",
"-..-" : "V",
"-.--" : "Y",
"--.." : "Z",
".----" : "1",
"..---" : "2",
"...--" : "3",
"....-" : "4",
"....." : "5",
"-...." : "6",
"--..." : "7",
"---.." : "8",
"----." : "9",
"-----" : "0",
"SPACE" : " "}
morseCode.strip()
new = morseCode.replace(" ", " SPACE ")
prep = new.split()
res = ""
li = list(morse_code.keys())
for n in prep:
elif n in li:
res = res + morse_code[n]
else:
pass
return res.strip()
================================================
FILE: multiplicationTables.py
================================================
# Multiplication Table viewer
while True:
startOrEnd = str(input('Start or End : '))
if startOrEnd == 'Start':
whichTable = int(input('Which Table : '))
for x in range(1, 13):
table = whichTable * x
print(table)
continue
else :
print('Program Ended...')
break
================================================
FILE: my_name.py
================================================
# Example of accessing elements in list
inside = list("abcdefghijklmnopqrs tuvwyxyz")
print (inside[10] + inside[0] + inside[11] + inside[15] + inside[0] + inside[10] + inside[19] + inside[20] + inside[0] + inside[10] + inside[4])
================================================
FILE: nearest_square_and_its_root.py
================================================
# Find the nearest root and its square
def nearest_square(n):
i = 0
found = False
while (not found):
if i ** 2 <= n < ((i + 1) ** 2):
found = True
else:
i += 1
return (i, i ** 2)
# Test
case = 40
res = nearest_square(case)
print("Nearest square to {}: \n{}".format(case, res[1]))
================================================
FILE: network/are_you_connected_to_world.py
================================================
import os
import sys
import webbrowser
from time import sleep as sleep_sheep
# Executing ping with input host
# using systems functionality (only linux)
def ping(host):
instr = "ping -c 1 %s" %(host)
response = os.system(instr)
return response == 0
# Finite state loop if
# computer re-connects to network
# else will run till re-conn
def you_cant_be_dead(host):
if (not ping(host)):
# Status update
print(" [.] Status -> Not connected to network")
print(" / CONSTANTLY Re-CHECKING CONNECTIVITY... /")
while (True):
if not ping(host): continue
else: break
# Connectivity is checked
# every 7 secs
sleep_sheep(7)
return True
def exit_(status):
if (status == 0 or status == 1):
print("\n ~ See you soon!")
sys.exit(status)
else:
return None
# User
# Shell Interface
while True:
if raw_input("\nStart [Y/n]? ").strip().lower() == "y":
inp = raw_input("URI (alive) HOST: ").strip()
print("\n > CHECKING CONNECTION...\n > Host -> %s\n" % inp)
if you_cant_be_dead(inp):
# When connected to internet
# Status update, and proof of connection
print("\n [.] Status -> CONNECTED to network")
webbrowser.open("https://www.youtube.com/watch?v=JbjIH5pvT5A")
exit_(0)
else:
exit_(0)
================================================
FILE: newOnContacts.py
================================================
# pre code
# main list of contacts
contacts = {}
# funcs of pre code
# func to add new contact
def newContact():
while True:
newContact = raw_input("Name for new Contact : ")
numForNewContact = raw_input("Number for Contact : ")
add = raw_input("Add or Try again :")
if add.strip() == "Add":
contacts[newContact] = numForNewContact
print("Contact Successfully added.")
break
elif add.strip() == "Try again":
continue
else :
print("Invalid Input.try again")
continue
startAgain = raw_input("Add more or continue : ")
if startAgain.strip() == "Add more":
print(" ")
continue
elif startAgain.strip() == "continue":
print(" ")
break
# func to search for a contact
def searchContact():
while True:
search = raw_input("Search for contact : ")
toShow = str(search) + contacts[search]
print(toShow)
startAgain = raw_input("Search more or continue : ")
if startAgain.strip() == "Search more":
print(" ")
continue
elif startAgain.strip() == "continue":
print(" ")
break
# func to edit a contact
def editContact():
while True:
whichToEdit = raw_input("Name of Contact of which Number to Edit : ")
contacts[whichToEdit] = raw_input("Number to add : ")
startAgain = raw_input("Edit more or continue : ")
if startAgain.strip() == "Edit more":
print(" ")
continue
elif startAgain.strip() == "continue":
print(" ")
break
# main code to interact
while True:
print("hello,".title())
# part of main code to start or end
startOrEnd = raw_input("Start or End : ")
if startOrEnd.strip() == "Start":
# part of main code to control functions
addSearchEdit = raw_input("Add or Search or Edit : ")
if addSearchEdit.strip() == "Add":
print(newContact())
elif addSearchEdit.strip() == "Search":
print(searchContact())
elif addSearchEdit.strip() == "Edit":
print(editContact())
else :
print("Invalid Input . Try Again")
continue
elif startOrEnd.strip() == "End":
print("Ending...")
break
else :
print("Invalid Input . Try Again")
continue
# part of main code to start again or end
startAgain = raw_input("Start again or End : ")
if startAgain.strip() == "Start again":
print("Starting again...")
continue
elif startAgain.strip() == "End":
print("Ending program...")
break
else :
break
================================================
FILE: non_multiples.py
================================================
number_to_check = int(input("Number : "))
till_where = int(input("Till where to check : "))
list_of_non_multiples = []
for num in range(0, till_where + 1):
if num % number_to_check != 0:
list_of_non_multiples.append(num)
print(list_of_non_multiples)
# or you can do
# this
print(" ")
for element in list_of_non_multiples:
print(element)
================================================
FILE: ordered_binary_search.py
================================================
def binary_search(array, n):
arr = sorted(array)
to_return = False
first_elem = 0
last_elem = len(arr) - 1
while (first_elem <= last_elem):
mid = (first_elem + last_elem) // 2
if (arr[mid] == n):
to_return = True
break
else:
if (n > arr[mid]):
first_elem = mid + 1
else:
last_elem = mid - 1
return to_return
def Ordered_binary_search(arra, elem):
if (len(arra) == 0):
return False
middle = len(arra) // 2
if (arra[middle] == elem):
return True
else:
if (elem > arra[middle]):
return binary_search(arra[middle:], elem)
else:
return binary_search(arra[:middle], elem)
nums = [0,23,54,5,32,78]
print Ordered_binary_search(nums, 32)
print Ordered_binary_search(nums, 5)
================================================
FILE: otherAngle.py
================================================
def complementary():
while(True):
complementary = float(input('Complementary of : '))
if complementary <= 90:
complement = 90 - complementary
return(complement)
break
else:
print('Number greater than 90 degree. Try again')
continue
def supplementary():
while(True):
supplementary = float(input('Supplementary of : '))
if supplementary <= 180:
supplement = 180 - supplementary
return(supplement)
break
else:
print('Number greater than 180 degree. Try again')
continue
while(True):
countOrEnd = str(input('Count or End : '))
if countOrEnd.strip() == 'Count':
print('\nSupp for supplementary\nComp for complementary')
getSuppOrCom = str(input('Supp or Comp : '))
if getSuppOrCom.strip() == 'Supp':
print(supplementary())
continue
elif getSuppOrCom.strip() == 'Comp':
print(complementary())
continue
else:
break
else:
quit()
================================================
FILE: password_creator.py
================================================
"""
Why to create strong password?
Because it makes the chances of hackers bruteforcing your password to almost 0%
Simply to not get hacked!
"""
import random
import string
# Password level is Strong!
# Creates a alphanumeric password of `n` chars
def create_password(n):
allChars = list(string.ascii_letters) + list(string.digits) + list(string.punctuation)
passphrase = []
for i in range(n):
tmp = random.choice(allChars)
passphrase.append(tmp)
res = "".join(passphrase)
return res
# Test 1
test1 = create_password(16)
print(test1)
# Test 2
test2 = create_password(32)
print(test2)
================================================
FILE: percentageCalc.py
================================================
# Percentage Calculator
def percentToOrig():
whatPercent = float(input('What Percent : '))
ofWhat = float(input('Of What Percent : '))
orignal = whatPercent / 100 * ofWhat
print(orignal)
print(percentToOrig())
================================================
FILE: percentage_increase_decrease.py
================================================
# Percantage Increase , Percentage Decrease
def increasePercent(increase , origValue):
return(str(increase / origValue * 100) + '%')
def decreasePercent(decrease , origValue):
return(str(decrease / origValue * 100) + '%')
print('Hello,\nPress Enter To Exit')
incOrDec = str(input('increase or decrease: ')).strip().lower()
if incOrDec == 'increase':
print(increasePercent(float(input('Increased Value : ')) , float(input('Orignal Value : '))))
elif incOrDec == 'decrease':
print(increasePercent(float(input('Increased Value : ')), float(input('Orignal Value : '))))
else:
quit()
================================================
FILE: physics.py
================================================
# physics calcy
operations = [ "Preassure" , "Force" , "Speed" , "Velocity" , "Accelaration" , "Momentum" ]
#pre code sector I
# preassure function to calculate preassure
def preassure():
print(" ")
force = int(raw_input("Enter force : "))
print(" ")
area = int(raw_input("Enter area : "))
preassure = force / area
print(" ")
print("Preassure is " + str(preassure) + "pascal")
# force function to calculate force
def force():
print(" ")
mass = int(raw_input("Enter mass : "))
print(" ")
accelaration = int(raw_input("Enter accelaration : "))
force = mass * accelaration
print(" ")
print("Force is " + str(force) + "newton")
# speed func to calculate speed of object
def speed():
print(" ")
distance = int(raw_input("Enter distance : "))
print(" ")
time = int(raw_input("Enter time taken : "))
speed = distance / time
print(" ")
print("Speed of object is " + str(speed))
# velocity func to calculate velocity of object
def velocity():
print(" ")
displacement = int(raw_input("Enter displacement : "))
print(" ")
time = int(raw_input("Enter time taken : "))
velocity = displacement / time
print(" ")
print("Velocity of object is " + str(velocity))
# accelaration func to calculate accelaration
def accelaration():
print(" ")
initialV = int(raw_input("Enter initial velocity : "))
print(" ")
finalV = int(raw_input("Enter final velocity : "))
print(" ")
time = int(raw_input("Enter time taken : "))
acce = (finalV - initialV) / time
print(" ")
print("Accelaration is " + str(acce) + "m/s sq.")
# monentum func to calculate momentum
def moment():
print(" ")
mass = int(raw_input("Enter mass : "))
print(" ")
velocity = int(raw_input("Enter velocity : "))
print(" ")
momentum = mass * velocity
print(" ")
print("Momentum is " + str(momentum))
# CLI code sector II
while True:
print(" ")
print("Hello")
print(" ")
startOrEnd = raw_input("Start or End : ")
print(" ")
if startOrEnd.strip() == "Start" :
for op in operations:
print(op)
print(" ")
main = raw_input("Which operation : ")
if main.strip() == "Preassure":
print(preassure())
continue
elif main.strip() == "Force":
print(force())
continue
elif main.strip() == "Speed":
print(speed())
continue
elif main.strip() == "Velocity":
print(velocity())
continue
elif main.strip() == "Accelaration":
print(accelaration())
continue
elif main.strip() == "Momentum":
print(moment())
continue
else :
print("Invalid operation")
continue
elif startOrEnd.strip() == "End":
print("...Progarm Ended...")
break
================================================
FILE: pigLatin.py
================================================
# Pig Latin Word Altering Game
# function to convert word in pig latin form
def alterWords():
wordToAlter = str(input('Word To Translate : '))
alteredWord = wordToAlter[1:] + wordToAlter[0:2] + 'y' # translating word to pig latin
if len(wordToAlter) < 46 :
print(alteredWord)
else :
print('Too Big . Biggest Word in English Contains 45 characters.')
# main interaction code
while True:
startOrEnd = str(input('Start or End : '))
if startOrEnd == 'Start':
print(' ')
print(alterWords())
continue
else :
quit()
================================================
FILE: piggyBank.py
================================================
# piggy bank
# pre code
money = 0
# function to add money to current amount
def addMoney():
print(" ")
userAdd = float(raw_input("Add money : "))
print(" ")
money = money + userAdd
print("After adding current Money you have is " + str(money) + " rupees")
# function to withdraw money from current amount
def withdrawMoney():
print(" ")
userWithdraw = float(raw_input("Add money : "))
print(" ")
money = money + userWithdraw
print("After adding current Money you have is " + str(money) + " rupees")
# function to display current amount
def currentMoney():
print(" ")
current = "Current money you have is " + str(money) + " rupees"
# main code
print(" ")
print("--------------------Start-------------------")
while True:
print(" ")
user = raw_input("Start or End : ")
if user.strip() == "Start":
controlPiggy = raw_input("Add Withdraw or Check : ")
if controlPiggy.strip() == "Add":
print(addMoney())
continue
elif controlPiggy.strip() == "Withdraw":
print(withdrawMoney())
continue
elif controlPiggy.strip() == "Check":
print(currentMoney())
continue
else :
print(" ")
print("Invalid Input.Try again")
continue
elif user.strip() == "End" :
print(" ")
print("------------Program Ended-----------")
print(" ")
break
else :
print(" ")
print("Invalid Input. Try again")
continue
================================================
FILE: ping_host.py
================================================
import os
import platform as plt
def ping_host(host_name):
ping_str = "-c 1"
if plt.system().lower() == "Windows":
ping_str = "-n 1"
ping = "ping " + ping_str + " " + host_name
resp = os.system(ping)
return resp == 0
# Test
test_host = "www.google.co.in"
result = ping_host(test_host)
if result:
print("\nStatus ({}): Is Alive".format(test_host))
else:
print("\nStatus ({}): Is Dead".format(test_host))
================================================
FILE: primeNumbers.py
================================================
# Prime number Determiner
# replace input() with raw_input() in Python version 2.7 input() works with version 3
import math as Math
POSITIVE_MESSAGE = " is a prime number"
NEGATIVE_MESSAGE = " is not a prime number"
def is_number_prime(number):
"""
Function which checks whether the number is a prime number or not
:param number: integer - to be checked for prime-ness
:return: boolean - true if prime, else false
"""
"""
This is the main logic behind reducing the numbers to check for as factors
if N = a * b; where a<=b and a,b C (1, N)
then, a * b >= a*a;
which leads to => a*a <= N
=> a <= sqrt(N)
Hence checking only till the square root of N
"""
upper_lim = Math.floor(Math.sqrt(number)) + 1
is_prime = True if number != 1 else False
for i in range(2, upper_lim):
if number % i == 0:
is_prime = False
break
# The moment there is a divisor of 'number', break the iteration, as the number is not prime
return is_prime
while True:
startOrEnd = str(input('Start or End : '))
if startOrEnd == 'Start':
number = int(input('Number to Check : '))
result = str(number)
prime_status = is_number_prime(number)
if prime_status:
result += POSITIVE_MESSAGE
else:
result += NEGATIVE_MESSAGE
print(result)
else:
print('Program Ended...')
break
================================================
FILE: profitLoss.py
================================================
# Profit Loss Calculator
def profit(sellP , costP):
profit = sellP - costP
return(profit) # Function for calculating profit
def loss(costP , sellP):
loss = costP - sellP
return(loss) # Function for calculating loss
def profitPercent(prof , costP):
profitPerc = prof / costP * 100
return(str(profitPerc) + '%') # func to calculate profit percent
def lossPercent(loss , costP):
lossPerc = loss / costP * 100
return(str(lossPerc) + '%') # Func to calculate loss percent
print('Hello\n')
print('Press Enter To Exit')
while(True):
google = str(input('Profit or Loss : '))
if google.strip() == 'Profit': # condition for profit
sellPrice = float(input('Selling Price : ')) # getting selling price
costPrice = float(input('Cost Price : ')) # getting costprice
if sellPrice > costPrice: # if selling price is greater than cp
print('Profit : ' + str(profit(sellPrice , costPrice)))
print('Profit Percent : ' + str(profitPercent(profit(sellPrice , costPrice) , costPrice)))
continue
else: # else if sp is less than cp so it is loss
print('Cost Price is Greater Than Selling Price')
print('Try calculating loss\n')
continue
elif google.strip() == 'Loss':
costPrice = float(input('Cost Price : '))
sellPrice = float(input('Selling Price : '))
if costPrice > sellPrice:
print('Loss : ' + str(loss(costPrice , sellPrice)))
print('Loss Percent : ' + str(lossPercent(loss(costPrice , sellPrice) , costPrice)))
continue
else:
print('Selling Price is Greater Than Cost Price')
print('Try calculating profit\n')
continue
else:
quit()
================================================
FILE: pyKeywords.py
================================================
# Checking is some keyword is a python keyword or not
import keyword
pythonKeywords = keyword.kwlist
getToCheck = str(input('Keyword to check : '))
check = keyword.iskeyword(getToCheck)
if check == True:
print(getToCheck + ' is a python keyword.')
else:
print(getToCheck + ' is not a python keyword.')
print('\nShowing all keywords in python : \n')
print(pythonKeywords)
# remember to test the code
================================================
FILE: pythagoras.py
================================================
# Pythagoras Formula
import math
# a.sq + b.sq = c.sq
a = float(input('Value for A : '))
b = float(input('Value for B : '))
c = math.sqrt(a ** 2 + b ** 2)
# here's the answer
print(c)
================================================
FILE: python_files_compiler.py
================================================
from cx_Freeze import setup, Executable
# file must be saved in same directory as the file you want to Compile
# Download cx_Freeze from source forge or run easy_install in power shell
nameOfExec = input("Name for Executable: ")
versionNumber = input("Version: ")
auth = input("Name of Author: ")
auth_email = input("Email of Author: ")
descript = input("Description: ")
filename = input("File to Compile(Add .py to file): ")
# run this file in cmd "python CompileFiles.py build" or "python CompileFiles.py build_exe"
# This setup in minimialistic
setup(
name = nameOfExec,
version = versionNumber,
description = descript,
author = auth,
author_email = auth_email,
executables = [Executable(filename)]
)
================================================
FILE: randomModule.py
================================================
import random
inside = random.randint(1,37890) # choses a random integer between given range
print(inside)
outside = random.randrange(1,1000) # choses a random number number in given range
print(outside)
colors = ['green','black','blue','yellow','white']
print(random.choice(colors)) # choses random element from list
================================================
FILE: readFiles.py
================================================
# Reading files
# Enter file name which is in same directory as that of the program
fileName = str(input('File name : '))
fileToRead = open(fileName, 'r') # 'r' reads the file
print(fileToRead.read()) # reading file
fileToRead.close() # closing the file
================================================
FILE: reverse_sort.py
================================================
"""
This sort is designed by me.
First self designed sorting Algorithm.
Kalpak Take
"""
def reverse_sort(array):
for i in range(len(array) - 1):
for n in range(len(array) - 1):
a = array[n]
if (a < array[i]):
tem = array[i]
array[i] = a
array[n] = tem
return array
print reverse_sort([123, 3455, 6577, 546, 345, 22, 56, 7])
================================================
FILE: rock,paper,scissor.py
================================================
import random
while 2 == 2:
print('--------------------------------------------------------------')
get_again = raw_input('Enter rock paper or scissor : ')
make_use = random.choice(['rock','paper','scissor'])
print('--------------------------------------------------------------')
print(make_use)
print('--------------------------------------------------------------')
if get_again == 'rock' and make_use == 'paper':
print('computer wins! You "LOSE" ')
print('--------------------------------------------------------------')
continue
elif get_again == 'rock' and make_use == 'scissor':
print('computer loses You win!')
print('--------------------------------------------------------------')
break
elif get_again == 'rock' and make_use == 'rock':
print('It\'s a tie ! try again !')
print('--------------------------------------------------------------')
continue
elif get_again == 'paper' and make_use == 'paper':
print('It\'s a tie ! try again !')
print('--------------------------------------------------------------')
continue
elif get_again == 'scissor' and make_use == 'scissor':
print('It\'s a tie ! try again !')
print('--------------------------------------------------------------')
continue
elif get_again == 'paper' and make_use == 'scissor':
print('computer wins! You "LOSE" ')
print('--------------------------------------------------------------')
continue
elif get_again == 'scissor' and make_use == 'paper':
print('computer loses You win!')
print('--------------------------------------------------------------')
break
elif get_again == 'paper' and make_use == 'rock':
print('computer wins! You "LOSE" ')
print('--------------------------------------------------------------')
continue
elif get_again == 'scissor' and make_use == 'rock':
print('computer wins You "LOSE" ')
print('--------------------------------------------------------------')
continue
else :
print('Invalid input: Try again')
continue
================================================
FILE: selection_sort.py
================================================
#Selection Sort
def selection_sort(l):
# Scan slices l[0:len(l)], l[1:len(l)], …
for start in range(len(l)):
# Find minimum value in slice . . .
minpos = start
for i in range(start,len(l)):
if l[i] < l[minpos]:
minpos = i
# . . . and move it to start of slice
(l[start],l[minpos]) = (l[minpos],l[start])
return(l)
# Test
result = selection_sort([9,8,7,6,5,4,3,2,1])
print("Builtin Method Result: {}".format(sorted([9,8,7,6,5,4,3,2,1])))
print("Selection Sort Method Result: {}".format(result))
================================================
FILE: sendingEmailsInPython.py
================================================
import smtplib
# REMEMBER : dont send mails through public computers or servers
# connecting to googles serevrs
serverToLogin = smtplib.SMTP('smtp.gmail.com' , 587)
# Username
userName = str(input('Username for Gmail : '))
# password
password = str(input('Password Of Account : '))
# Logging in
serverToLogin.login(userName , password)
def sendMail():
yourEmail = str(input('Your Email Address : ')) # senders email address
toSendEmail = str(input('Receivers Email Address')) # receivers email address
messageHead = str(input('Message Head : ')) # Message head
messageBody = str(input('Message : ')) # main message
fullMessage = messageHead + '\n' + messageBody # full message
serverToLogin.sendmail(yourEmail , toSendEmail , fullMessage) # sending email address through server
while True:
toSendOrNot = str(input('Send or End : '))
if toSendOrNot == 'Send':
print('\n')
print(sendMail())
else :
quit()
================================================
FILE: server_file.py
================================================
import socket
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12345
server_socket.bind((host,port))
print("Server socket sucessfully Created on IP : {} at port {} ".format(host,port))
server_socket.listen()
print("Server is waiting for clients to connect .... \n\n")
client_socket,client_addr = server_socket.accept()
print("Client is connected")
print("Client's IP {}:{}\n\n".format(*client_addr))
f = open(input("Enter path to your file "),'rb')
name =f.name
client_socket.send(name.encode())
for line in f:
client_socket.send(line)
else :
client_socket.send("EOF".encode())
client_socket.close()
server_socket.close()
================================================
FILE: shell_games/README.md
================================================
'shell_games' Sub-directory contains all the games(programs)
written for terminal/shell/command line.
More games like sudoku, chess, battleship, et cetera are on their way!
The programs have been re-checked and re-mastered by me!
Although i've tried to keep it as orignal as possible.
Keep Patience It'll take time to go through every program!! Thanks
================================================
FILE: shell_games/battleship.py
================================================
# Add Encoding and path to exec
from random import randint
import sys
class BattleShip:
def __init__(self, rows_grid, columns_grid, co_ord_symbol):
# Initializes battleship board of n * m size
self.board = self.create_board(rows_grid, columns_grid, co_ord_symbol)
# Placing ship randomly on board x refers to
# array, y refers to index in array
self.ship_x = randint(0, rows_grid)
self.ship_y = randint(0, columns_grid)
def create_board(self, x_length, y_length, co_ord_symbol="o "):
# creates a multi-dimensional array of
# n * m length
return [[co_ord_symbol]*x_length for col in range(y_length)]
def view(self):
# For graphical representation of board
for row in self.board:
print(" ".join(row))
def is_ship_there(self, x_cord_guess, y_cord_guess):
# Check if ship exists at given co-ordinates
if self.ship_x == x_cord_guess and self.ship_y == y_cord_guess:
return True
return False
def no_place_for_old_guess(self, row, col):
# Replaces the co-ordinate at wrong guessed
# ship position for convinience with X
self.board[row][col] = "X "
def get(self, row, col):
# For UI purpose see ln 72
return self.board[row][col]
def battleshipUI():
# Maximum n turns for player to guess the position of ship
max_turns = 5
turns = 0
# Board of rows * columns for playing
rows = int(input("How many rows? "))
cols = int(input("How many columns? "))
lets_battle = BattleShip(rows, cols, "o ")
# Execute until user runs out of chances
while turns < max_turns:
# View the board at each new chance
print("\n\nOcean:")
lets_battle.view()
# User to guess position of ship
row_guess = int(input("\nGuess row? "))
col_guess = int(input("Guess column? "))
# Conditions if user guessed correctly,
# or missed it or guessed extremely wrong
# co-ordinates
if lets_battle.is_ship_there(row_guess, col_guess):
print("\n > Damn! You sunk my SHIP!")
print(" > You Won the Game!\n\nSee You Soon!")
sys.exit(0)
elif (row_guess >= rows or row_guess < 0 or col_guess >= cols or col_guess < 0):
print("\n - Ship isn't even in Ocean!")
else:
if lets_battle.get(row_guess, row_guess) == "X ":
print("\n - Really you tried that already!")
else:
print("\n - Wrong Guess! Use your sailor's instincts!")
# Replace symbol o with X to tell user
# He/She already tried those co-ordinates
lets_battle.no_place_for_old_guess(row_guess, col_guess)
turns += 1
print("\n~~~GAMEOVER~~~")
battleshipUI()
================================================
FILE: shell_games/battleship_info.txt
================================================
Battleship:
Computer places a ship on the board
User/Player has to guess the position os ship
Rows and columns are numbered from 0 to n-1
and not 1 to n
Structure of code can be understood by giving a careful look!
You'll notice the game is highly customizable!
Enjoy the game!
================================================
FILE: shell_games/dice_rolling_simulator.py
================================================
# Add encoding and path to executable
import sys
import time
import random
class DiceRollSim:
def __init__(self, no_of_players, no_of_dies):
self.players = self.assign_names(no_of_players)
self.die_n = no_of_dies
def assign_names(self, n):
# Assigns names to 'n' players playing
dict_players = {}
# All members are indentified by name
# and not number
for i in range(n):
dict_players[i + 1] = str(
input("Name for player({}): ".format(i + 1)))
return dict_players
def roll_die(self):
# Roll die n number of times
# In case playing with multiple dies
return [random.randint(1, 6) for roll in range(self.die_n)]
def play(self):
# Main
rounds = 0
while True:
# Continue playing until desired
if str(input("\n\n[+]Continue [Y/n]? ")).strip().lower() == "y":
print("\nRound-> %d" % rounds)
# Print rolled die upper face number/s
# for each player playing, along with sum for quick moves
for player_num in self.players.keys():
rolled = self.roll_die()
print(" > Chance of player %s: %s total: %d" %
(self.players[player_num], rolled, sum(rolled)))
# Delay for better user experience
time.sleep(5)
# Update rounds played
rounds += 1
continue
else:
# Finished playing
print("\n > Rounds played: %d" % rounds)
break
def main_interface():
# Indroductions
print(" " * 7 + "| Dice Rolling Simulator | \n\n")
# Initializations/Declarations
players_n = abs(int(input("> How many players? ")))
die_n = abs(int(input("> Number of dies? ")))
print("\n\n")
die_rolling_simulator = DiceRollSim(players_n, die_n)
print("\nNumber of players playing -> %d\nWith %d dies." % (players_n, die_n))
# And the game begins
die_rolling_simulator.play()
print("\n\nSee you at another game!")
sys.exit(0)
main_interface()
================================================
FILE: shell_games/dice_rolling_simulator_info.txt
================================================
DiceRollingSimulator:
Basically simulates rolling of die for 'n' players
Playing with given number of dies
Each player is identified by name
During each dice rolling session, session is called as round
After each round user can either continue playing another round
Or simply exit
Simulator is helpful in playing all board games played with dies
================================================
FILE: shell_games/number_guessing_game.py
================================================
#!/usr/bin/python3
from random import randint
MAX_ = 500 # Specify biggest possible value from random number generation
# Asks user for a guess and returns this when successful
def get_guess():
while True: # Run forever, until broken
try: # Try the following, if fails, run the except statment
user_input = int(input("Guess a number: ")) # Get user input and covert it to an int (number)
break # If the input can be converted, break the loop
except ValueError: # This runs if the input could not be converted - text was entered
print("Enter a number!\n") # Tell them to enter a number, then run loop again
return user_input # Return value when loop broken
num_to_guess = randint(0, MAX_) # Generates a random number between 0 and value of MAX_
print("Welcome to my random number guessing game!\nGuess a number between 0 and ", MAX_, "\n")
while True:
guess = get_guess()
if guess >= 0 and guess <= MAX_: # Check if guess between 0 and max
# Correct number!
if guess == num_to_guess:
print("That's a correct guess!\nYou got it!\n")
break
# Incorrect - give hint
elif guess < num_to_guess:
print("Try a bigger num!") # Number to small
else:
print("Try a smaller num!") # Number to big
# Number is not in range
else:
print("Enter a number in between 0 and ", MAX_)
print("")
'''
*Challenge*
1) Can you give the user the option to Play Again?
- if yes, the game will reset - including the random number
2) Try count the number of guesses and give a score to the user when they guess the number
- the lower the guesses, the higher the score
'''
================================================
FILE: simple_scripts/ListExample.py
================================================
my_list = ['p','y','t','h','o','n']
# Output: p
print(my_list[0])
# Output: t
print(my_list[2])
# Output: o
print(my_list[4])
# Error! Only integer can be used for indexing
# my_list[4.0]
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
================================================
FILE: simple_scripts/README.md
================================================
'simple_scripts' Sub-directory contains all simplest programs,
these programs are simple to read/write.
The programs have been re-checked and improved a bit
Although i've tried to keep it as orignal as possible. Thanks
================================================
FILE: simple_scripts/args_example.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# *args is used when we don't know the exact number of
# arguments are going that will be passed, so this placeholder
# is used commonly
def add_numbers(*args):
res = 0
for i in args:
res += i
return res
# Quick Test
t1 = add_numbers(123,435,876,12,54,76,78954,89,87,56,78,98,56,32,87)
if t1 == sum([123,435,876,12,54,76,78954,89,87,56,78,98,56,32,87]):
print("Sum: " + str(t1))
else:
print("Something went wrong!")
================================================
FILE: simple_scripts/args_example_1.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# *params is just a placeholder(try putting other name)
# for n number of arguments
# so that n can be any number, instead of params
# any name can be used, but the * asterisk is important
# Below function, is a generator
# generates a tuple containing arg, and a boolean value
# every time it encounters argument
def squared(*params):
for arg in params:
yield((arg, arg % 2 == 0))
# Quick Test
print("Divisibility Test(by 2): ")
for n, bool_ in squared(12, 13, 34, 4576, 234536, 2341):
if bool_:
print(" [" + str(n) + "] -> is divisible by 2!")
else:
print(" [" + str(n) + "] -> is NOT divisible by 2!")
================================================
FILE: simple_scripts/class_animal_attributes_examples.py
================================================
class Animal:
def __init__(self, species, name, legs, color, voices):
self.species = species
self.name = name
self.legs = legs
self.color = color
self.voices = voices
cat = Animal("Cat" , "Pussy-Cat" , 4 , "white" , "meow")
dog = Animal("Dog" , "Cloudy", 4 , "brownie" , "bark")
print("Species of animal : ",dog.species)
print("name of animal : ",dog.name)
print("no. of legs : ",dog.legs)
print("color of animal : ",dog.color)
print("voice of animal : ",dog.voices)
print(" ")
print("Species of animal : ",cat.species)
print("name of animal : ",cat.name)
print("no. of legs : ",cat.legs)
print("color of animal : ",cat.color)
print("voice of animal : ",cat.voices)
================================================
FILE: simple_scripts/class_example_movies.py
================================================
class movie():
def __init__(self, name, rating, director, budget, description):
self.name = name
self.rating = rating
self.director = director
self.budget = budget
self.description = description
def good_movie(self):
if self.rating >= 4:
return("It's a good movie.")
toy_story = movie("ToyStory2" , 4 , "John Lasseter , Lee Unkrich , Ash Brannon" , "90 millon USD" , """When Woody is toy-napped by a greedy toy collector and is nowhere to be found, Buzz and his friends set out to rescue him.But Woody too is tempted by the idea of becoming immortal in a museum.
""")
print("Title : " + str(toy_story.name))
print("Rating : " + str(toy_story.rating))
print("Director : " + str(toy_story.director))
print("Budget : " + str(toy_story.budget) + "\n")
print("Description : " + str(toy_story.description))
print(toy_story.good_movie())
================================================
FILE: simple_scripts/class_movies.py
================================================
class Movie:
def __init__(self, name, rating, director, budget, description):
self.name = name
self.rating = rating
self.director = director
self.budget = budget
self.description = description
def good_movie(self):
if self.rating >= 4:
return"Good Movie"
else:
return "Average Movie"
toy_story = Movie("ToyStory2" , 4 , "John Lasseter , Lee Unkrich , Ash Brannon" , "90 millon USD" , "When Woody is toy-napped by a greedy toy collector and is nowhere to be found, \nBuzz and his friends set out to rescue him.\nBut Woody too is tempted by the idea of becoming immortal in a museum.")
print("Title : " + toy_story.name)
print("Rating : " + str(toy_story.rating))
print("Director : " + toy_story.director)
print("Budget : " + str(toy_story.budget))
print("Description : " + toy_story.description)
print("Comment: " + toy_story.good_movie())
================================================
FILE: simple_scripts/conditionals_examples.py
================================================
# THIS SCRIPT IS TO UNDERSTAND
# THAN TO EXECUTE!
# Conditionals Examples
# if , elif , else
# Condition Testing operators
# == checks equality
# != not equal to
# > greater than
# < less than
# <= smaller than equal to
# >= greater than equal to
# Let's start with if
# Let's say we have a robot and we want it to move forward by 20 steps
robotMoving = True
if robotMoving == True:
print('Move 20 steps')
# Okay what about if robot is not moving
# This is where else : statement comes in
robotMoving = False
else :
print('You are not moving')
# elif
# What if there are multiple things to check like if
# We need more if statements but each if will run
# Thus we need elif(else if) statement
# Only else : statements dont contain values to check
start = str(input('Enter a or b or c : '))
# we need to check if entered value is equal to a or b or c
if start == 'a':
print('You entered ' + start)
elif start == 'b':
print('You entered ' + start)
elif start == 'c':
print('You entered ' + start)
else:
print('Invalid Input')
# Another Example
numsA = input('Enter a : ')
numsB = input('Enter b : ')
if numsA > numsB:
print(str(numsA) + ' is greater than ' + str(numsB))
elif numsA < numsB:
print(str(numsB) + ' is greater than ' + str(numsA))
else :
print('Numbers are equal')
# nested if else
# You can nest conditionals inside other conditionals
startProgram = True
numsA = input('Enter a : ')
numsB = input('Enter b : ')
if startProgram == True:
if numsA > numsB:
print(str(numsA) + ' is greater than ' + str(numsB))
elif numsA < numsB:
print(str(numsB) + ' is greater than ' + str(numsA))
else :
print('Numbers are equal')
else:
print('Can\'t access program')
# and or not are helpful
# and returns True if both conditions are true
# or returns True if one of both condition is true
# not returns True if condition is false and False if condition is True
# Think you have bike and you want to go out on a ride but you have to check if you have enough fuel
# remember not evaluates first then and then or
# and
youHaveBike = True
fuel = 30
if youHaveBike == True and fuel > 65:
print('You are good to go')
else:
print('You need to refill fuel')
# or
extraFuel = True
if extraFuel = True or fuel > 65:
print('You are good to go')
else:
print('You need to refill fuel')
# not
number = 12
if not(number != 11):
print('True')
else:
print('False')
================================================
FILE: simple_scripts/for_loop_fibonnaci
================================================
#printing fibonnaci series till nth element
def print_fibonacci(n):
current_no = 1
prev_no = 0
for i in range(n):
print(current_no, end = " ")
prev_no,current_no = current_no, current_no + prev_no
print_fibonacci(10)
================================================
FILE: simple_scripts/for_loop_mountain.py
================================================
# Accept User Input, consider (4)
n = int(raw_input("How big? "))
# Building block of our mountain of money
s = '$'
# Process for constructing mountain
# Since n = 4,
# range (1, n+1) would be all the integers from 1 to 4 including 1 and 4
# Mountain formed would be:
# $ i = 1, ' ' * n-i = 4-1 = 3 is empty space taken 3 times, s*i is '$' taken once(i times)
# $$ i = 2, ' ' * n-i = 4-2 = 2 , s*i is '$' taken twice(i times)
# $$$ and so on
# $$$$
# Again, notice how i and n change for each iteration
for i in range( 1 , n+1):
print (' ' *(n-i) + s*i)
print("\n")
# Other variant
s = '$$'
for i in range( 1 , n+1):
print (' ' *(n-i) + s*i)
================================================
FILE: simple_scripts/personality_teller.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Personality Teller
import random
# Chooses personality randomly
# Just for fun!
# Don't be serious!
personalities = ['Arrogant and Rude','Funny and Polite','Insane and Crazy'
,'Lover and Cute','Nerd and Boring','Cool and Rude','Cute but arrogant','Intelligent and Geek'
,'Cool and Funny','Idiot and Crazy','Awesome and Crazy','Good and Smart','Cool and Smart',
'Smart and Geek','Cool and Smart']
while True:
if raw_input("\nPress(e) to Exit,\nName?: ").strip() == "e":
print("\nHope you enjoyed!")
exit(0)
else:
print(" > You are %s" % random.choice(personalities))
================================================
FILE: simple_scripts/unicode.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# returns UNICODE value of a character
def get_ascii(S):
# even if string has only 1 character
# it yields same for all
if len(S) > 0:
for char_ in list(S):
yield((char_, ord(char_)))
# ord returns unicode value of given string of length 1
# we only increased it's capacity
# simple ..eh
# test
test_characters = ['A', 'x', 'Y', 'Z', 'm', 'K', "STack"]
for test_case in test_characters:
print("Test Case: " + test_case)
codes = list(get_ascii(test_case))
for code in codes:
print(" character: {}, unicode_val: {}".format(code[0], code[1]))
print(" ")
================================================
FILE: simple_scripts/website_opener.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Just Exploring webbrowser lib
from webbrowser import open as web_open
# Simple function to open given link in webbrowser
def open_website(link):
try:
print("Opening link: " + link)
web_open(link)
except Exception as e:
print("Error Occurred:\n {}".format(e))
# Just for test
get_link = raw_input("Link to open: ")
open_website(get_link)
================================================
FILE: sleepWellAlarm.py
================================================
# Alarm in Python
# Playing Sound on youtube to wake the person up
# I havent really battle tested the program so it might contain bugs
# If you come accross the bugs inform me
from time import sleep,ctime
import datetime
import webbrowser
import random
now = datetime.datetime.now()
linksToSounds = ['https://www.youtube.com/watch?v=6pR5cyH63mA','https://www.youtube.com/watch?v=e12KryuLcbs','https://www.youtube.com/watch?v=nbjwmC8K4K4','https://www.youtube.com/watch?v=UqSww10eeKw','https://www.youtube.com/watch?v=9f06QZCVUHg','https://www.youtube.com/watch?v=kffacxfA7G4'] # remember to add links and test the code
def alarm(h,m,s):
timeToSleep = h * 3600 + m * 60 + s
sleepingTime = sleep(timeToSleep)
playSound = webbrowser.open_new(random.choice(linksToSounds))
# Main code
print(ctime(),'\n')
startOrEnd = str(input('Set alarm or End : '))
if startOrEnd.strip() == 'Set alarm':
hours = int(input('Hours : '))
minutes = int(input('Minutes : '))
seconds = int(input('Seconds : '))
print('Alarm started at %s : %s'%(now.hour,now.minute))
print(alarm(hours,minutes,seconds))
wakedUp = False
while wakedUp == False:
get = str(input('Have you waked up : '))
if get == 'Yes':
print('Good')
wakedUp = True
else:
sleepMoreTime = sleep(300) # playing sound again in 5 minutes
playSoundAgain = webbrowser.open_new(random.choice(linksToSounds))
continue
else :
quit()
================================================
FILE: snake game/.idea/.gitignore
================================================
# Default ignored files
/shelf/
/workspace.xml
================================================
FILE: snake game/.idea/inspectionProfiles/profiles_settings.xml
================================================
================================================
FILE: snake game/.idea/misc.xml
================================================
================================================
FILE: snake game/.idea/modules.xml
================================================
================================================
FILE: snake game/.idea/snake game.iml
================================================
================================================
FILE: snake game/index.html
================================================
Live streaming
================================================
FILE: snake game/main.py
================================================
import math
import random
import cvzone
import cv2
import numpy as np
from cvzone.HandTrackingModule import HandDetector
from flask import Flask,render_template,Response
app=Flask(__name__)
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
detector = HandDetector(detectionCon=0.8, maxHands=1)
class SnakeGameClass:
def __init__(self, pathFood):
self.points = [] # all points of the snake
self.lengths = [] # distance between each point
self.currentLength = 0 # total length of the snake
self.allowedLength = 150 # total allowed Length
self.previousHead = 0, 0 # previous head point
self.imgFood = cv2.imread(pathFood, cv2.IMREAD_UNCHANGED)
self.hFood, self.wFood, _ = self.imgFood.shape
self.foodPoint = 0, 0
self.randomFoodLocation()
self.score = 0
self.gameOver = False
def randomFoodLocation(self):
self.foodPoint = random.randint(100, 1000), random.randint(100, 600)
def update(self, imgMain, currentHead):
if self.gameOver:
cvzone.putTextRect(imgMain, "Game Over", [300, 400],
scale=7, thickness=5, offset=20)
cvzone.putTextRect(imgMain, f'Your Score: {self.score}', [300, 550],
scale=7, thickness=5, offset=20)
else:
px, py = self.previousHead
cx, cy = currentHead
self.points.append([cx, cy])
distance = math.hypot(cx - px, cy - py)
self.lengths.append(distance)
self.currentLength += distance
self.previousHead = cx, cy
# Length Reduction
if self.currentLength > self.allowedLength:
for i, length in enumerate(self.lengths):
self.currentLength -= length
self.lengths.pop(i)
self.points.pop(i)
if self.currentLength < self.allowedLength:
break
# Check if snake ate the Food
rx, ry = self.foodPoint
if rx - self.wFood // 2 < cx < rx + self.wFood // 2 and \
ry - self.hFood // 2 < cy < ry + self.hFood // 2:
self.randomFoodLocation()
self.allowedLength += 50
self.score += 1
print(self.score)
# Draw Snake
if self.points:
for i, point in enumerate(self.points):
if i != 0:
cv2.line(imgMain, tuple(self.points[i - 1]), tuple(self.points[i]), (0, 0, 255), 20)
cv2.circle(imgMain, tuple(self.points[-1]), 20, (0, 255, 0), cv2.FILLED)
# Draw Food
imgMain = cvzone.overlayPNG(imgMain, self.imgFood,
(rx - self.wFood // 2, ry - self.hFood // 2))
cvzone.putTextRect(imgMain, f'Score: {self.score}', [50, 80],
scale=3, thickness=3, offset=10)
# Check for Collision
pts = np.array(self.points[:-2], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(imgMain, [pts], False, (0, 255, 0), 3)
minDist = cv2.pointPolygonTest(pts, (cx, cy), True)
if -1 <= minDist <= 1:
print("Hit")
self.gameOver = True
self.points = [] # all points of the snake
self.lengths = [] # distance between each point
self.currentLength = 0 # total length of the snake
self.allowedLength = 150 # total allowed Length
self.previousHead = 0, 0 # previous head point
self.randomFoodLocation()
return imgMain
game = SnakeGameClass("donut.png")
def game1():
while True:
success, img = cap.read()
img = cv2.flip(img, 1)
hands, img = detector.findHands(img, flipType=False)
if hands:
lmList = hands[0]['lmList']
pointIndex = lmList[8][0:2]
img = game.update(img, pointIndex)
cv2.imshow("Image", img)
key = cv2.waitKey(1)
if key == ord('r'):
game.gameOver = False
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + img+ b'\r\n')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/video')
def video():
return Response(game1())
if __name__=='__main__':
app.run()
================================================
FILE: snake_game.py
================================================
# Contribution by https://github.com/Karan9034
import pygame
import sys
import random
class Snake(object):
def __init__(self):
self.length=1
self.positions=[((SCREEN_WIDTH/2),(SCREEN_HEIGHT/2))]
self.direction=random.choice([UP,DOWN,LEFT,RIGHT])
self.color=(17,24,47)
def get_head_position(self):
return self.positions[0]
def turn(self,point):
if self.length>1 and (point[0] * -1, point[1] * -1) == self.direction:
return
else:
self.direction=point
def move(self):
cur=self.get_head_position()
x,y=self.direction
new=((cur[0] + (x*GRIDSIZE))%SCREEN_WIDTH,(cur[1]+(y*GRIDSIZE))%SCREEN_HEIGHT)
if len(self.positions)>2 and new in self.positions[2:]:
pygame.quit()
sys.exit()
else:
self.positions.insert(0,new)
if len(self.positions)>self.length:
self.positions.pop()
def draw(self,surface):
for p in self.positions:
r=pygame.Rect((p[0],p[1]),(GRIDSIZE,GRIDSIZE))
pygame.draw.rect(surface,self.color,r)
pygame.draw.rect(surface,(93,216,228),r,1)
def handle_keys(self):
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type==pygame.KEYDOWN:
if event.key==pygame.K_UP:
self.turn(UP)
elif event.key==pygame.K_DOWN:
self.turn(DOWN)
elif event.key==pygame.K_LEFT:
self.turn(LEFT)
elif event.key==pygame.K_RIGHT:
self.turn(RIGHT)
elif event.key==pygame.K_ESCAPE:
pygame.quit()
sys.exit()
class Food(object):
def __init__(self):
self.position=(0,0)
self.color=(233,163,49)
self.randomize_position()
def randomize_position(self):
self.position=(random.randint(0,GRID_WIDTH-1)*GRIDSIZE,random.randint(0,GRID_HEIGHT-1)*GRIDSIZE)
def draw(self,surface):
r=pygame.Rect((self.position[0],self.position[1]),(GRIDSIZE,GRIDSIZE))
pygame.draw.rect(surface,self.color,r)
pygame.draw.rect(surface,(93,216,228),r,1)
def drawGrid(surface):
for y in range(0,int(GRID_HEIGHT)):
for x in range(0,int(GRID_WIDTH)):
if (x+y)%2==0:
r=pygame.Rect((x*GRIDSIZE,y*GRIDSIZE),(GRIDSIZE,GRIDSIZE))
pygame.draw.rect(surface,(200,200,200),r)
else:
rr=pygame.Rect((x*GRIDSIZE,y*GRIDSIZE),(GRIDSIZE,GRIDSIZE))
pygame.draw.rect(surface,(100,100,100),rr)
SCREEN_WIDTH=480
SCREEN_HEIGHT=480
GRIDSIZE=20
GRID_WIDTH=SCREEN_WIDTH/GRIDSIZE
GRID_HEIGHT=SCREEN_HEIGHT/GRIDSIZE
UP=(0,-1)
DOWN=(0,1)
LEFT=(-1,0)
RIGHT=(1,0)
def main():
pygame.init()
clock=pygame.time.Clock()
screen=pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT),0,32)
pygame.display.set_caption("Snake")
surface=pygame.Surface(screen.get_size())
surface=surface.convert()
drawGrid(surface)
snake=Snake()
food= Food()
myfont=pygame.font.SysFont("monospace",16)
score=0
while True:
clock.tick(10)
snake.handle_keys()
drawGrid(surface)
snake.move()
if snake.get_head_position()==food.position:
snake.length+=1
score+=1
food.randomize_position()
snake.draw(surface)
food.draw(surface)
screen.blit(surface,(0,0))
text=myfont.render("Score: {0}".format(score),1,(0,0,0))
screen.blit(text,(5,10))
pygame.display.update()
if __name__=="__main__":
main()
================================================
FILE: sortString.py
================================================
# function to sort strings
def sortString():
strr = str(input('Enter : '))
words = strr.split()
words.sort()
print(' ')
for word in words:
print(word)
# main code
print('Hello,')
while True:
startOrEnd = str(input('Start or End : '))
if startOrEnd == 'Start':
print(' ')
print(sortString())
continue
elif startOrEnd == 'End' :
print(' ')
quit() # closes interpreter
else :
print('Oops Try Again')
continue
================================================
FILE: sortingFunctions.py
================================================
# functions to sort out data
# they act on lists
# you can apply these functions in your programs
# this function takes first and second element from list and compare them
def bubbleSort(g): # g argument is for list
for x in range(len(g) - 2):
a = g[x]
b = g[x + 1 + 1]
if a > b :
return(a)
else :
return(b)
# use this to convert output into list
# result = list(map(bubbleSort , g)) replace g with parameter
# this function checks even num
def oddSort(odd):# odd can be list or variable
for x in odd:
if x % 3 == 0:
return(x)
# use this to get list as output
# result = list(filter(oddSort , odd)) replace odd with parameter
# this function checks even num
def evenSort(eve):# eve can be list or variable
for a in eve:
if a % 2 == 0:
return(a)
# use this to get list as output
# result = list(filter(evenSort , eve)) replace eve with parameter
# this function checks divisibility
def divisibleSort(divi , get):# here divi is list and get is an variable set to integer or float
for r in divi:
if r % get == 0:
return(r)
# use this to get output
# result = list(filter(divisibleSort , divi , get)) replace arguments with suitable parameters
# this function checks if addition of group of two elements has desired answer
def addBubbleSort(f,user):# here f is list and user is integer or float
for x in range(len(f) - 2):
a = f[x]
b = f[x + 1 + 1]
if a + b == user:
return(a,b)
# i havent checked this function check for bugs
# this is how it works
# res = list(filter(addBubbleSort , f , user)) replace arguments with suitable parameters
# this function checks if subtraction of group of two elements has desired answer
def subBubbleSort(z,userSub):
for x in range(len(z) - 2):
a = z[x]
b = z[x + 1 + 1]
if a - b == useSubr:
return(a,b)
# i havent checked this function check for bugs
#res = list(filter(subBubbleSort , z , userSub)) replace arguments with suitable parameters
================================================
FILE: squareTurtle.py
================================================
import turtle
def square():
win = turtle.Screen()
win.bgcolor("white")
jack = turtle.Turtle()
for x in range(1,5):
jack.forward(100)
jack.right(90)
win.exitonclick()
square()
================================================
FILE: square_root_algorithm.py
================================================
""" Function uses prime factorisation method
to find square root of number """
def prime_factors(c):
pos = 2
factors = []
while (pos <= c):
if (c % pos == 0):
c = c // pos
factors.append(pos)
continue
else:
pos = pos + 1
return factors
def extract_common(li):
final = []
if (len(li) % 2 != 0):
return "Number is not perfect root."
else:
pre = len(li) - 1
for n in range(0, pre, 2):
a = li[n]
b = li[n + 1]
if (a == b):
final.append(b)
else:
return "Number is not perfect root."
return final
def square_root(take_in):
res = 1
for c in take_in:
res *= c
return res
get_num = int(raw_input("\nNumber : "))
print square_root(extract_common(prime_factors(get_num))), " "
================================================
FILE: squarecube.py
================================================
# pre code
def square():
print(" ")
makeUse = raw_input("Square or Cube : ")
if makeUse.strip() == "Square":
print(" ")
user = int(raw_input("Enter number to get square : "))
square = user ** 2
print(" ")
print("Square of the number " + str(user) + " is " + str(square))
elif makeUse.strip() == "Cube":
print(" ")
userAgain = int(raw_input("Enter number to get square : "))
cube = userAgain ** 3
print(" ")
print("Cube of the number " + str(userAgain) + " is " + str(cube))
# main code
while True:
print("Hello,")
print(" ")
startOrEnd = raw_input("Start or End : ")
print(" ")
if startOrEnd.strip() == "Start":
print(square())
elif startOrEnd.strip() == "End":
print(" ")
print(" ")
print("Program Ended......")
break
else :
print(" ")
print("Try Again")
continue
startagain = ("Start again or End : ")
print(" ")
if startagain.strip() == "Start again":
print(" ")
print("Starting again.....")
continue
elif startagain == "End":
print(" ")
print(" ")
break
else :
print(" ")
print("Try Again")
continue
================================================
FILE: star_turtle.py
================================================
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import turtle
>>> star=turtle.Turtle()
>>> win=turtle.Screen()
>>> win.setworldcoordinates(-100,-100,100,100)
>>> for i in range(5):
star.forward(50)
star.right(144)
>>>
================================================
FILE: stringIndexing.py
================================================
# string indexing
'''
Indexing
0 1 2 3 4
H E L L O
'''
message = 'Hello'
print(message[0]) # this will print H that is first letter in the string
print(message[1:4]) # this will print from index one to index four
print(message[:3]) # this will print from starting to index 3
print(message[2:]) # this will print from index 2 till end
print(message[:]) # this prints whole string
print(message[0:4:2]) # this escapes 2 characters from string
# negative Indexing
'''
negative Indexing
P y t h o n
-6 -5 -4 -3 -2 -1
'''
awesome = 'Python is awesome'
print(awesome[:-1]) # -1 prints last character
print(awesome[-2]) # this prints m from starting
print(awesome[-7:]) # try this one out in interpreter
print('You are ' + awesome[10:] + ' you are learning ' + awesome[:6])
================================================
FILE: stringOperations.py
================================================
# This example shows you string operations
name = 'Kalpak'
print('My name is ' + name) # I have given space after is notice
age = 14
print('My age is ', age) # comma seprates two different things you want to print
print('This isn\'t going away too soon.') # that \ is called as an escape character
# the \ is used to use same quote in a string
print('I love newlines \n') # \n prints new line after string or according to its position
print('\t I love tabs') # \t adds a tab according to its position
multiple = 'Iron Man'
print(multiple * 5) # this will print string 5 times
# string methods in built
country = 'Norway'
print(country.upper()) # prints all letters in upper case
print(country.lower()) # prints all letters in lower case
print(country.title()) # converts into title
# string formatting
print('%s %s %s'%('I' , 'am' , 'cool'))
expression = 'I love'
movie = 'Captain America 3'
print('%s %s'%(expression , movie))
# type conversion
addition = 12343 + 3349
print('The answer is ' + str(addition)) # str() method converts non-string into string
================================================
FILE: stringReverse.py
================================================
# String Reverse
# This program is funny
getString = str(input('Word to Reverse : '))
reverseString = getString[::-1] # [::-1] tells to step from end without difference
print(reverseString)
================================================
FILE: sumAverage.py
================================================
# average of sum of lists
m = [1,43,656,8,54,,908,4,5,23,78,,435,89,45,476,89]
n = [234,56,90,,675,56,786,90,564,8,657,87,64,354,2,75]
q = [34,76,76,564,34,32,16,67,25,98,90,345,235,64,134,76]
def avgSums():
summingUp = sum(m) + sum(n) + sum(q)
summed = summingUp / 3
return(summed)
print(avgSums)
================================================
FILE: sum_array.py
================================================
def sum_arr(n):
res = 0
for x in n:
res += x
return res
nums = [52345,746587,98589,54398,9348,45887,49856]
test = sum_arr(nums)
#sum() is Pythons built in method of adding all the elements in a list
if test == sum(nums):
print("Sum of arr: {}".format(test))
else:
print("Func dosen't work!")
# Most simple algorithm ever! Isn't it!
================================================
FILE: sum_of_arithmetic_sequence.py
================================================
class ArithmeticSequence():
def __init__ (self, seq):
self.seq = seq
def sum(self):
summed = len(self.seq) / 2 * (self.seq[0] + self.seq[-1])
return summed
test_sub = [2,4,6,8,10,12,14,16]
print(ArithmeticSequence(test_sub).sum())
print(sum(test_sub))
================================================
FILE: swap_case.py
================================================
def swap_case(s):
swapped = ""
for i in range(len(s)):
temp = s[i].upper()
if (s[i] == temp):
swapped += s[i].lower()
else:
swapped += s[i].upper()
return swapped
================================================
FILE: systemInfo.py
================================================
import platform
import os
import sys
print('============================')
print('System Information : ')
print(os.name)
print(platform.system())
print(platform.release(),'\n')
print('============================')
print('Python Version Installed : ')
print(sys.version,'\n')
print('============================')
================================================
FILE: table_maker.py
================================================
# Tables maker
num = int(input("Number to make table : "))
li_a = [num for num in range(0 , num * 11 , num)]
for digit in li_a:
print(digit)
================================================
FILE: take-a-break.py
================================================
import webbrowser
import time
make_use = 1
while make_use < 3 :
time.sleep(10)
webbrowser.open("https://www.youtube.com/results?search_query=comedy+pranks")
make_use = make_use + 1
================================================
FILE: testofdivisibility.py
================================================
# pre code
def testDivisibility():
print(" ")
toTest = int(raw_input("Enter number of which you want to test Divisibility : "))
print(" ")
test = int(raw_input("Enter number by which you want to test : "))
if toTest % test == 0 :
print("-------------Answer---------------- ")
print(str(toTest) + " is divisible by " + str(test))
else :
print(str(toTest) + " is not divisible " + str(test))
print(" ")
print("--------------------Start-------------------")
user = raw_input("Start or End : ")
if user.strip() == "Start" :
print(testDivisibility())
print(" ")
# MAIN code
while True:
get = raw_input("Start again or End : ")
if get.strip() == "Start again":
print("---------------Start Again----------------")
print(" ")
continue
elif get.strip() == "End" :
print(" ")
print("------------------Program Ended--------------")
print(" ")
break
else :
break
elif user.strip() == "End" :
print(" ")
print("------------Program Ended-----------")
print(" ")
break
else :
print(" ")
print("Invalid Input. Try again")
continue
================================================
FILE: time_conversion.py
================================================
def twelve_to_twenty_four():
time = input().strip()
if (time[-2:] == 'PM'):
if (time[:2] == "12"): return(time[:-2])
else: return(str(12 + int(time[:2])) + time[2:-2])
else:
if (time[:2] == "12"): print("00" + time[2:-2])
else: return(time[:-2])
# Input Format : 12:00:00AM / 03:12:00PM
print(twelve_to_twenty_four())
================================================
FILE: tuplesExample.py
================================================
# Creating tuples
# Tuples are used to store 2-d grids and fixed values
# tuples are immutable that means they cant be changed
tupA = () # Empty tuple
print(tupA)
c = 12,56,78
tupC = tuple(c) # tuple() is built-in
print(tupC)
x,y,z = (12,45,42)
a = x,y,z
print(a)
print(type(a))
# Accessing items in tuples
print(tupC[0])
print(a[1])
print(tupC[2],'\n')
# tuples cant be reassigned
# tupC[1] = 18 # uncomment this line to see the error this should cause a error 'TypeError'
# iterating through tuples
for x in tupC:
print(x)
================================================
FILE: turtleRandomWeb.py
================================================
import random
import turtle
t = turtle.Pen()
for i in range(150):
t.color(random.choice(['green','red','violet']))
t.width(5)
t.forward(i)
t.right(30)
================================================
FILE: useful_scripts/Diffe_Hellman.py
================================================
import random, hashlib
def list_prime():
for num in range(3, 1000):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num, end=', ')
def is_prime(n):
"""if num > 1:
for i in range(2, num//2):
if (num % i) == 0:
return False
break
else:
return True
else:
return False"""
# Corner cases
if (n <= 1) :
return False
if (n <= 3) :
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def cost(h, cost):
for i in range(cost):
h = hashlib.sha3_512(h.encode()).hexdigest()
return h
print("type 'prime' to choose from list")
prime = input("Enter a largest prime number you can think of >>> ")
if prime == 'prime':
list_prime()
prime = int(input("Enter a largest prime number you can think of >>> "))
else:
prime = int(prime)
if is_prime(prime):
private = int(input("Enter your private key>>> "))
public = random.randint(0, 999999999)
my_share = (public**private)%prime
my_exchange_key = cost(hashlib.sha3_512(str(my_share).encode()).hexdigest(), 5)
print()
print(f"Your exchange key is --> {my_exchange_key}")
print('*' * 100)
bob_private = int(input("Enter Bob's private key>>> "))
bob_share = (public**private)%prime
bob_exchange_key = cost(hashlib.sha3_512(str(bob_share).encode()).hexdigest(), 5)
print()
print(f"Bob'sexchange key is --> {bob_exchange_key}")
print()
print(f"my_exchange_key == bob_exchange_key\n{my_exchange_key == bob_exchange_key}")
print('*' * 100)
else:
print("This is not a prime number")
================================================
FILE: useful_scripts/binary_to_decimal_conversion.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# Binary to decimal conversion
# See explaination: https://i.imgur.com/heAT0PB.gif ,
# https://www.electronics-tutorials.ws/binary/bin_2.html
def binary_to_decimal_conv(binary_string):
res = 0
binary_l = list(binary_string)
for bit_i in range(len(binary_l)):
res += int(binary_l[bit_i]) * (2 ** bit_i)
return res
# Test
# Testing interface
i = 0
while True:
if raw_input("\n[{}] Exit(press e) or Continue(press c): ".format(i)).strip().lower() == "c":
print("Decimal form: " + str(binary_to_decimal_conv(raw_input("\nBinary?: "))))
else:
print("\nHope you enjoyed!")
sys.exit()
i += 1
================================================
FILE: useful_scripts/bmi_body_mass_index_calculator.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# BMI calculator
# f(w, h) = w / h ** 2
# w refers to weight, h refers to height
# weight is in kilograms(kg's), height in meters(m) standard metrics
body_mass_index = lambda w, h: round((w) / ((h * 0.01) ** 2), 1)
# Test
# Playing/Testing Interface
i = 0
while True:
if raw_input("\n[{}] Exit(press e) or To count BMI(press c):".format(i)).strip().lower() == "c":
cal = body_mass_index(float(raw_input('\nWeight(in kgs)?: ')), float(raw_input('Height (in cm)?: ')))
print("\nHealthy BMI ranges between 19 to 25:")
print("Status: ")
if cal >= 19 and cal <= 25:
print("Your BMI: " + str(cal) + "\n You are HEALTHY")
elif cal < 19:
print("Your BMI: " + str(cal) + "\n Your BodyMassIndex is Underweight\n Not between Healthy range")
else:
print("Your BMI: " + str(cal) + "\n Your BodyMassIndex is Overweight\n Not between Healthy range")
i += 1
else :
sys.exit()
================================================
FILE: useful_scripts/caesars_cipher_encryption.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import string, sys
# Caesar's cipher is type of shift cipher,
# an encryption technique
# First used by roman rular Julius Caesar
# To see how it works refer:
# web-page/article: https://en.wikipedia.org/wiki/Caesar_cipher OR
# https://www.khanacademy.org/computing/computer-science/cryptography/crypt/v/caesar-cipher
def caesars_cipher_encoding(s, k, lowercase = True, uppercase = False):
# To encrypt plain text in either
# uppercase letters or lowercase letters
if lowercase:
alphas = list(string.lowercase)
elif uppercase:
alphas = list(string.uppercase)
encrypted = ""
# List characters in orignal string
char_s = list(s)
# Shifting of each single
# character in orignal string
# using given key
for char in char_s:
# avoid encryption of spaces
if char == " ":
encrypted += " "
else:
# n_index or new index is
# the index of encrypted character
n_index = k + alphas.index(char)
# if encrypted character is greater than
# length of english alphabets
if n_index > 25:
# Read explaination on line 59
while not n_index <= 25:
n_index = n_index - 26
encrypted += alphas[n_index]
# simple shift
else:
encrypted += alphas[n_index]
return encrypted
# Explaination of key bigger than 26:
# say we have key 54,
# we add index of char(say 'a') to key, i.e. key = 54 + 1 = 55
# so after first iteration over array of length(26),
# i.e. 55(total iterations to perform) - 26(iterations completed) = 29(iterations left)
# but, 29 is still a big index i.e. 29 > length of array(26)
# so we continue to subtract more 26(iterations),
# i.e. 29(iterations to perform) - (26 iterations done) = 3(remaining)
# so 3 is smaller than length of array and can be used as key,
# i.e. 3 < 26(length of array)
# thus, we reached at index of 3 after 54 iterations over an array of length 26
# bit complicated but read it twice, you'll master it!
# Test, Playing UI
i = 0
while True:
if raw_input("[{}] Exit(press e), To continue(press c): ".format(i)).lower() == "c":
# Number of times
i += 1
# Input for String and key for char shift
S, K = raw_input("\nString: "), int(raw_input("Key: "))
# Results
print("\nOrignal string: " + S + " , Key: " + str(K))
print("Encrypted text: " + caesars_cipher_encoding(S, K, True, False) + "\n")
else:
sys.exit()
================================================
FILE: useful_scripts/calculator.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# Functions to apply basic arithmetic
# operations on 2 numbers
# Each func, takes 2 numbers as input
add = lambda a, b: a + b
subtract = lambda a, b: a - b
multiply = lambda a, b: a * b
divide = lambda a, b: a / b
modulus = lambda a, b: a % b
# CLI
# Testing/Playing Interface
i = 0
while True:
if raw_input("\n\n[{}] Exit(press e) or Calculate(press c): ".format(i)) == "c":
op = raw_input("\nAdd(press a), Subtract(press s), Multiply(press m),\nDivide(press d), Modulus(press mo): ").strip().lower()
if op == "a":
print(" Sum: " + str(add(float(raw_input("\nN1: ")), float(raw_input("N2: ")))))
elif op == "s":
print(" Subtracted: " + str(subtract(float(raw_input("\nN1: ")), float(raw_input("N2: ")))))
elif op == "m":
print(" Multiplied: " + str(multiply(float(raw_input("\nN1: ")), float(raw_input("N2: ")))))
elif op == "d":
print(" Divided: " + str(divide(float(raw_input("\nN1: ")), float(raw_input("N2: ")))))
else:
print(" Modulus: " + str(modulus(float(raw_input("\nN1: ")), float(raw_input("N2: ")))))
i += 1
else:
print("\nHope you enjoyed!")
sys.exit()
================================================
FILE: useful_scripts/calendar.py
================================================
# calender viewer
import sys
import calendar
# function to view calendar
viewCalender = lambda yy, mm: print("\n\n Calendar > \n %s\n" % calendar.month(yy, mm))
# UI
while True:
if str(input("[+] Start [Y/n] ? ")).strip().lower() == "y":
try:
viewCalender(int(input("\nYear: ")), int(input("Month: ")))
except IndexError:
print(" -> Try Again! With valid numbers!\n")
else:
print("\nSee Ya Soon!")
sys.exit(0)
================================================
FILE: useful_scripts/password_generator.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Now-a-days, hashes of our passwords are
# flowing on internet, but to avoid password
# getting discovered by whoever got their hands
# on them, a password should contain:
# 1. Least 8 characters
# 2. No words, instead randomly chosen characters
# 3. Characters i'm refering to are, numbers,
# uppercase/lowercase letters, punctuation's
# This will protect password against, dictionary/brute force attacks
import random, string, sys
# List of characters, alphabets, numbers
# to choose from
data_set = list(string.ascii_letters) + list(string.digits) + list(string.punctuation)
# generates a random password
# very strong due to random ness
# primary protection against dictionary attack on hash tables
def generate_random_password(n):
# For password to be strong it should
# be at least 8 characters long
if n < 8:
return "Invalid Input,\nPassword should be at least 8 characters long!"
# Chooses a random character from data_set
# after password of given length is created
# returns it to user
password = ""
for x in range(n):
password += random.choice(data_set)
return password
# Test
while True:
usr = raw_input("Exit(press e), or Length: ").lower()
if usr == "e":
sys.exit()
print("Generated password: " + generate_random_password(int(usr)) + "\n")
================================================
FILE: useful_scripts/pinger.py
================================================
import subprocess
from datetime import datetime
import matplotlib.pyplot as plt
pings = []
losses = []
times = []
i = 0
def update_line():
plt.plot(times, pings)
plt.xticks(rotation=45)
plt.draw()
try:
plt.show()
while True:
output = subprocess.check_output("ping 8.8.8.8", shell=True)
losses.append(output.decode().split()[-18])
output = output.decode().split()[-1]
time = datetime.now().strftime("%H:%M:%S")
pings.append(int(output.strip("ms")))
times.append(time)
i += 1
# update_line()
except KeyboardInterrupt:
pings = [int(i) for i in pings]
losses = [int(i) for i in losses]
plt.figure()
plt.subplot(211)
plt.xticks(rotation=45)
plt.ylabel("ping (MS) - avg")
plt.plot(times, pings)
if sum(losses) != 0:
plt.subplot(212)
plt.plot(times, losses)
plt.xticks(rotation=45)
plt.ylabel("Loss")
plt.show()
================================================
FILE: useful_scripts/timer.py
================================================
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import time
import webbrowser
def timer(s, hrs, mins, secs):
# Convert time into seconds
_n = secs + mins*60 + hrs*60*60
print("\nTimer Started...")
print("> Countdown for: %i hours:%i minutes:%i seconds" %(hrs, mins, secs))
# This is where real timer works
# -0.01 is assumed time for execution of above instructions
time.sleep(_n - 0.01)
print("Time's up!")
print("...\...Playing Sound.../...")
# Play sound after timer count completion
webbrowser.open(s)
while True:
if raw_input("\nContinue[Y/n]? ").strip().lower() == "y":
timer(raw_input("\nSound(Link)?: ").strip(), int(raw_input("Hours?: ").strip()), int(raw_input("Minutes?: ").strip()), int(raw_input("Seconds?: ").strip()))
else:
print("\nHope You Enjoyed!")
sys.exit(0)
================================================
FILE: videodownloader.py
================================================
#program ended
================================================
FILE: writingFiles.py
================================================
# Writing files
# Enter file name which is in same directory as that of the program
fileName = str(input('File name : '))
fileToWrite = open(fileName, 'w') # 'w' writes to the file
textToWrite = str(input('Text to write : '))
fileToWrite.write(textToWrite) # writing file
fileToWrite.close() # closing the file