From 88658bec901a3112601fd7562fd9bf2ded3fd336 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 18 Jan 2018 21:30:27 +0530 Subject: [PATCH 001/151] Create LICENSE --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + 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 +. From fd06736625b6ffc163831907e822676d865cddd3 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 18 Jan 2018 21:30:55 +0530 Subject: [PATCH 002/151] Delete LICENSE --- LICENSE | 674 -------------------------------------------------------- 1 file changed, 674 deletions(-) delete mode 100644 LICENSE diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 94a9ed0..0000000 --- a/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - 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 -. From 2de8ddf8c5383fd67f9989cf38d977bc89eecf48 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 10:39:08 +0530 Subject: [PATCH 003/151] Update and rename ASCII.py to Very_Simple/unicode.py --- ASCII.py | 12 ------------ Very_Simple/unicode.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 12 deletions(-) delete mode 100644 ASCII.py create mode 100644 Very_Simple/unicode.py diff --git a/ASCII.py b/ASCII.py deleted file mode 100644 index efba98f..0000000 --- a/ASCII.py +++ /dev/null @@ -1,12 +0,0 @@ -# ASCII value of a character -def get_ascii(S): - if len(S) == 1: - return 'ASCII value of {} is {} '.format(S, ord(S)) - else: - return 'Entered value is a string and not a character' -# test -character = 'Z' -character1 = 'z' -print(get_ascii(character)) -print(get_ascii(character1)) -print(get_ascii("STack")) diff --git a/Very_Simple/unicode.py b/Very_Simple/unicode.py new file mode 100644 index 0000000..3716b30 --- /dev/null +++ b/Very_Simple/unicode.py @@ -0,0 +1,28 @@ + +#!/usr/bin/python +# -*- coding: -*- + + +# 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(" ") From 3e412ca5efe0e127c1408a280ad271687f933276 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 10:41:49 +0530 Subject: [PATCH 004/151] Update unicode.py --- Very_Simple/unicode.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Very_Simple/unicode.py b/Very_Simple/unicode.py index 3716b30..2b45566 100644 --- a/Very_Simple/unicode.py +++ b/Very_Simple/unicode.py @@ -1,4 +1,3 @@ - #!/usr/bin/python # -*- coding: -*- From d7b479fedd5e3c759f276e52f401cc899bc17f0f Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 11:24:37 +0530 Subject: [PATCH 005/151] Update and rename Eulers PYTHON.py to eulers_python.py functions based of Euler's formula that shows relations between faces, edges and vertices of a 3-dimensional figure --- Eulers PYTHON.py | 39 --------------------------------------- eulers_python.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 39 deletions(-) delete mode 100644 Eulers PYTHON.py create mode 100644 eulers_python.py diff --git a/Eulers PYTHON.py b/Eulers PYTHON.py deleted file mode 100644 index 15d0f71..0000000 --- a/Eulers PYTHON.py +++ /dev/null @@ -1,39 +0,0 @@ -while("Euler" != "Pythagoras"): - print("--------------------------------------------------") - print("CASE 1: F + V = E+2") - print("CASE 2: V = E+2 - F") - print("CASE 3: F = E+2 - V") - print("--------------------------------------------------") - get_again_again = raw_input("Enter CASES for calculation:") - if get_again_again == "CASE 1": - get = int(input("Enter faces of the Figure:")) - print("--------------------------------------------------") - get_again = int(input("Enter Vertices of the figure:")) - print("--------------------------------------------------") - print("Edges are ",(get + get_again)-2) - print("--------------------------------------------------") - elif get_again_again == "CASE 2": - get = int(input("Enter Edges of the Figure:")) - print("--------------------------------------------------") - get_again = int(input("Enter Faces of the figure:")) - print("--------------------------------------------------") - print("Vertices are ",(get + 2) - get_again) - print("--------------------------------------------------") - elif get_again_again == "CASE 3": - get = int(input("Enter Edges of the Figure:")) - print("--------------------------------------------------") - get_again = int(input("Enter Vertices of the figure:")) - print("--------------------------------------------------") - print("Vertices are ",(get + 2) - get_again) - print("--------------------------------------------------") - feature = raw_input("Start again or End:") - if feature == "Start again": - print("Starting again...") - print(" ") - continue - elif feature == "End": - print("Ending program...") - print("Finished") - print(" ") - print("--------------------------------------------------") - break diff --git a/eulers_python.py b/eulers_python.py new file mode 100644 index 0000000..273cef3 --- /dev/null +++ b/eulers_python.py @@ -0,0 +1,44 @@ +#!/usr/bin/python +# -*- coding: -*- + + +# 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 From 8e6e29502b631093abdd30e00ee4bbf68f9be4fe Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 11:25:36 +0530 Subject: [PATCH 006/151] Rename eulers_python.py to math/eulers_python.py --- eulers_python.py => math/eulers_python.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename eulers_python.py => math/eulers_python.py (100%) diff --git a/eulers_python.py b/math/eulers_python.py similarity index 100% rename from eulers_python.py rename to math/eulers_python.py From 5e47b9b802a5bd079efb28c1536bc255172a3fe1 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 11:26:17 +0530 Subject: [PATCH 007/151] Rename Very_Simple/unicode.py to simple_programs/unicode.py --- {Very_Simple => simple_programs}/unicode.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Very_Simple => simple_programs}/unicode.py (100%) diff --git a/Very_Simple/unicode.py b/simple_programs/unicode.py similarity index 100% rename from Very_Simple/unicode.py rename to simple_programs/unicode.py From 6ee6f2b2c4d9da63af1fa45efdc858efad30db6f Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 11:27:52 +0530 Subject: [PATCH 008/151] Update some styling --- simple_programs/unicode.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/simple_programs/unicode.py b/simple_programs/unicode.py index 2b45566..84bda0c 100644 --- a/simple_programs/unicode.py +++ b/simple_programs/unicode.py @@ -1,12 +1,10 @@ #!/usr/bin/python # -*- coding: -*- - # 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_))) @@ -23,5 +21,4 @@ def get_ascii(S): codes = list(get_ascii(test_case)) for code in codes: print(" character: {}, unicode_val: {}".format(code[0], code[1])) - print(" ") From 6829238a7df89aef5a02aa1fbc33a670dcbd3f11 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 11:29:06 +0530 Subject: [PATCH 009/151] Useless program, db support is missing I'll write a similar program with DB for some real usage --- Handlepassword.py | 63 ----------------------------------------------- 1 file changed, 63 deletions(-) delete mode 100644 Handlepassword.py diff --git a/Handlepassword.py b/Handlepassword.py deleted file mode 100644 index 9acf27c..0000000 --- a/Handlepassword.py +++ /dev/null @@ -1,63 +0,0 @@ -# don't forget to add a sqlite3 db support -# and also add password encryption and decryption support - -# Universal dict for saving passwords -passwords = {} - -def addPassword(): - getMoreSite = str(input('Name of Website : ')) - getMorePassword = str(input('Password : ')) - passwords[getMoreSite] = getMorePassword - -def showPassword(): - getName = str(input('Name of Website : ')) - try: - return(getName + ' : ' + str(passwords[getName])) - except KeyError: - print('Password not saved') - -def deletePassword(): - toDelete = str(input('Website of Password to delete : ')) - try: - del passwords[toDelete] - return('Deleted Successfully.') - except KeyError: - print('Invalid site to delete') - -def showAll(): - return(passwords) - -def showWebsites(): - keys = str(passwords.keys()) - return(keys[9:]) - -def mainCode(add , view , remove , allwords , allSites): - while(True): - start = str(input('Add or View or Delete or Show all or Show sites : ')) - if start.strip() == 'Add': - print(add()) - continue - elif start.strip() == 'View': - print(view()) - continue - elif start.strip() == 'Delete': - print(remove()) - continue - elif start.strip() == 'Show all': - print(allwords()) - continue - elif start.strip() == 'Show sites': - print(allSites()) - continue - else: - quit() - - -# Main code -# Login function -login = str(input('Username : ')) -loginPassword = str(input('Password : ')) -if login == 'Kalpak' and loginPassword == 'thisisapassword': # replace with your username or password - print(mainCode(addPassword , showPassword , deletePassword , showAll , showWebsites)) -else : - quit() From 6ff5ee5d105c050249be6af2e4387dfe591504ec Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 12:02:13 +0530 Subject: [PATCH 010/151] Update Number Guessing Game.py --- Number Guessing Game.py | 58 ++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 21 deletions(-) diff --git a/Number Guessing Game.py b/Number Guessing Game.py index 9526aec..d52f856 100644 --- a/Number Guessing Game.py +++ b/Number Guessing Game.py @@ -1,21 +1,37 @@ -"""this program asks person to guess a number if the number is correct the code breaks -otherwise it runs continously as it is in infinite loop""" -while(2==2): - print("Welcome to the Guessing Game") - print("Hint:number is in range 10") - start = raw_input("Enter Start or End:") - if start == "Start": - get = int(input("Guess the number:")) - if get == 5: - print("You Win") - break - elif get <= 4: - print("Number you entered is Too Low") - elif get >= 6: - print("Number you enetred is Too High") - elif start == "End": - print("Game Ended") - else : - print("You Lose Sorry!") - print("Game Ended") - +#!/usr/bin/python +# -*- coding: -*- + +from random import randint as r_int + +# generates a random number +# in inclusive list from 0 to 10 +n = r_int(0, 10) +print("Hint: number is between 0 to 10 including 0 and 10\n") + + +while True: + usr = int(raw_input("Guess a number: ")) + + # Make sure user got the hint + if usr <= 10 and usr >= 0: + + # if correct + if usr == n: + print("That's a correct guess!\nYou got it!\n") + break + + # brings user closer to answer + elif usr < n: + print("Try a bigger num!") + else: + print("Try a smaller num!") + + else: + print("Pls read the hint!") + + # Continue till guess does not match 'n' + # the random number + print("") + continue + +# Is an infinite loop if usr keeps guessing wrong From d423eda4b854dd5e60ce60cf7035c3801ab3692c Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 12:03:47 +0530 Subject: [PATCH 011/151] Update Number Guessing Game.py --- Number Guessing Game.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Number Guessing Game.py b/Number Guessing Game.py index d52f856..7029ff4 100644 --- a/Number Guessing Game.py +++ b/Number Guessing Game.py @@ -35,3 +35,6 @@ continue # Is an infinite loop if usr keeps guessing wrong +# an extra loop can be added to play game as long as user wants +# or can play number of times the user entered! +# Also can be made more harder to play From d62eadc318ee6543ad28456514efd0fbaf6ff678 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 12:04:25 +0530 Subject: [PATCH 012/151] Update encoding --- Number Guessing Game.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Number Guessing Game.py b/Number Guessing Game.py index 7029ff4..1f428ba 100644 --- a/Number Guessing Game.py +++ b/Number Guessing Game.py @@ -1,5 +1,5 @@ #!/usr/bin/python -# -*- coding: -*- +# -*- coding: utf-8 -*- from random import randint as r_int From 915a231d529c29f920e78f0c12072558aad94222 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 12:05:03 +0530 Subject: [PATCH 013/151] Rename Number Guessing Game.py to shell_games/number_guessing_game.py --- Number Guessing Game.py => shell_games/number_guessing_game.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Number Guessing Game.py => shell_games/number_guessing_game.py (100%) diff --git a/Number Guessing Game.py b/shell_games/number_guessing_game.py similarity index 100% rename from Number Guessing Game.py rename to shell_games/number_guessing_game.py From e651e6856515b596ea22a9dec3339e6dee282649 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 13:53:25 +0530 Subject: [PATCH 014/151] Update encoding --- math/eulers_python.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/eulers_python.py b/math/eulers_python.py index 273cef3..000694d 100644 --- a/math/eulers_python.py +++ b/math/eulers_python.py @@ -1,5 +1,5 @@ #!/usr/bin/python -# -*- coding: -*- +# -*- coding: utf-8 -*- # By formula derived by Euler(A great mathematician) From 9e9d198898561ace8368f78e4eb1397571a79da8 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 13:54:05 +0530 Subject: [PATCH 015/151] update file encoding --- simple_programs/unicode.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simple_programs/unicode.py b/simple_programs/unicode.py index 84bda0c..2e988ff 100644 --- a/simple_programs/unicode.py +++ b/simple_programs/unicode.py @@ -1,5 +1,5 @@ #!/usr/bin/python -# -*- coding: -*- +# -*- coding: utf-8 -*- # returns UNICODE value of a character def get_ascii(S): From f5cce4f92d3a49f303ef0ebb9f5584ada98987b6 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 13:55:10 +0530 Subject: [PATCH 016/151] Delete phonebook cuz no db support and code is useless --- Phonebook.py | 224 --------------------------------------------------- 1 file changed, 224 deletions(-) delete mode 100644 Phonebook.py diff --git a/Phonebook.py b/Phonebook.py deleted file mode 100644 index 8644a06..0000000 --- a/Phonebook.py +++ /dev/null @@ -1,224 +0,0 @@ - - -phone = {} - -class Phonebook: - - def __init__ ( self, fname, lname, phone_number, email, address ): - - self.fname = fname - self.lname = lname - self.phone_number = phone_number - self.email = email - self.address = address - - - def view_info( self ): - - print( "Name : {} {}".format( self.fname, self.lname ) ) - print( "Phone number : {}".format( self.phone_number ) ) - print( "Email : {}".format( self.email ) ) - print( "Address : {}".format( self.address ) ) - - def show_number( self ): - - return( "Phone number : {}".format( self.phone_number ) ) - - def show_email ( self ): - - return( "Email : {}".format( self.email ) ) - -def add(): - while (True): - - get_fname = str(input( "First name : " )) - get_lname = str(input( "Last name : " )) - get_phone_number = int(input( "Phone number : " )) - get_email = str(input( "Email address : " )) - get_address = str(input( "Home address : " )) - - full_name = get_fname + " " + get_lname - - phone[full_name] = Phonebook( get_fname, get_lname, get_phone_number, get_email, get_address ) - - more = str(input("Do you want to add more [Y/n] : ")) - if more.strip() == "Y": - print(" ") - continue - - else: - print(" ") - break - - -def update(): - # still working here - pass - - -def view_all(): - while (True): - - name = str(input( "Full name : " )) - if name in phone.keys(): - print(phone[name].view_info()) - - else: - print("The name you entered does not exist.Try again") - - more = str(input("Do you want to view more [Y/n] : ")) - if more.strip() == "Y": - print(" ") - continue - - else: - print(" ") - break - - -def number_contacts(): - num_of_contacts = 0 - for i in phone.keys(): - num_of_contacts += 1 - return("Total number of contacts : {}".format(num_of_contacts)) - - -def view_number(): - while (True): - - name = str(input( "Full name : " )) - if name in phone.keys(): - print(phone[name].view_number()) - - else: - print("The name you entered does not exist.Try again") - - more = str(input("Do you want to view more [Y/n] : ")) - if more.strip() == "Y": - print(" ") - continue - - else: - print(" ") - break - - -def view_email(): - while (True): - - name = str(input( "Full name : " )) - if name in phone.keys(): - print(phone[name].view_email()) - - else: - print("The name you entered does not exist.Try again") - - more = str(input("Do you want to view more [Y/n] : ")) - if more.strip() == "Y": - print(" ") - continue - - else: - print(" ") - break - - -def view_names(): - print("All contacts : ") - for i in phone.keys(): - print(" {}".format(i)) - -def delete(): - - while (True): - - if len(phone.keys()) == 0: - print("The contacts list is empty.") - break - - name = str(input( "Full name : " )) - if name in phone.keys(): - del phone[name] - print("Contact deleted successfully.") - - else: - print("The name you entered does not exist.Try again") - - more = str(input("Do you want to delete more [Y/n] : ")) - if more.strip() == "Y": - print(" ") - continue - - else: - print(" ") - break - - - -print("========================Program Started========================") - -print("Hello,") - -while (True): - - start_or_end = str(input( "Start or End : " )) - if start_or_end.strip() == "Start" : - - op = str(input( "Add or Update or Delete or View : " )) - if op.strip() == "Add": - print(add()) - print(" ") - continue - - elif op.strip() == "Update": - print(update()) - print(" ") - continue - - elif op.strip() == "Delete": - print(delete()) - print(" ") - continue - - elif op.strip() == "View": - view_op = str(input("View all or View number or View email or View names: ")) - if view_op.strip() in [ "View all", "view all", "view All", "View all", "all" ]: - print(view_all()) - print(" ") - continue - - elif view_op.strip() in [ "View number", "view number", "view Number", "View Number", "number" ]: - print(view_number()) - print(" ") - continue - - elif view_op.strip() in [ "View email", "view email", "view Email", "View Email", "email" ]: - print(view_email()) - print(" ") - continue - - elif view_op.strip() in [ "View names", "view names", "view Names", "View Names", "names" ]: - print(view_names()) - print(" ") - print(number_contacts()) - print(" ") - continue - - else: - print("Invalid Input for View menu.") - print(" ") - continue - - else: - print("Invalid Input. Try again!") - print(" ") - continue - - elif start_or_end.strip() == "End": - print("=========================Program Ended=========================") - break - - else: - print("Invalid Input. Try again!") - print(" ") - continue From 72c30fe2a1bbcb4c9d5b97c73dd1b66c2b14ad67 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 14:05:33 +0530 Subject: [PATCH 017/151] Update and rename YoutubePlayer.py to website_opener.py --- YoutubePlayer.py | 17 ----------------- website_opener.py | 18 ++++++++++++++++++ 2 files changed, 18 insertions(+), 17 deletions(-) delete mode 100644 YoutubePlayer.py create mode 100644 website_opener.py diff --git a/YoutubePlayer.py b/YoutubePlayer.py deleted file mode 100644 index cd6b665..0000000 --- a/YoutubePlayer.py +++ /dev/null @@ -1,17 +0,0 @@ -# Just Exploring webbrowser lib -import webbrowser -import random - -youtubeMusic = ["https://www.youtube.com/watch?v=6pR5cyH63mA", "https://www.youtube.com/watch?v=4JK_Lg8P7PU", "https://www.youtube.com/watch?v=nbjwmC8K4K4", "https://www.youtube.com/watch?v=qHm9MG9xw1o", "https://www.youtube.com/watch?v=QJO3ROT-A4E"] - -user = str(raw_input("Start playing : ")) -if user == "No": - exit() - -playingStyle = str(raw_input("Play in order or random song : ")) - -if user == "Yes" and playingStyle == "random song": - webbrowser.open(random.choice(["https://www.youtube.com/watch?v=6pR5cyH63mA", "https://www.youtube.com/watch?v=4JK_Lg8P7PU", "https://www.youtube.com/watch?v=nbjwmC8K4K4", "https://www.youtube.com/watch?v=qHm9MG9xw1o", "https://www.youtube.com/watch?v=QJO3ROT-A4E"])) -elif user == "Yes" and playingStyle == "Play in order": - for x in youtubeMusic: - webbrowser.open(x) diff --git a/website_opener.py b/website_opener.py new file mode 100644 index 0000000..0ccf24f --- /dev/null +++ b/website_opener.py @@ -0,0 +1,18 @@ +#!/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) From 3695187d1c165c5dd3c12f651e8f019b92eca9f8 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 14:06:14 +0530 Subject: [PATCH 018/151] Rename website_opener.py to simple_programs/website_opener.py --- website_opener.py => simple_programs/website_opener.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename website_opener.py => simple_programs/website_opener.py (100%) diff --git a/website_opener.py b/simple_programs/website_opener.py similarity index 100% rename from website_opener.py rename to simple_programs/website_opener.py From 272068dd47e0a5b86d65eb3df3d80367e0cd3e8f Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 19:55:52 +0530 Subject: [PATCH 019/151] Tried to keep it similar to orignal --- aircraft_thrust.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/aircraft_thrust.py b/aircraft_thrust.py index 6aa73a8..25e1f79 100644 --- a/aircraft_thrust.py +++ b/aircraft_thrust.py @@ -1,17 +1,27 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + import math -# Calculating thrust of Aircraft Propeller +# 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,') +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('Diameter of propeller: ')) , float(input('Velocity of air flow: ')) , float(input('Additional propeller acceleration, velocity: ')) , float(input('Fluid density: '))) print("Thrust of propeller: {}".format(res)) - continue + else: quit() -# I dont know much about airplane physics this formula maybe wrong + print("") + +# found formula on nasa's website From 48373267bc286e08266e0f4d461df69758c9c81c Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 19:56:33 +0530 Subject: [PATCH 020/151] Rename aircraft_thrust.py to math/aircraft_thrust.py Tried to keep program as original as possible --- aircraft_thrust.py => math/aircraft_thrust.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename aircraft_thrust.py => math/aircraft_thrust.py (100%) diff --git a/aircraft_thrust.py b/math/aircraft_thrust.py similarity index 100% rename from aircraft_thrust.py rename to math/aircraft_thrust.py From 8aab06bdcd7c01db6aced7746305fb48581d0b5c Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 19:57:44 +0530 Subject: [PATCH 021/151] Update some interface styling --- math/aircraft_thrust.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/math/aircraft_thrust.py b/math/aircraft_thrust.py index 25e1f79..9425042 100644 --- a/math/aircraft_thrust.py +++ b/math/aircraft_thrust.py @@ -17,8 +17,8 @@ def thrust_props(diameter , velocity , velocity1 , density): # Main interface if start_or_end == 'start': - res = thrust_props(float(input('Diameter of propeller: ')) , float(input('Velocity of air flow: ')) , float(input('Additional propeller acceleration, velocity: ')) , float(input('Fluid density: '))) - print("Thrust of propeller: {}".format(res)) + 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() From d43be424d8d9b1cbda3456d0ffb0703845f9c674 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 20:08:32 +0530 Subject: [PATCH 022/151] Create README for math sub-dir --- math/README.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 math/README.md diff --git a/math/README.md b/math/README.md new file mode 100644 index 0000000..8b842c8 --- /dev/null +++ b/math/README.md @@ -0,0 +1,8 @@ + +
 
+'math' Sub-directory contains all the math related programs
+The programs have be 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
+
From dc625f134a72c7af436fddb9a06245f6429dd3bb Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 20:09:22 +0530 Subject: [PATCH 023/151] Update spelling --- math/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/README.md b/math/README.md index 8b842c8..fef474d 100644 --- a/math/README.md +++ b/math/README.md @@ -1,7 +1,7 @@
 
 'math' Sub-directory contains all the math related programs
-The programs have be re-checked and re-mastered by me!
+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

From 8b42863c2c67a4de5b4679c30c536206a1ed4735 Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Thu, 25 Jan 2018 20:13:33 +0530
Subject: [PATCH 024/151] Create README.md

---
 shell_games/README.md | 11 +++++++++++
 1 file changed, 11 insertions(+)
 create mode 100644 shell_games/README.md

diff --git a/shell_games/README.md b/shell_games/README.md
new file mode 100644
index 0000000..39cc73b
--- /dev/null
+++ b/shell_games/README.md
@@ -0,0 +1,11 @@
+
+
 
+'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
+
From 78f0e596ecb008a32413a52ac5732185646245d4 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 20:16:17 +0530 Subject: [PATCH 025/151] Create README.md --- simple_programs/README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 simple_programs/README.md diff --git a/simple_programs/README.md b/simple_programs/README.md new file mode 100644 index 0000000..2696768 --- /dev/null +++ b/simple_programs/README.md @@ -0,0 +1,10 @@ + +
 
+'simple_programs' Sub-directory contains all simplest programs,
+these programs are simple to read/write.
+
+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
+
From b9f2a6ddf39aa28022087115e7a1f56c0b4be94e Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 20:37:22 +0530 Subject: [PATCH 026/151] Update and rename analytical_functions.py to algorithms/analysis/count.py Making programs more precise easier to understand and use --- algorithms/analysis/count.py | 34 +++++ analytical_functions.py | 234 ----------------------------------- 2 files changed, 34 insertions(+), 234 deletions(-) create mode 100644 algorithms/analysis/count.py delete mode 100644 analytical_functions.py diff --git a/algorithms/analysis/count.py b/algorithms/analysis/count.py new file mode 100644 index 0000000..f1469bd --- /dev/null +++ b/algorithms/analysis/count.py @@ -0,0 +1,34 @@ +#!/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 diff --git a/analytical_functions.py b/analytical_functions.py deleted file mode 100644 index ea9aeb9..0000000 --- a/analytical_functions.py +++ /dev/null @@ -1,234 +0,0 @@ - -""" -After looking at the code you might've thought that -i've used too common `Exception` everywhere! -That's because i'm too lazy to find or think about every single -exception that can occur! -""" - -""" -Changes you should make to use the class on single data set; -def __init__(self, data): - self.data - -then, -change all @classmethods to the methods operating on self.data -and also change corresponding changes -""" -import math - - -class AnalysisFunctions: - @classmethod - def count(cls, to_check, n): - if not(isinstance(to_check, str) or isinstance(to_check, list)): - raise TypeError("Expected a string or list, but, got a {} instead!".format(type(to_check))) - else: - if isinstance(to_check, str): - to_check = [str(s) for s in to_check] - counter = 0 - for _ in to_check: - if _ == n: - counter = counter + 1 - return counter - - @classmethod - def sum(cls, *args): - res = 0 - try: - for i in args: - res += i - except Exception as e: - return e - else: - return res - - @classmethod - def mean(cls, arr): - try: - average = sum(arr) / len(arr) - except Exception as e: - return e - else: - return average - - @classmethod - def mean_arr(cls, li): - res = [] - try: - for i in range(len(li) - 1): - a = li[i] - b = li[i + 1] - res.append(round(math.sqrt(a * b), 2)) - except Exception as e: - return e - else: - return res - - @classmethod - def mult(cls, *args): - res = 1 - try: - for i in args: - res *= i - except Exception as e: - return e - else: - return res - - @classmethod - def enum(cls, arr): - res = [] - try: - for item in arr: - tmp = (arr.index(item), item) - res.append(tmp) - except Exception as e: - return e - else: - return res - - @classmethod - def median(cls, data): - if not(sorted(data) == data): - data.sort() - res = None - try: - if not(len(data) % 2 == 0): - middle = int((len(data) + 1) / 2) - res = data[middle - 1] - else: - middle = int((len(data) + 2) / 2) - middle_1 = int(len(data) / 2) - res = (data[middle - 1] + data[middle_1 - 1]) / 2 - except Exception as e: - return e - else: - return res - - @classmethod - def length(cls, x): - counter = 0 - try: - if isinstance(x, str): - x = list(x) - for i in x: - counter = counter + 1 - except Exception as e: - return e - else: - return counter - - @classmethod - def factorial(cls, n): - try: - if n <= 1: - return 1 - else: - fact = n * AnalysisFunctions().factorial(n - 1) - return fact - except Exception as e: - return e - - @classmethod - def sort(cls, arr): - try: - for i in range(len(arr)): - for n in range(len(arr) - 1): - x = arr[n] - y = arr[n + 1] - if y < x: - tmp = x - arr[n] = y - arr[n + 1] = tmp - except Exception as e: - return e - - @classmethod - def reverse_sort(cls, arr): - try: - for i in range(len(arr)): - for n in range(len(arr) - 1): - x = arr[n] - y = arr[n + 1] - if y > x: - tmp = x - arr[n] = y - arr[n + 1] = tmp - except Exception as e: - return e - - @classmethod - def sorted(cls, arr): - try: - for i in range(len(arr)): - for n in range(len(arr) - 1): - x = arr[n] - y = arr[n + 1] - if y < x: - tmp = x - arr[n] = y - arr[n + 1] = tmp - except Exception as e: - return e - else: - return arr - - @classmethod - def sqre(cls, num): - try: - square = num ** 2 - except Exception as e: - return e - else: - return square - - @classmethod - def is_divisible(cls, x, y): - try: - return x % y == 0 - except Exception as e: - return e - - @classmethod - def is_odd(cls, n): - try: - return n % 2 != 0 - except Exception as e: - return e - - @classmethod - def is_even(cls, n): - try: - return n % 2 == 0 - except Exception as e: - return e - - @classmethod - def max(cls, arr): - try: - maxi = arr[0] - for elem in arr[1:]: - if elem > maxi: - maxi = elem - except Exception as e: - return e - else: - return maxi - - @classmethod - def min(cls, arr): - try: - mini = arr[0] - for elem in arr[1:]: - if elem < mini: - mini = elem - except Exception as e: - return e - else: - return mini - -""" -It will be so kind to report bugs -""" -# I hate indentation problems From 6af9025abc4ba092c8afd560a465451240655457 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 20:41:04 +0530 Subject: [PATCH 027/151] Create README.md --- algorithms/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 algorithms/README.md diff --git a/algorithms/README.md b/algorithms/README.md new file mode 100644 index 0000000..583cb45 --- /dev/null +++ b/algorithms/README.md @@ -0,0 +1,9 @@ + +
+'math' Sub-directory contains all algorithms
+further separated in different 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
+
From ded1ae07338ba30c52c8510f57d768f5043244ae Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 20:43:10 +0530 Subject: [PATCH 028/151] Create README.md --- algorithms/analysis/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 algorithms/analysis/README.md diff --git a/algorithms/analysis/README.md b/algorithms/analysis/README.md new file mode 100644 index 0000000..c67a0cc --- /dev/null +++ b/algorithms/analysis/README.md @@ -0,0 +1,9 @@ + + + +
+'analysis' Sub-directory contains all 
+analysis related algorithms.
+
+Thanks
+
From ae860fe5d9d2da3384399b9e15f1dd23b53fff3a Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 21:12:10 +0530 Subject: [PATCH 029/151] Create sum.py --- algorithms/analysis/sum.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 algorithms/analysis/sum.py diff --git a/algorithms/analysis/sum.py b/algorithms/analysis/sum.py new file mode 100644 index 0000000..5f50eb8 --- /dev/null +++ b/algorithms/analysis/sum.py @@ -0,0 +1,32 @@ +#!/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 + 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 + for elem in ar[:end_i + 1]: + res += elem + + return res + +# Simple Algorithm From 2e69dcddec0b9e7a0e2aff3a60655cc59eae9eaa Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 21:17:46 +0530 Subject: [PATCH 030/151] Update testing, testcases --- algorithms/analysis/sum.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/algorithms/analysis/sum.py b/algorithms/analysis/sum.py index 5f50eb8..1a49021 100644 --- a/algorithms/analysis/sum.py +++ b/algorithms/analysis/sum.py @@ -30,3 +30,15 @@ def sum_ar(ar, end_i): 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!") From 803832b3658fdaf4033c7ad4e84a99c692f8268b Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 21:35:50 +0530 Subject: [PATCH 031/151] Datatype flaw --- algorithms/analysis/sum.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/algorithms/analysis/sum.py b/algorithms/analysis/sum.py index 1a49021..43e3d24 100644 --- a/algorithms/analysis/sum.py +++ b/algorithms/analysis/sum.py @@ -8,7 +8,7 @@ # return sum def sum_(*args): - res = 0 + res = 0.0 for arg in args: res += arg return res @@ -23,7 +23,7 @@ def sum_ar(ar, end_i): else: end_i = len(ar) - 1 - res = 0 + res = 0.0 for elem in ar[:end_i + 1]: res += elem From 3b0b8cc9ca77e321ed913e1d066799bcaaac294c Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 21:37:36 +0530 Subject: [PATCH 032/151] Create mean.py --- algorithms/analysis/mean.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 algorithms/analysis/mean.py diff --git a/algorithms/analysis/mean.py b/algorithms/analysis/mean.py new file mode 100644 index 0000000..a871c98 --- /dev/null +++ b/algorithms/analysis/mean.py @@ -0,0 +1,37 @@ +#!/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!") + From f8495df3a921e4d9ae921aeed58f9f3e6afda26e Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 21:46:18 +0530 Subject: [PATCH 033/151] Create enum.py --- algorithms/analysis/enum.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 algorithms/analysis/enum.py diff --git a/algorithms/analysis/enum.py b/algorithms/analysis/enum.py new file mode 100644 index 0000000..79402af --- /dev/null +++ b/algorithms/analysis/enum.py @@ -0,0 +1,23 @@ +#!/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((ar[index], 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 From f1948a73cec74eab7e38cee117018521e4cdb37f Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 21:58:42 +0530 Subject: [PATCH 034/151] Useless file/program --- another_calculator.py | 29 ----------------------------- 1 file changed, 29 deletions(-) delete mode 100644 another_calculator.py diff --git a/another_calculator.py b/another_calculator.py deleted file mode 100644 index ba37434..0000000 --- a/another_calculator.py +++ /dev/null @@ -1,29 +0,0 @@ -def adda(): - return float(raw_input("enter number here:")) + float(raw_input("enter next number :")) - -def extract(): - return float(raw_input("enter number here:")) - float(raw_input("enter next number :")) - -def multiple(): - return float(raw_input("enter number here:")) * float(raw_input("enter next number :")) - -def divi(): - try: - return float(raw_input("enter number here:")) / float(raw_input("enter number here:")) - except ZeroDivisionError: - return "Cannot divide by Zero." - -def modula(): - return float(raw_input("enter number here:")) % float(raw_input("enter next number :")) - -user = raw_input("enter add,subtract,multiply,divide,modulo :") -if user == "add": - print float(adda()) -elif user == "subtract": - print float(extract()) -elif user == "multiply": - print float(multiple()) -elif user == "divide": - print float(divi()) -elif user == "modulo": - print float(modula()) From 7d8740592ed1ba926821edd0a8dd6a259d8ba28e Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 22:51:32 +0530 Subject: [PATCH 035/151] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 08a945b..dd3dc7c 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,9 @@ Hey guys i wrote these programs when i was just starting up with programming, no Note: In 2.x versions input isn't useful , lly , 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! +
+NOTE: WORK IN PROGRESS!
+


Also see this : Beginners-Python-Examples/CONTRIBUTING.md
contact kalpaktake@gmail.com From 55eb73ae08ba870e0bd75d225ae67cb4c5eb9757 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 23:01:09 +0530 Subject: [PATCH 036/151] Update and rename is_palindrome.py to algorithms/string/is_palindrome.py --- algorithms/string/is_palindrome.py | 27 +++++++++++++++++++++++++++ is_palindrome.py | 21 --------------------- 2 files changed, 27 insertions(+), 21 deletions(-) create mode 100644 algorithms/string/is_palindrome.py delete mode 100644 is_palindrome.py diff --git a/algorithms/string/is_palindrome.py b/algorithms/string/is_palindrome.py new file mode 100644 index 0000000..9cd0832 --- /dev/null +++ b/algorithms/string/is_palindrome.py @@ -0,0 +1,27 @@ +#!/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 satck 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) diff --git a/is_palindrome.py b/is_palindrome.py deleted file mode 100644 index 0e37599..0000000 --- a/is_palindrome.py +++ /dev/null @@ -1,21 +0,0 @@ - - -class Palindrome: - - @classmethod - def is_palindrome(cls, word): - if (len(word) > 0): - pre = word[::-1].lower() - if (pre == word.lower()): - return True - else: - return False - else: - return None - -# Testing the function - -get_word = str(input("Enter a Word : ")) -print(" ") -print(Palindrome.is_palindrome(get_word)) - From cfd30116cd41ccf224fc9034daeaa7b04e796eaf Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 25 Jan 2018 23:02:23 +0530 Subject: [PATCH 037/151] Create README.md --- algorithms/string/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 algorithms/string/README.md diff --git a/algorithms/string/README.md b/algorithms/string/README.md new file mode 100644 index 0000000..e68b6c1 --- /dev/null +++ b/algorithms/string/README.md @@ -0,0 +1,7 @@ + +
+'string' Sub-directory contains all 
+string related algorithms
+
+Thanks
+
From 05b1383b1296d3c9922a6af49256fcc9be9fa7ab Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 11:22:18 +0530 Subject: [PATCH 038/151] Update spelling mistake Satck -> Stack --- algorithms/string/is_palindrome.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/string/is_palindrome.py b/algorithms/string/is_palindrome.py index 9cd0832..77faea3 100644 --- a/algorithms/string/is_palindrome.py +++ b/algorithms/string/is_palindrome.py @@ -10,7 +10,7 @@ # string[::-1] is a clever way to reverse string # string from start index to end index # whose difference is -1(reverse) -# found on satck overflow, very pythonic +# found on stack overflow, very pythonic def is_palindrome(s) : if s[::-1] == s: From a900a6d535cf943632fd484d3d92f4e607d55bc7 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 12:08:48 +0530 Subject: [PATCH 039/151] Median of un-distributed data --- algorithms/analysis/median.py | 54 +++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 algorithms/analysis/median.py diff --git a/algorithms/analysis/median.py b/algorithms/analysis/median.py new file mode 100644 index 0000000..03e5bb1 --- /dev/null +++ b/algorithms/analysis/median.py @@ -0,0 +1,54 @@ +#!/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 data +# i.e. no frequencies +# plain numbers in an array From 0b256fbaa899d97b4545a01137e5dad848d035b7 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 12:10:38 +0530 Subject: [PATCH 040/151] Update some styling --- algorithms/analysis/median.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/algorithms/analysis/median.py b/algorithms/analysis/median.py index 03e5bb1..586b32d 100644 --- a/algorithms/analysis/median.py +++ b/algorithms/analysis/median.py @@ -38,6 +38,7 @@ def median(ar, ranked = False): # 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 @@ -49,6 +50,6 @@ def median(ar, ranked = False): # If algo didn't work print("There's something wrong!") -# This median is for un-distributed data +# This median is for un-distributed/un-grouped data # i.e. no frequencies # plain numbers in an array From f9e9a962b2d365649ab9bc269bd85310d2c22620 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 13:59:06 +0530 Subject: [PATCH 041/151] Create length.py count length of different sequences --- algorithms/analysis/length.py | 87 +++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 algorithms/analysis/length.py diff --git a/algorithms/analysis/length.py b/algorithms/analysis/length.py new file mode 100644 index 0000000..b56b394 --- /dev/null +++ b/algorithms/analysis/length.py @@ -0,0 +1,87 @@ +#!/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") From 78197611a84041affdecae27563dd6d01d2099ee Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 14:00:18 +0530 Subject: [PATCH 042/151] Rename simple_programs/unicode.py to simple_scripts/unicode.py --- {simple_programs => simple_scripts}/unicode.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {simple_programs => simple_scripts}/unicode.py (100%) diff --git a/simple_programs/unicode.py b/simple_scripts/unicode.py similarity index 100% rename from simple_programs/unicode.py rename to simple_scripts/unicode.py From 7312580a9e0a3e99cc5ef75e16e35a6f6ab43c9e Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 14:00:51 +0530 Subject: [PATCH 043/151] Rename simple_programs/website_opener.py to simple_scripts/website_opener.py --- {simple_programs => simple_scripts}/website_opener.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {simple_programs => simple_scripts}/website_opener.py (100%) diff --git a/simple_programs/website_opener.py b/simple_scripts/website_opener.py similarity index 100% rename from simple_programs/website_opener.py rename to simple_scripts/website_opener.py From 5129d4bbc5f96569bd01bc0c4f43b84ca8e05edb Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 14:01:17 +0530 Subject: [PATCH 044/151] Rename simple_programs/README.md to simple_scripts/README.md --- {simple_programs => simple_scripts}/README.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {simple_programs => simple_scripts}/README.md (100%) diff --git a/simple_programs/README.md b/simple_scripts/README.md similarity index 100% rename from simple_programs/README.md rename to simple_scripts/README.md From 80dd8a4761a9b3065736e12324792a4fa2593d36 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 14:01:44 +0530 Subject: [PATCH 045/151] Update README.md --- simple_scripts/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simple_scripts/README.md b/simple_scripts/README.md index 2696768..898d518 100644 --- a/simple_scripts/README.md +++ b/simple_scripts/README.md @@ -1,6 +1,6 @@
 
-'simple_programs' Sub-directory contains all simplest programs,
+'simple_scripts' Sub-directory contains all simplest programs,
 these programs are simple to read/write.
 
 The programs have been re-checked and re-mastered by me!

From 4be08afadf210dc6f71a008a0905371bb5e0cdd3 Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 14:04:32 +0530
Subject: [PATCH 046/151] Delete tkinter_label.py

---
 tkinter_label.py | 7 -------
 1 file changed, 7 deletions(-)
 delete mode 100644 tkinter_label.py

diff --git a/tkinter_label.py b/tkinter_label.py
deleted file mode 100644
index f809b1f..0000000
--- a/tkinter_label.py
+++ /dev/null
@@ -1,7 +0,0 @@
-import tkinter
-
-root = tkinter.Tk()
-root.title('Kalpak')
-lab = tkinter.Label(None , text = 'This is a label.' )
-lab.pack()
-root.mainloop()

From 354b732ac891c9424950a68e281bc50d67e24770 Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 14:04:46 +0530
Subject: [PATCH 047/151] Delete variable_examples.py

---
 variable_examples.py | 5 -----
 1 file changed, 5 deletions(-)
 delete mode 100644 variable_examples.py

diff --git a/variable_examples.py b/variable_examples.py
deleted file mode 100644
index 774e5d0..0000000
--- a/variable_examples.py
+++ /dev/null
@@ -1,5 +0,0 @@
-# below is an example of varible
-# variable is created by = to sign and is known an assignment operator
-
-message = "Hello Python!"
-print(message)

From 4d8c8583f4dfaa8ad9b3aca212739cc83a138a01 Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 20:01:21 +0530
Subject: [PATCH 048/151] Create factorial.py

Implementation of factorial in 2 different ways
---
 algorithms/numbers/factorial.py | 55 +++++++++++++++++++++++++++++++++
 1 file changed, 55 insertions(+)
 create mode 100644 algorithms/numbers/factorial.py

diff --git a/algorithms/numbers/factorial.py b/algorithms/numbers/factorial.py
new file mode 100644
index 0000000..c38ee91
--- /dev/null
+++ b/algorithms/numbers/factorial.py
@@ -0,0 +1,55 @@
+#!/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!")

From 938354f249acdcd12058de685e10e4e2e4c1b8e3 Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 21:13:06 +0530
Subject: [PATCH 049/151] Update generated tuple's sequence

---
 algorithms/analysis/enum.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/algorithms/analysis/enum.py b/algorithms/analysis/enum.py
index 79402af..c6bf35e 100644
--- a/algorithms/analysis/enum.py
+++ b/algorithms/analysis/enum.py
@@ -5,7 +5,7 @@
 # yields a tuple of element and it's index
 def enum(ar):
 	for index in range(len(ar)):
-		yield((ar[index], index))
+		yield((index, ar[index]))
 
 # Test
 case_1 = [19, 17, 20, 23, 27, 15]

From ecb752a2371bd2bf6071211a156898bcc6ba0736 Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 21:31:21 +0530
Subject: [PATCH 050/151] Create sort.py

Bubble sort algorithm
---
 algorithms/analysis/sort.py | 67 +++++++++++++++++++++++++++++++++++++
 1 file changed, 67 insertions(+)
 create mode 100644 algorithms/analysis/sort.py

diff --git a/algorithms/analysis/sort.py b/algorithms/analysis/sort.py
new file mode 100644
index 0000000..0cd99b3
--- /dev/null
+++ b/algorithms/analysis/sort.py
@@ -0,0 +1,67 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# Bubble Sort
+# Good sorting algorithm for 
+# small data/array
+
+# temporary parameter tells
+# function to sort a copy of 
+# orignal array, and not the array itself
+
+def sort_(arr, temporary = 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):
+
+			# Swapping greater elements to right
+			# and smaller to left
+			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 = [[9, 8, 7, 6, 5, 4, 3, 2, 1, 0], [1312, 1110, 98, 76, 54, 32, 10], ] # Add your test cases 
+for test in tests:
+	c = sort_(test, True) 
+	if c == sorted(test):
+		print("Orignal: {}".format(test))
+		print("Sorted: {}".format(c))
+		print("It worked!\n")
+	else:
+		print("Something went wrong!\n")
+
+
+# Seems our bubble sort works
+# however for small data or array!

From 8768e08951f7090d7d4c433ca31f834244e2e3de Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 21:32:43 +0530
Subject: [PATCH 051/151] Create classic bubble_sort.py

---
 algorithms/sorting/bubble_sort.py | 67 +++++++++++++++++++++++++++++++
 1 file changed, 67 insertions(+)
 create mode 100644 algorithms/sorting/bubble_sort.py

diff --git a/algorithms/sorting/bubble_sort.py b/algorithms/sorting/bubble_sort.py
new file mode 100644
index 0000000..491fbe3
--- /dev/null
+++ b/algorithms/sorting/bubble_sort.py
@@ -0,0 +1,67 @@
+#!/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
+
+def sort_(arr, temporary = 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):
+
+			# Swapping greater elements to right
+			# and smaller to left
+			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 = [[9, 8, 7, 6, 5, 4, 3, 2, 1, 0], [1312, 1110, 98, 76, 54, 32, 10], ] # Add your test cases 
+for test in tests:
+	c = sort_(test, True) 
+	if c == sorted(test):
+		print("Orignal: {}".format(test))
+		print("Sorted: {}".format(c))
+		print("It worked!\n")
+	else:
+		print("Something went wrong!\n")
+
+
+# Seems our bubble sort works
+# however for small data or array!

From 98ad467a887c552c8b668fbb1f2917bd5a70068b Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 21:43:45 +0530
Subject: [PATCH 052/151] Add reverse sort feature

---
 algorithms/sorting/bubble_sort.py | 45 ++++++++++++++++++++++---------
 1 file changed, 32 insertions(+), 13 deletions(-)

diff --git a/algorithms/sorting/bubble_sort.py b/algorithms/sorting/bubble_sort.py
index 491fbe3..6d16aa2 100644
--- a/algorithms/sorting/bubble_sort.py
+++ b/algorithms/sorting/bubble_sort.py
@@ -9,6 +9,10 @@
 # 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):
 	
 	# Making copy of array if temporary is true
@@ -17,7 +21,8 @@ def sort_(arr, temporary = False):
 	else:
 		ar = arr
 	
-	# To blend every element in correct position
+	# To blend every element
+	# in correct position
 	# length of total array is required
 	length = len(ar)
 	
@@ -29,12 +34,25 @@ def sort_(arr, temporary = False):
 		# through un-sorted elements
 		for i in range(0, length - 1):
 
-			# Swapping greater elements to right
-			# and smaller to left
-			if ar[i] > ar[i+1]:
-				tmp = ar[i]
-				ar[i] = ar[i + 1]
-				ar[i + 1] = tmp
+			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 
@@ -52,16 +70,17 @@ def sort_(arr, temporary = False):
 
 
 # Testing
-tests = [[9, 8, 7, 6, 5, 4, 3, 2, 1, 0], [1312, 1110, 98, 76, 54, 32, 10], ] # Add your test cases 
+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:
-	c = sort_(test, True) 
-	if c == sorted(test):
+	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(c))
-		print("It worked!\n")
+		print("Sorted: {}".format(accend))
+		print("Sorted(reverse): {}".format(decend))
 	else:
 		print("Something went wrong!\n")
 
 
 # Seems our bubble sort works
-# however for small data or array!
+# however for small data/array!

From 496865ab0731e4ff3f19b30546dfb6defa45c3ab Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 21:45:53 +0530
Subject: [PATCH 053/151] Add reverse sort feature

---
 algorithms/analysis/sort.py | 49 +++++++++++++++++++++++++------------
 1 file changed, 34 insertions(+), 15 deletions(-)

diff --git a/algorithms/analysis/sort.py b/algorithms/analysis/sort.py
index 0cd99b3..9074ad0 100644
--- a/algorithms/analysis/sort.py
+++ b/algorithms/analysis/sort.py
@@ -2,14 +2,18 @@
 # -*- coding: utf-8 -*-
 
 # Bubble Sort
-# Good sorting algorithm for 
+# Ideal sorting algorithm for 
 # small data/array
 
 # temporary parameter tells
 # function to sort a copy of 
 # orignal array, and not the array itself
 
-def sort_(arr, temporary = False):
+# 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:
@@ -17,7 +21,8 @@ def sort_(arr, temporary = False):
 	else:
 		ar = arr
 	
-	# To blend every element in correct position
+	# To blend every element
+	# in correct position
 	# length of total array is required
 	length = len(ar)
 	
@@ -29,12 +34,25 @@ def sort_(arr, temporary = False):
 		# through un-sorted elements
 		for i in range(0, length - 1):
 
-			# Swapping greater elements to right
-			# and smaller to left
-			if ar[i] > ar[i+1]:
-				tmp = ar[i]
-				ar[i] = ar[i + 1]
-				ar[i + 1] = tmp
+			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 
@@ -52,16 +70,17 @@ def sort_(arr, temporary = False):
 
 
 # Testing
-tests = [[9, 8, 7, 6, 5, 4, 3, 2, 1, 0], [1312, 1110, 98, 76, 54, 32, 10], ] # Add your test cases 
+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:
-	c = sort_(test, True) 
-	if c == sorted(test):
+	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(c))
-		print("It worked!\n")
+		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 or array!
+# however for small data/array!

From ad27e391bb95496ff32ad848f31f67c4b3eca7d7 Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 21:47:11 +0530
Subject: [PATCH 054/151] Update params list to avoid errors & some styling

---
 algorithms/sorting/bubble_sort.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/algorithms/sorting/bubble_sort.py b/algorithms/sorting/bubble_sort.py
index 6d16aa2..9074ad0 100644
--- a/algorithms/sorting/bubble_sort.py
+++ b/algorithms/sorting/bubble_sort.py
@@ -13,7 +13,7 @@
 # to sort array in reverse/decending
 # order
 
-def sort_(arr, temporary = False):
+def sort_(arr, temporary = False, reverse = False):
 	
 	# Making copy of array if temporary is true
 	if temporary:
@@ -77,7 +77,7 @@ def sort_(arr, temporary = False):
 	if accend == sorted(test) and decend == sorted(test, reverse = True):
 		print("Orignal: {}".format(test))
 		print("Sorted: {}".format(accend))
-		print("Sorted(reverse): {}".format(decend))
+		print("Sorted(reverse): {}\n".format(decend))
 	else:
 		print("Something went wrong!\n")
 

From 2619caf9c802fd439fc334cc051bdccb3ed2f6ec Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 22:06:43 +0530
Subject: [PATCH 055/151] Create password_generator.py

A strong, powerful password generator.
---
 useful_scripts/password_generator.py | 47 ++++++++++++++++++++++++++++
 1 file changed, 47 insertions(+)
 create mode 100644 useful_scripts/password_generator.py

diff --git a/useful_scripts/password_generator.py b/useful_scripts/password_generator.py
new file mode 100644
index 0000000..34d3188
--- /dev/null
+++ b/useful_scripts/password_generator.py
@@ -0,0 +1,47 @@
+#!/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")

From 59a68eab3ee95939d797deee7bfda7cfd5c8547d Mon Sep 17 00:00:00 2001
From: Kalpak Take 
Date: Fri, 26 Jan 2018 22:09:26 +0530
Subject: [PATCH 056/151] Update README.md

---
 README.md | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/README.md b/README.md
index dd3dc7c..69c471f 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,10 @@ Hey guys i wrote these programs when i was just starting up with programming, no
 Note: In 2.x versions input isn't useful , lly , 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! 
 
 
-NOTE: WORK IN PROGRESS!
+NOTE: WORK IN PROGRESS!
+Files Outside Particular Folders/Directories have not been checked yet!
+Files inside, directories offer much elegant code and explaination
+
 


Also see this : Beginners-Python-Examples/CONTRIBUTING.md
From d5fe9de0a3d601ad4c6cb2ea68efe3b60630f7c3 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 22:26:11 +0530 Subject: [PATCH 057/151] Create useful_function_mapping.py Includes functions like divisibility check, squaring a number, raising a number to given power, et cetera --- .../analysis/useful_function_mapping.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 algorithms/analysis/useful_function_mapping.py diff --git a/algorithms/analysis/useful_function_mapping.py b/algorithms/analysis/useful_function_mapping.py new file mode 100644 index 0000000..76a0c0a --- /dev/null +++ b/algorithms/analysis/useful_function_mapping.py @@ -0,0 +1,35 @@ +#!/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 + From 5bd3b3b53d4321219f2e43270f263228466f1622 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 23:11:36 +0530 Subject: [PATCH 058/151] Create max.py find maximum number in given array --- algorithms/analysis/max.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 algorithms/analysis/max.py diff --git a/algorithms/analysis/max.py b/algorithms/analysis/max.py new file mode 100644 index 0000000..eab3474 --- /dev/null +++ b/algorithms/analysis/max.py @@ -0,0 +1,36 @@ +#!/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!") From 10c4fd6e75befa1418eb0b266386296fbd4bcd2b Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 23:15:53 +0530 Subject: [PATCH 059/151] Create min.py Find min or smallest number in data --- algorithms/analysis/min.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 algorithms/analysis/min.py diff --git a/algorithms/analysis/min.py b/algorithms/analysis/min.py new file mode 100644 index 0000000..e848335 --- /dev/null +++ b/algorithms/analysis/min.py @@ -0,0 +1,37 @@ +#!/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!") From 066b63a22e93c0c9e70ab879ca8455af7cfbc93d Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 26 Jan 2018 23:46:57 +0530 Subject: [PATCH 060/151] Update and rename arithmetic_progression_builder.py to math/arithmetic_progression_builder.py --- arithmetic_progression_builder.py | 27 ------------------ math/arithmetic_progression_builder.py | 38 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 27 deletions(-) delete mode 100644 arithmetic_progression_builder.py create mode 100644 math/arithmetic_progression_builder.py diff --git a/arithmetic_progression_builder.py b/arithmetic_progression_builder.py deleted file mode 100644 index 28a0be8..0000000 --- a/arithmetic_progression_builder.py +++ /dev/null @@ -1,27 +0,0 @@ - -def sum_sequence(seq): - # Sn = n / 2 * (t1 + tn) formula from algebra - t1 = seq[0] - tn = seq[-1] - d = seq[1] - seq[0] - n = len(seq) - return n / 2 * (t1 + tn) - -def build_arithmetic_seq(start, end, diff): - a_seq = [start] - try: - for i in range(start, end): - a_seq.append(a_seq[-1] + diff) - except TypeError as typerr: - print(typerr) - except Exception as e: - print(e) - else: - return a_seq - -# Test -res = build_arithmetic_seq(1, 10, 2) -print("Arithmetic sequence:") -for _ in res: - print(" " + str(_)) -print("Sum of sequence: {}".format(sum_sequence(res))) diff --git a/math/arithmetic_progression_builder.py b/math/arithmetic_progression_builder.py new file mode 100644 index 0000000..89d3fa6 --- /dev/null +++ b/math/arithmetic_progression_builder.py @@ -0,0 +1,38 @@ +#!/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! From 0b243db36df47521127ff0595daec5f4687f20ca Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 01:04:10 +0530 Subject: [PATCH 061/151] Update and rename ascii_encrypting.py to algorithms/string/caesars_cipher_encryption.py --- .../string/caesars_cipher_encryption.py | 84 +++++++++++++++++++ ascii_encrypting.py | 14 ---- 2 files changed, 84 insertions(+), 14 deletions(-) create mode 100644 algorithms/string/caesars_cipher_encryption.py delete mode 100644 ascii_encrypting.py diff --git a/algorithms/string/caesars_cipher_encryption.py b/algorithms/string/caesars_cipher_encryption.py new file mode 100644 index 0000000..0aa9f54 --- /dev/null +++ b/algorithms/string/caesars_cipher_encryption.py @@ -0,0 +1,84 @@ +#!/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() diff --git a/ascii_encrypting.py b/ascii_encrypting.py deleted file mode 100644 index 37b3e4b..0000000 --- a/ascii_encrypting.py +++ /dev/null @@ -1,14 +0,0 @@ -string = str(input("Enter Text : ")) - -list_of_ascii = [] -for character in string: - code = ord(character) - list_of_ascii.append(code) - -new_string = "" - -for element in list_of_ascii: - new_string = new_string + " " +str(element) - -print(" ") -print(new_string) From 6eb792f21f8ce4e97b765836e5063c18a71ec4f7 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 01:05:11 +0530 Subject: [PATCH 062/151] Create caesars_cipher_encryption.py --- useful_scripts/caesars_cipher_encryption.py | 84 +++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 useful_scripts/caesars_cipher_encryption.py diff --git a/useful_scripts/caesars_cipher_encryption.py b/useful_scripts/caesars_cipher_encryption.py new file mode 100644 index 0000000..7769b40 --- /dev/null +++ b/useful_scripts/caesars_cipher_encryption.py @@ -0,0 +1,84 @@ +#!/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() From 742dbe9fee592b196e5d31cc1ec458e0afebd146 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 01:05:40 +0530 Subject: [PATCH 063/151] Delete average_calcy.py --- average_calcy.py | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 average_calcy.py diff --git a/average_calcy.py b/average_calcy.py deleted file mode 100644 index 9e4f0c8..0000000 --- a/average_calcy.py +++ /dev/null @@ -1,6 +0,0 @@ -# Simple averaging function -def average(x): - return sum(x) / len(x) - -data = [12, 546, 8, 2, 34, 8, 67, 34, 5, 876, 3456, 76] -print(average(data)) From b57969e2e3097e4515f19b2dc69839df6da54788 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 01:09:00 +0530 Subject: [PATCH 064/151] Update README.md --- math/README.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/math/README.md b/math/README.md index fef474d..b9ff406 100644 --- a/math/README.md +++ b/math/README.md @@ -1,8 +1,10 @@ -
 
-'math' Sub-directory contains all the math related programs
-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
+
+'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 From e879fb3c1cef505c4df56e6fd6be7a42f4227bf8 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 01:09:53 +0530 Subject: [PATCH 065/151] Update README.md --- shell_games/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/shell_games/README.md b/shell_games/README.md index 39cc73b..874ea25 100644 --- a/shell_games/README.md +++ b/shell_games/README.md @@ -3,9 +3,9 @@ '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
+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 + From f76cc3d2d04bf48526561f07afc70839bfa7a3e3 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 01:11:28 +0530 Subject: [PATCH 066/151] Update README.md --- simple_scripts/README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/simple_scripts/README.md b/simple_scripts/README.md index 898d518..62e18b5 100644 --- a/simple_scripts/README.md +++ b/simple_scripts/README.md @@ -2,9 +2,8 @@
 
 'simple_scripts' Sub-directory contains all simplest programs,
 these programs are simple to read/write.
-
-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
 
+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 From 3c2120d212b3f596f99f56dedca8410ca3f9e9dd Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 01:12:33 +0530 Subject: [PATCH 067/151] Update README.md --- algorithms/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/algorithms/README.md b/algorithms/README.md index 583cb45..c1eb52a 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -1,9 +1,9 @@
 'math' Sub-directory contains all algorithms
-further separated in different 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
+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 From 3ce6376596b814c95c565563ecbdede07e2beb7d Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 01:12:56 +0530 Subject: [PATCH 068/151] Update README.md --- algorithms/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/README.md b/algorithms/README.md index c1eb52a..89d8be4 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -1,6 +1,6 @@
-'math' Sub-directory contains all algorithms
+'algorithms' Sub-directory contains all algorithms
 further separated in different particular sub directories
 
The programs have been re-checked and re-mastered by me!
From a764b051a8d821dbc3db0bb30126e2c9f146ead7 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 01:15:15 +0530 Subject: [PATCH 069/151] Create README.md --- algorithms/numbers/README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 algorithms/numbers/README.md diff --git a/algorithms/numbers/README.md b/algorithms/numbers/README.md new file mode 100644 index 0000000..aa8ac92 --- /dev/null +++ b/algorithms/numbers/README.md @@ -0,0 +1,10 @@ + + + + +
+'numbers' Sub-directory contains all 
+numbers/math/sequences(arrays) related algorithms.
+
+Thanks
+
From d485eb0ef1b26229c4d3212e3851a9fbab64c207 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 01:16:11 +0530 Subject: [PATCH 070/151] Create README.md --- algorithms/sorting/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 algorithms/sorting/README.md diff --git a/algorithms/sorting/README.md b/algorithms/sorting/README.md new file mode 100644 index 0000000..4d9fe96 --- /dev/null +++ b/algorithms/sorting/README.md @@ -0,0 +1,9 @@ + + + +
+'sorting' Sub-directory contains all 
+sorting algorithms.
+
+Thanks
+
From 59fe4d3678f63c98e62f324ed3ee69e50266c1a1 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 11:25:42 +0530 Subject: [PATCH 071/151] Useless script --- bubble_sort.py | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 bubble_sort.py diff --git a/bubble_sort.py b/bubble_sort.py deleted file mode 100644 index d83b611..0000000 --- a/bubble_sort.py +++ /dev/null @@ -1,14 +0,0 @@ - -def bubble_sort(array): - """Bubble Sort Elem Swapping algorithm""" - for i in range(len(array)): - for i in range(len(array) - 1): - a = array[i] - b = array[i + 1] - if (b < a): - array[i + 1] = array[i] - array[i] = b - return array - -a = [3,56,32,65,43,2] -print bubble_sort(a) \ No newline at end of file From 198bebc45ef8d7350956d7ee4df077a1595bd311 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 15:37:25 +0530 Subject: [PATCH 072/151] Update and rename area volume and perimeter calcy1.1.py to math/area_volume_calculator.py --- area volume and perimeter calcy1.1.py | 119 ----------------------- math/area_volume_calculator.py | 132 ++++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 119 deletions(-) delete mode 100644 area volume and perimeter calcy1.1.py create mode 100644 math/area_volume_calculator.py diff --git a/area volume and perimeter calcy1.1.py b/area volume and perimeter calcy1.1.py deleted file mode 100644 index 73ba92e..0000000 --- a/area volume and perimeter calcy1.1.py +++ /dev/null @@ -1,119 +0,0 @@ - -def area_of_square(): - woody = int(raw_input("Enter side of the square")) - print("This is the area of square ", woody ** 2) - - -def area_of_rectangle(): - apple = int(raw_input("Enter length of the rectangle")) - i_hate_bill_gates = int(raw_raw_input("Enter width of the rectangle")) - print("This is the area of rectangle ", apple * i_hate_bill_gates) - - -def area_of_circle(): - palo_alto = int(raw_input("Enter radius of the circle")) - print("This is the area of circle", 2 * 22 / 7 * palo_alto) - - -def area_of_cube(): - mountview = int(raw_input("Enter edge of the cube")) - print("This is the area of the cube ", 6 * mountview ** 2) - - -def area_of_cuboid(): - dropbox = int(raw_input("Enter length of cuboid")) - facemash = int(raw_input("Enter width of cuboid")) - facebook = int(raw_input("Enter height of cuboid")) - print("This is the area of cuboid", 2 * ((dropbox * facemash) + (facemash * facebook) + (dropbox * facebook))) - - -def area_of_triangle(): - bloggar = int(raw_input("enter height of the triangle")) - wordpress = int(raw_input("Enter base of the triangle")) - print("This is the area of triangle", (bloggar * wordpress) / 2) - - -def area_of_rhombus(): - my_space = int(raw_input("Enter the first diagonal of rhombus")) - friendster = int(raw_input("Enter the second diagonal of rhombus")) - print("This is the area of rhombus", (my_space * friendster) / 2) - - -def area_of_quadrilateral(): - eclipse = int(raw_input("Enter diagonal of the quadrilateral")) - android_studio = int(raw_input("Enter first height of the quadrilateral")) - jetbrains = int(raw_input("Enter next height of the quadrilateral")) - print("This is the area of quadrilateral", (eclipse * (android_studio + jetbrains)) / 2) - - -# sector 2{perimeters} - - -def peri_of_square(): - twitter = int(raw_input("Enter the side of square")) - print("This is the perimeter of square", 4 * twitter) - - -def peri_of_rectangle(): - oracle = int(raw_input("Enter length of rectangle")) - python = int(raw_input("Enter the width of rectangle")) - print("This is the perimeter of rectangle", 2 * (oracle + python)) - - -def peri_of_rhombus(): - dji_phantom = int(raw_input("Enter side of the rhombus")) - print("This is the perimeter of rhombus", 4 * dji_phantom) - - -def peri_of_triangle(): - youtube = int(raw_input("Enter first side of the triangle")) - vimeo = int(raw_input("Enter second side of the triangle")) - vloggar = int(raw_input("Enter third side of rectangle")) - print("This is the perimeter of triangle", youtube + vimeo + vloggar) - - -def vol_of_cube(): - amd = int(raw_input("Enter side of the cube")) - print("This is the volume of the cube", amd ** 3) - - -def vol_of_cuboid(): - yahoo = int(raw_input("Enter length of cuboid")) - google = int(raw_input("Enter width of cuboid")) - duck_duck_go = int(raw_input("Enter height of cuboid")) - print("This is the volume of the cuboid", yahoo * google * duck_duck_go) - -italy = raw_input("Enter Volume,Area,Perimeter") -brazil = raw_input("Enter rectangle,square,triangle,quadrilateral,cube,cuboid,circle,rhombus") - -if italy == "area" and brazil == "cube": - area_of_cube() -elif italy == "area" and brazil == "cuboid": - area_of_cuboid() -elif italy == "area" and brazil == "triangle": - area_of_triangle() -elif italy == "area" and brazil == "circle": - area_of_circle() -elif italy == "area" and brazil == "rhombus": - area_of_rhombus() -elif italy == "area" and brazil == "quadrilateral": - area_of_quadrilateral() -elif italy == "area" and brazil == "square": - area_of_square() -elif italy == "area" and brazil == "rectangle": - area_of_rectangle() - -elif italy == "perimeter" and brazil == "rectangle": - peri_of_rectangle() -elif italy == "perimeter" and brazil == "square": - peri_of_square() -elif italy == "volume" and brazil == "cube": - vol_of_cube() -elif italy == "volume" and brazil == "cuboid": - vol_of_cuboid() -elif italy == "perimeter" and brazil == "rhombus": - peri_of_rhombus() -elif italy == "perimeter" and brazil == "triangle": - peri_of_triangle() - - diff --git a/math/area_volume_calculator.py b/math/area_volume_calculator.py new file mode 100644 index 0000000..7703fbd --- /dev/null +++ b/math/area_volume_calculator.py @@ -0,0 +1,132 @@ +#!/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() From a46f2477c358b13a9cfee56605504dd53689b88a Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 15:38:16 +0530 Subject: [PATCH 073/151] Delete circle.py --- circle.py | 37 ------------------------------------- 1 file changed, 37 deletions(-) delete mode 100644 circle.py diff --git a/circle.py b/circle.py deleted file mode 100644 index 003788e..0000000 --- a/circle.py +++ /dev/null @@ -1,37 +0,0 @@ -import math -# Basic Circle - -def diameter(radii): # d = 2r r is radius - diaOfCircle = 2 * radii - return('Diameter is : ' + str(diaOfCircle)) - -def circumference(rad): # C = 2pir - peri = 2 * math.pi * rad - return('Circumference is : ' + str(peri)) - -def area(rad): # area = pi r square - area = math.pi * rad ** 2 - return('Area is : ' + str(area)) - -# main -print('Hello\n') -print('Press Enter to exit') -print('=' * 5 + 'Started' + '=' * 5 ) -while True: - user = str(input('Diameter or Circum or Area : ')) - if user == 'Diameter': - radius = float(input('Radius : ')) - print(diameter(radius)) - continue - elif user == 'Circum': - radius = float(input('Radius : ')) - print(circumference(radius)) - continue - elif user == 'Area': - radius = float(input('Radius : ')) - print(area(radius)) - continue - else: - print('\nProgram Ended...') - print('=' * 17) - break From b41fca2db1710ba226c01a94f752c927a788ed7b Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 19:59:15 +0530 Subject: [PATCH 074/151] Update and rename args_addition_example.py to simple_scripts/args_example.py --- args_addition_example.py | 7 ------- simple_scripts/args_example.py | 21 +++++++++++++++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) delete mode 100644 args_addition_example.py create mode 100644 simple_scripts/args_example.py diff --git a/args_addition_example.py b/args_addition_example.py deleted file mode 100644 index 50ce700..0000000 --- a/args_addition_example.py +++ /dev/null @@ -1,7 +0,0 @@ -def addNumbers(*args): - finalValue = 0 - for i in args: - finalValue = finalValue + i - return(finalValue) - -print(addNumbers(123,435,876,12,54,76,78954,89,87,56,78,98,56,32,87)) diff --git a/simple_scripts/args_example.py b/simple_scripts/args_example.py new file mode 100644 index 0000000..00405dc --- /dev/null +++ b/simple_scripts/args_example.py @@ -0,0 +1,21 @@ +#!/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!") + From 23c74f30b7004c3f255938b802e09551089f2f21 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 20:15:36 +0530 Subject: [PATCH 075/151] Update and rename args_example.py to simple_scripts/args_example_1.py --- args_example.py | 7 ------- simple_scripts/args_example_1.py | 23 +++++++++++++++++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) delete mode 100644 args_example.py create mode 100644 simple_scripts/args_example_1.py diff --git a/args_example.py b/args_example.py deleted file mode 100644 index 3392ec7..0000000 --- a/args_example.py +++ /dev/null @@ -1,7 +0,0 @@ -def numbers(*args): - total = 1 - for x in args: - total = total * x - print(total) - -numbers(12, 13, 34, 4576, 234536, 2341) diff --git a/simple_scripts/args_example_1.py b/simple_scripts/args_example_1.py new file mode 100644 index 0000000..3127d0c --- /dev/null +++ b/simple_scripts/args_example_1.py @@ -0,0 +1,23 @@ +#!/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!") From 467b0ff83aef99b36848ae85facebc7cde2349d6 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 20:17:04 +0530 Subject: [PATCH 076/151] See algorithms/analysis to get all above functions --- array_properties.py | 107 -------------------------------------------- 1 file changed, 107 deletions(-) delete mode 100644 array_properties.py diff --git a/array_properties.py b/array_properties.py deleted file mode 100644 index addb7ff..0000000 --- a/array_properties.py +++ /dev/null @@ -1,107 +0,0 @@ - - -class Array(object): - - def __init__(self, array_list): - self.array_list = array_list - self.f_dict = {} - - - def kay_sort(self): - for i in range(len(self.array_list)): - - for n in range(len(self.array_list) - 1): - a = self.array_list[n] - - if (a > self.array_list[i]): - temp = self.array_list[i] - self.array_list[i] = a - self.array_list[n] = temp - - self.f_dict["Sorted List : "] = self.array_list - - - def difference_in_sequence(self): - insta = [] - for i in range(len(self.array_list) - 1): - a = self.array_list[i] - b = self.array_list[i + 1] - insta.append(abs(a - b)) - - self.f_dict["Sequence Difference : "] = insta - - def list_length(self): - res = 0 - for i in range(len(self.array_list)): - res += 1 - self.f_dict["Length : "] = res - - def maximum_n(self): - max_num = 0 - for i in range(len(self.array_list)): - prep = self.array_list[i] - - for i in self.array_list: - if (prep > i): - max_num = prep - - else: pass; - - self.f_dict["Maximum number : "] = max_num - - def minimum_n(self): - min_num = 0 - for j in range(len(self.array_list)): - inst = self.array_list[j] - - for n in self.array_list: - if (inst < n): - min_num = inst - - else: pass; - - self.f_dict["Minimum number : "] = min_num - - def mean_of_arr(self): - length = len(self.array_list) - summed = sum(self.array_list) - mean = float(summed / length) - - self.f_dict["Mean of Array : "] = mean - - def median_of_arr(self): - help_here = len(self.array_list) - - if (len(self.array_list) % 2 != 0): - med = self.array_list[(help_here + 1) / 2] - self.f_dict["Median of Array : "] = med - - else : - val_x = help_here / 2 - val_y = (help_here + 2) / 2 - median_x_y = (self.array_list[val_x] + self.array_list[self.val_y]) / 2 - self.f_dict["Median of Array : "] = median_x_y - - def mode_of_array(self): - mode_dict = {} - - for i in self.array_list: - mode_dict[i] = self.array_list.count(i) - - self.f_dict["Mode : "] = mode_dict - - def show_props(self): - for i in self.f_dict.keys(): - print("{}{}".format(i , str(self.f_dict[i]))) - -to_test = [12, 12, 54, 234, 76,3, 34, 4 ,56, 23, 12] -instance = Array(to_test) -instance.kay_sort() -instance.difference_in_sequence() -instance.list_length() -instance.maximum_n() -instance.minimum_n() -instance.mean_of_arr() -instance.median_of_arr() -instance.mode_of_array() -print(instance.show_props()) \ No newline at end of file From 1d1762182c629ed39bb30a2c7ea2f4d51561c677 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 27 Jan 2018 21:17:34 +0530 Subject: [PATCH 077/151] Create mode.py Find mode of un-grouped data(plain array) --- algorithms/analysis/mode.py | 63 +++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 algorithms/analysis/mode.py diff --git a/algorithms/analysis/mode.py b/algorithms/analysis/mode.py new file mode 100644 index 0000000..46bae88 --- /dev/null +++ b/algorithms/analysis/mode.py @@ -0,0 +1,63 @@ +#!/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 From 72cd00e9b0dd29c67f8dd4c3d778a6ea185cb247 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 01:21:30 +0530 Subject: [PATCH 078/151] Update and rename binary_search.py to algorithms/searching/binary_search.py --- algorithms/searching/binary_search.py | 75 +++++++++++++++++++++++++++ binary_search.py | 14 ----- 2 files changed, 75 insertions(+), 14 deletions(-) create mode 100644 algorithms/searching/binary_search.py delete mode 100644 binary_search.py diff --git a/algorithms/searching/binary_search.py b/algorithms/searching/binary_search.py new file mode 100644 index 0000000..7adcbf2 --- /dev/null +++ b/algorithms/searching/binary_search.py @@ -0,0 +1,75 @@ +#!/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): + if not sorted_ar: + arr.sort() + + 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 diff --git a/binary_search.py b/binary_search.py deleted file mode 100644 index 03270a1..0000000 --- a/binary_search.py +++ /dev/null @@ -1,14 +0,0 @@ -# Binary Search for an array seq, search element is v, from positions l to r - - -def binary_search(seq,v,l,r): - #search for v in seq[l:r], seq is sorted - if r - l == 0: - return(False) - mid = (l + r) // 2 #integer division - if v == seq[mid]: - return (True) - if v < seq[mid]: - return (binary_search(seq,v,l,mid)) - else: - return (binary_search(seq,v,mid+1,r)) From e40dd13fd1b51aa4f91183c10d594c7e6de8850e Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 01:23:57 +0530 Subject: [PATCH 079/151] Add comments at line 23, 24 and 28 --- algorithms/searching/binary_search.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/algorithms/searching/binary_search.py b/algorithms/searching/binary_search.py index 7adcbf2..cd728a2 100644 --- a/algorithms/searching/binary_search.py +++ b/algorithms/searching/binary_search.py @@ -20,9 +20,12 @@ # 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 From 2ce77c3c811e01ddf8a75fee035254e4f7bc2d12 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 01:24:38 +0530 Subject: [PATCH 080/151] Fairly useless --- binary_search_algorithm.py | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 binary_search_algorithm.py diff --git a/binary_search_algorithm.py b/binary_search_algorithm.py deleted file mode 100644 index 940ab4e..0000000 --- a/binary_search_algorithm.py +++ /dev/null @@ -1,22 +0,0 @@ - - -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 - -nums = [0,23,54,5,32,78] -print binary_search(nums, 32) -print binary_search(nums, 5) From 790d8b78d31c3fdfa55590baec6cb10c0a0b1c6d Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 14:19:22 +0530 Subject: [PATCH 081/151] Update and rename binary_to_decimal_converter.py to algorithms/numbers/binary_to_decimal_converter.py --- .../numbers/binary_to_decimal_converter.py | 32 +++++++++++++++++++ binary_to_decimal_converter.py | 27 ---------------- 2 files changed, 32 insertions(+), 27 deletions(-) create mode 100644 algorithms/numbers/binary_to_decimal_converter.py delete mode 100644 binary_to_decimal_converter.py diff --git a/algorithms/numbers/binary_to_decimal_converter.py b/algorithms/numbers/binary_to_decimal_converter.py new file mode 100644 index 0000000..ecd86fe --- /dev/null +++ b/algorithms/numbers/binary_to_decimal_converter.py @@ -0,0 +1,32 @@ +#!/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 diff --git a/binary_to_decimal_converter.py b/binary_to_decimal_converter.py deleted file mode 100644 index 6c3d08b..0000000 --- a/binary_to_decimal_converter.py +++ /dev/null @@ -1,27 +0,0 @@ - -# Pseudo: -# loop through the list of zeros and ones -# if current value is zero pass -# else result += current value ** index of value -# return the result - -def binary_to_decimal(X): - res = 0 - list_binary = list(X) - try: - for i in range(len(list_binary)): - if not(list_binary[i] == "0"): - res += 2 ** i - else: - pass - except TypeError: - return "Expected a string containing binary number!" - except ValueError: - return "Invalid input or value!" - else: - return res - -# Test -case = "11111111" * 4; -res = binary_to_decimal(case); -print("Input(binary): {}\nValue(decimal): {}".format(case, res)) # 32-bit value! From a877b85d40f4ded51415d6b9591f0dbbc38e6b2a Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 14:20:24 +0530 Subject: [PATCH 082/151] Create binary_to_decimal_conversion.py --- .../binary_to_decimal_conversion.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 useful_scripts/binary_to_decimal_conversion.py diff --git a/useful_scripts/binary_to_decimal_conversion.py b/useful_scripts/binary_to_decimal_conversion.py new file mode 100644 index 0000000..730f474 --- /dev/null +++ b/useful_scripts/binary_to_decimal_conversion.py @@ -0,0 +1,27 @@ +#!/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 From bce836b2dcd58dfea27fb870ae2b6919670478ae Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 14:24:28 +0530 Subject: [PATCH 083/151] Update and rename caesars_cipher.py to caesars_cipher_encryption.py --- caesars_cipher.py | 40 ----------------- caesars_cipher_encryption.py | 84 ++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 40 deletions(-) delete mode 100644 caesars_cipher.py create mode 100644 caesars_cipher_encryption.py diff --git a/caesars_cipher.py b/caesars_cipher.py deleted file mode 100644 index d5b4f9f..0000000 --- a/caesars_cipher.py +++ /dev/null @@ -1,40 +0,0 @@ -import string - -def concat_elements(n): - res = "" - for i in n: - res += i - return res - -def encrypt(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 message!" - - 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 n_encrypt(ciph, key, times): - # You can modify this to take multiple keys - i = 0 - ciph = "" - while i < times: - ciph = encrypt(ciph, key) - i += 1 - return ciph - - -# Test -mesage = "This is top secret!" -result = encrypt(mesage, 9) -print("Encrypted Text: " + result) diff --git a/caesars_cipher_encryption.py b/caesars_cipher_encryption.py new file mode 100644 index 0000000..740537f --- /dev/null +++ b/caesars_cipher_encryption.py @@ -0,0 +1,84 @@ +#!/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() From 6739e72c6df206a850d11680aa9493e081ac7e93 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 14:26:28 +0530 Subject: [PATCH 084/151] Delete caesars_cipher_encryption.py --- caesars_cipher_encryption.py | 84 ------------------------------------ 1 file changed, 84 deletions(-) delete mode 100644 caesars_cipher_encryption.py diff --git a/caesars_cipher_encryption.py b/caesars_cipher_encryption.py deleted file mode 100644 index 740537f..0000000 --- a/caesars_cipher_encryption.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/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() From 75ef3c48f9206b5b6d3f9eb821572933ca341483 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 15:02:01 +0530 Subject: [PATCH 085/151] Update and rename bmi_calc.py to useful_scripts/bmi_body_mass_index_calculator.py --- bmi_calc.py | 19 ----------- .../bmi_body_mass_index_calculator.py | 32 +++++++++++++++++++ 2 files changed, 32 insertions(+), 19 deletions(-) delete mode 100644 bmi_calc.py create mode 100644 useful_scripts/bmi_body_mass_index_calculator.py diff --git a/bmi_calc.py b/bmi_calc.py deleted file mode 100644 index 52569b9..0000000 --- a/bmi_calc.py +++ /dev/null @@ -1,19 +0,0 @@ -# BMI calculator -# BMI = weight(kg) / height ** 2(m) standard metrics - -def body_mass_index(weight, height): - return round((weight) / ((height * 0.01) ** 2), 2) - -while True: - startOrEnd = str(input('Count or End : ')).strip() - if startOrEnd.lower() == 'count': - index = body_mass_index(float(input('Weight in Kg : ')), float(input('Height in Centimetre : '))) - print('\nHealthy BMI ranges between 19 to 25:') - if 18 < index < 26 : - print('Your BMI is ' + str(index) + '\nYou are HEALTHY\n') - else : - print('Your BMI is ' + str(index) + '\nYour BodyMassIndex isn\'t between Healthy range\n') - continue - else : - quit() - diff --git a/useful_scripts/bmi_body_mass_index_calculator.py b/useful_scripts/bmi_body_mass_index_calculator.py new file mode 100644 index 0000000..e185066 --- /dev/null +++ b/useful_scripts/bmi_body_mass_index_calculator.py @@ -0,0 +1,32 @@ +#!/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() From ac3ae2842b04e1edde78f5e42a8a8addd1367a69 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 15:02:51 +0530 Subject: [PATCH 086/151] Update password_generator.py --- useful_scripts/password_generator.py | 1 + 1 file changed, 1 insertion(+) diff --git a/useful_scripts/password_generator.py b/useful_scripts/password_generator.py index 34d3188..c9333a4 100644 --- a/useful_scripts/password_generator.py +++ b/useful_scripts/password_generator.py @@ -1,6 +1,7 @@ #!/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 From 8666c3fe0445a81b46c20dd3b67dd7c4887219bb Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 15:03:50 +0530 Subject: [PATCH 087/151] Library discontinued in Python 3.x versions --- bsddb_test.py | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 bsddb_test.py diff --git a/bsddb_test.py b/bsddb_test.py deleted file mode 100644 index 377506c..0000000 --- a/bsddb_test.py +++ /dev/null @@ -1,12 +0,0 @@ -import bsddb -import os - -def new_db(name = "my_db"): - os.chdir("D:\\") - db = bsddb.btopen(name + ".db" , "c") - db["Default"] = "Erika" - return db["Default"] - db.close() - -get_db_name = str(raw_input("db name : ")) -print new_db(get_db_name) From 8d5b9e3afb054b7c79e837d226a9d8cc3448040b Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 15:33:20 +0530 Subject: [PATCH 088/151] Update and rename calculator.py to useful_scripts/calculator.py Made really important changes --- calculator.py | 42 ------------------------------------ useful_scripts/calculator.py | 36 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 42 deletions(-) delete mode 100644 calculator.py create mode 100644 useful_scripts/calculator.py diff --git a/calculator.py b/calculator.py deleted file mode 100644 index 3fc7162..0000000 --- a/calculator.py +++ /dev/null @@ -1,42 +0,0 @@ -def addition(): - return float(raw_input("Number: ")) + float(raw_input("Next number: ")) - -def subtraction(): - return float(raw_input("Number: ")) - float(raw_input("Next number: ")) - -def multiplication(): - return float(raw_input("Number: ") * raw_input("Next number: ")) - -def division(): - return float(raw_input("Number: ")) / float(raw_input("Next number: ")) - -def modulo(): - return float(raw_input("Number: ")) % float(raw_input("Next number: ")) - -def exp_calcy(): - try: - return eval(raw_input("Expression: ")) - except Exception as e: - return e - -def calcy(a, b, c, d, e): - dispatch = {"add":a, "subtract":b, "multiplication":c, "division":d, "modulo":e} - try: - return dispatch[raw_input("Operation: ")]() - except Exception as e: - return e - -print("Hello,") -while(True): - start_or_end = raw_input("start or end: ") - if start_or_end.strip().lower() == "start": - which_calc = raw_input("calcy or exp_calcy(Exp = Expression): ") - if which_calc.strip().lower() == "calcy": - print(calcy(addition, subtraction, multiplication, division, modulo)) - elif which_calc.strip().lower() == "exp_calcy": - print(exp_calcy()) - else: - print("Invalid Input. Try again.\n") - continue - else: - break diff --git a/useful_scripts/calculator.py b/useful_scripts/calculator.py new file mode 100644 index 0000000..0569be9 --- /dev/null +++ b/useful_scripts/calculator.py @@ -0,0 +1,36 @@ +#!/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() From 51f97f5255bc15ae59716774048eff900cdf48f4 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 23:33:07 +0530 Subject: [PATCH 089/151] Create calculator.py --- math/calculator.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 math/calculator.py diff --git a/math/calculator.py b/math/calculator.py new file mode 100644 index 0000000..45d0e3c --- /dev/null +++ b/math/calculator.py @@ -0,0 +1,36 @@ +#!/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() From 3671b1dbd9064bcae9dd51562fee5d47b76985a7 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 23:49:08 +0530 Subject: [PATCH 090/151] Update and rename characterFinder.py to algorithms/string/vowel_count.py --- algorithms/string/vowel_count.py | 34 ++++++++++++++++++++++++++++++++ characterFinder.py | 14 ------------- 2 files changed, 34 insertions(+), 14 deletions(-) create mode 100644 algorithms/string/vowel_count.py delete mode 100644 characterFinder.py diff --git a/algorithms/string/vowel_count.py b/algorithms/string/vowel_count.py new file mode 100644 index 0000000..08ffa42 --- /dev/null +++ b/algorithms/string/vowel_count.py @@ -0,0 +1,34 @@ +#!/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() diff --git a/characterFinder.py b/characterFinder.py deleted file mode 100644 index e21d514..0000000 --- a/characterFinder.py +++ /dev/null @@ -1,14 +0,0 @@ -# Number of Character in String Counter - -def countVowels(unknownC,unknownT): - count = 0 - for x in unknownT : - if x == unknownC: - count = count + 1 - print('Number of Characters are : ' + str(count)) - -getText = str(input('Text : ')) -print(' ') -getChar = str(input('Which Char To Find : ')) -print(' ') -print(countVowels(getChar,getText)) From c0dab7f3c3a3844487c0bed72b7ea71360de3c8a Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 23:50:31 +0530 Subject: [PATCH 091/151] Extremely useless --- class example.py | 102 ----------------------------------------------- 1 file changed, 102 deletions(-) delete mode 100644 class example.py diff --git a/class example.py b/class example.py deleted file mode 100644 index 877cd8d..0000000 --- a/class example.py +++ /dev/null @@ -1,102 +0,0 @@ -class human: # object human to declare a person - def __init__(self,gender,name,age,skills,password): - self.gender = gender #gender attribute of object human - self.name = name #name attribute of object human - self.age = age #age attribute of obj. human - self.skills = skills # skills attribute of obj. - self.password = password # password attribute of obj. human(necessary for logIn function) - def sayHello(self) : # function to say hello to obj. human - print("Hello",self.name," Welcome to tunestore.com") - def profile(self) : # function to view profile of obj. human - print("--------------------------------------------------------") - print("Profile") - print("--------------------------------------------------------") - print("User : ",self.name) # to show attribute name - print("Gender : ",self.gender) # to show attribute gender - print("Age : ",self.age) # to show attribute age - print("Likes : ",self.skills) # to show attribute skills - print("--------------------------------------------------------") - -#user interacion section -# following variable will set username -get_name = str(input("Username : ")) -# following variable will set password -get_password = str(input("password : ")) -# following variable will set gender -get_gender = str(input("Gender : ")) -# following variable will set age -get_age = int(input("Age : ")) -# following variable will set likes -get_skill = str(input("Likes : ")) - -print(" ") - -# setting attributes to variables -kalpak = human(get_gender, get_name, get_age, get_skill,get_password) - -# printing functions from class -print(kalpak.sayHello()) # say hello function -print(" ") -print(kalpak.profile()) # view profile function - -# this a log in function -# this function authorises user to data -def logIn(): - while True : # loop is for try again - print("Log In :") - getUsername = str(input("username : ")) - getPassword = str(input("password : ")) - if (getUsername == kalpak.name) and (getPassword == kalpak.password) : - print("Log in successful") - print(kalpak.profile()) - break # break will break loop and print next function if username or password is wrong - else : - print("Invalid username or password") - print("Try again...") - print("--------------------------------------------------------") - continue # continue is to try logging in again if user name or password is wrong -print(logIn()) # calling function -# telling user that he is authorised to access the passwords -print("Access granted") -print("Now you have complete access to the data") - -# the data the user has to access in a form of dictionary called passwords -passwords = {"facebook" : "charlieat" , - "ubuntu" : "charlieAT12345" , - "windows" : "qwertyqwerty" , - "gmail" : "charlieat" , - "outlook" : "charlieat12345" } - -while True : # a loop - # asking user what to access - userAccess = str(input("site of password : ")) - - # checking what user asked in conditionals - if (userAccess.strip() == "facebook") : - print(passwords["facebook"]) - break # allowing user for one time access - - # probablity of input - elif (userAccess.strip() == "ubuntu") : - print(passwords["ubuntu"]) - break # allowing user for one time access - - # another probablity of input - elif (userAccess.strip() == "windows") : - print(passwords["windows"]) - break # allowing user for one time access - - # another probablity of input - elif (userAccess.strip() == "gmail") : - print(passwords["gmail"]) - break # allowing user for one time access - - # another probablity of input - elif (userAccess.strip() == "outlook") : - print(passwords["outlook"]) - break # allowing user for one time access - - # probablity of input if input was wrong - else : - print("The data you are trying to access is not in the database.") - continue # allowing user to try finding data again if input was wrong From 52120ac9beeece9dc016468c3531d72d09c39932 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 23:53:14 +0530 Subject: [PATCH 092/151] Rename class_animal.py to simple_scripts/class_animal_attributes_examples.py --- .../class_animal_attributes_examples.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename class_animal.py => simple_scripts/class_animal_attributes_examples.py (100%) diff --git a/class_animal.py b/simple_scripts/class_animal_attributes_examples.py similarity index 100% rename from class_animal.py rename to simple_scripts/class_animal_attributes_examples.py From a621ce2456edbc297718410faf32ba4f0d86f8f0 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 23:54:03 +0530 Subject: [PATCH 093/151] Really useless --- class_calculator.py | 99 --------------------------------------------- 1 file changed, 99 deletions(-) delete mode 100644 class_calculator.py diff --git a/class_calculator.py b/class_calculator.py deleted file mode 100644 index 77c7c53..0000000 --- a/class_calculator.py +++ /dev/null @@ -1,99 +0,0 @@ - - -class Calculator: - def __init__(self, num1, num2): - self.num1 = num1 - self.num2 = num2 - - def add(self): - added = self.num1 + self.num2 - return(added) - - def subtract(self): - subtracted = self.num1 - self.num2 - return(subtracted) - - def multiply(self): - multiplied = self.num1 * self.num2 - return(multiplied) - - def divide(self): - divided = self.num1 / self.num2 - return(divided) - - def modulo(self): - mod = self.num1 % self.num2 - return(mod) - - def exponent(self): - power = self.num1 ** self.num2 - return(power) - -class Expression: - def __init__(self, expression): - self.expression = expression - - def evaluate_expression(self): - evaluated = eval(self.expression) - return(evaluated) - -while(True): - start_or_end = str(input("Start or End : ")) - if start_or_end.strip() == "Start": - - calc_or_exp = str(input("Calc or Expression Calc : ")) - if calc_or_exp in ["Calc", "calc"]: - - get_op = str(input("Add or Subtract or Multiply or Divide or Exponent or Modulo : ")) - - if get_op == "Add": - num = float(input("Number : ")) - next_num = float(input("Next Number : ")) - add = Calculator(num, next_num) - print(add.add()) - - elif get_op == "Subtract": - num = float(input("Number : ")) - next_num = float(input("Next Number : ")) - subtract = Calculator(num, next_num) - print(subtract.subtract()) - - elif get_op == "Multiply": - num = float(input("Number : ")) - next_num = float(input("Next Number : ")) - multiply = Calculator(num, next_num) - print(multiply.multiply()) - - elif get_op == "Divide": - num = float(input("Number : ")) - next_num = float(input("Next Number : ")) - divide = Calculator(num, next_num) - print(divide.divide()) - - elif get_op == "Exponent": - num = float(input("Number : ")) - next_num = float(input("Next Number : ")) - exponent = Calculator(num, next_num) - print(exponent.exponent()) - - elif get_op == "Modulo": - num = float(input("Number : ")) - next_num = float(input("Next Number : ")) - modulo = Calculator(num, next_num) - print(modulo.modulo()) - - else: - print("Invalid Input.Try again!") - - elif calc_or_exp in ["Expression calc", "expression calc","expression"]: - get_expression = str(input("Expression : ")) - expressed = Expression(get_expression) - print(expressed.evaluate_expression()) - - else: - print("Invalid Input.Try again!") - - continue - - else: - break \ No newline at end of file From 712842d4ce95c66754acfef18a550abfb81b5c59 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 28 Jan 2018 23:58:00 +0530 Subject: [PATCH 094/151] Rename class_example_movies.py to simple_scripts/class_example_movies.py --- class_example_movies.py => simple_scripts/class_example_movies.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename class_example_movies.py => simple_scripts/class_example_movies.py (100%) diff --git a/class_example_movies.py b/simple_scripts/class_example_movies.py similarity index 100% rename from class_example_movies.py rename to simple_scripts/class_example_movies.py From 32482996a6cdd45d87f4a47e0700760d4b127ef4 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 29 Jan 2018 14:36:30 +0530 Subject: [PATCH 095/151] Update and rename class_movies.py to simple_scripts/class_movies.py --- class_movies.py | 86 ---------------------------------- simple_scripts/class_movies.py | 23 +++++++++ 2 files changed, 23 insertions(+), 86 deletions(-) delete mode 100644 class_movies.py create mode 100644 simple_scripts/class_movies.py diff --git a/class_movies.py b/class_movies.py deleted file mode 100644 index 076897f..0000000 --- a/class_movies.py +++ /dev/null @@ -1,86 +0,0 @@ - - -class movie: - - def __init__ ( self, title, director, rating, budget, box_office, cast, description ): - self.title = title - self.director = director - self.rating = rating - self.budget = budget - self.box_office = box_office - self.cast = cast - self.description = description - - def view_all( self ): - print( "Title : {}".format( self.title ) ) - print( "Director : {}".format( self.director ) ) - print( "Rating : {}".format( self.rating ) ) - print( "Budget : {} million USD".format( self.budget ) ) - print( "Box office : {} million USD".format( self.box_office ) ) - print( "Cast : {}".format( self.cast ) ) - print( "Description : {}".format( self.description ) ) - print(" ") - - def comment_movie( self ): - - if self.rating >= 4: - return( "It is a must watch movie.\n" ) - - elif 4 > self.rating > 2: - return( "It is a good movie.\n" ) - - else: - return( "It is a poor movie.\n" ) - -movies = {} - -def add(): - get_title = str(input( "Title of movie : " )) - get_director = str(input( "Director of movie : " )) - get_rating = float(input( "Rating of movie : " )) - get_budget = float(input( "Budget of the movie : " )) - get_box_office = float(input( "Box office earnings of the movie : " )) - get_cast = str(input( "Cast of the movie : " )) - get_description = str(input( "Description of the movie : " )) - - movies[get_title] = movie( get_title, get_director, get_rating, get_budget, get_box_office, get_cast, get_description ) - -def view_movie(): - which_movie = str(input( "Movie : " )) - if which_movie not in movies: - return( "Movie Not in list!" ) - else: - print( movies[which_movie].view_all() ) - print( movies[which_movie].comment_movie() ) - -print("Hello,") -while ( True ): - print(" ") - start_or_end = str(input( "Start or End : " )) - if ( start_or_end.strip() == "Start" ): - - op = str(input( "Add or View : " )) - - if op.strip() == "Add": - print(" ") - print( add() ) - - elif op.strip() == "View": - print(" ") - print( view_movie() ) - - else: - print(" ") - print( "Invalid Input Try again!" ) - continue - - continue - - elif ( start_or_end == "End" ): - break - - else: - print( "Invalid Input.Try Again!" ) - continue - - diff --git a/simple_scripts/class_movies.py b/simple_scripts/class_movies.py new file mode 100644 index 0000000..d052c4e --- /dev/null +++ b/simple_scripts/class_movies.py @@ -0,0 +1,23 @@ +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()) From 51ff9ee0ba48757f80749048d4b3da2b96ad3c5f Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 29 Jan 2018 15:28:37 +0530 Subject: [PATCH 096/151] Little better solution than previous one --- algorithms/numbers/collatz_sequence.py | 41 ++++++++++++++++++++++++++ collatz_sequence.py | 31 ------------------- 2 files changed, 41 insertions(+), 31 deletions(-) create mode 100644 algorithms/numbers/collatz_sequence.py delete mode 100644 collatz_sequence.py diff --git a/algorithms/numbers/collatz_sequence.py b/algorithms/numbers/collatz_sequence.py new file mode 100644 index 0000000..47dd5b5 --- /dev/null +++ b/algorithms/numbers/collatz_sequence.py @@ -0,0 +1,41 @@ +#!/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) + diff --git a/collatz_sequence.py b/collatz_sequence.py deleted file mode 100644 index f3c64c7..0000000 --- a/collatz_sequence.py +++ /dev/null @@ -1,31 +0,0 @@ -#IN collatz sequence you perform few mathematical operation depending on whether a number is even or odd , no matter what the integer is eventually you will get 1. - -#operation performed is the number is even = number // 2 and if the number is odd = number * 3 + 1 - -#example if the number is 5 , out put is 5 16 8 4 2 1 -from sys import exit # really no need to do that but as a precaution is good - -def collatz(num): # defining the function - if (num % 2 == 0): - res = num //2 - - elif (num % 2 != 0): - res = num * 3 + 1 - - else: - return 'Enter a valid integer' - - while True: - if (res == 1): #we need to exit the function after 1 is obtained - print(res) - exit(0) - elif (res != 1): - print(res) - collatz(res) #the function should be executing until 1 is obtained - -try: - num = int(input('Enter an integer: ')) #asking for input and then calling the function also change input to raw_input in python 2x versions -except Exception as e: - print("Try again...") -print("\nReaching one here....") -collatz(num) From 7336bd44d5e0318269f5c4c8005785451c13f3a6 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 29 Jan 2018 15:49:47 +0530 Subject: [PATCH 097/151] Update and rename compare_two.py to algorithms/numbers/compare_array_elements.py --- algorithms/numbers/compare_array_elements.py | 39 ++++++++++++++++++++ compare_two.py | 16 -------- 2 files changed, 39 insertions(+), 16 deletions(-) create mode 100644 algorithms/numbers/compare_array_elements.py delete mode 100644 compare_two.py diff --git a/algorithms/numbers/compare_array_elements.py b/algorithms/numbers/compare_array_elements.py new file mode 100644 index 0000000..74b8dc9 --- /dev/null +++ b/algorithms/numbers/compare_array_elements.py @@ -0,0 +1,39 @@ +#!/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] + ] +] + +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)) diff --git a/compare_two.py b/compare_two.py deleted file mode 100644 index e391564..0000000 --- a/compare_two.py +++ /dev/null @@ -1,16 +0,0 @@ - - -def compare_two(m,n): - final = [] - for i in range(len(m)): - if (m[i] > n[i]): - final.append(m[i]) - else: - final.append(n[i]) - return final - -a = [12, 24, 36] -b = [3, 554, 676] - -print compare_two(a, b) - From 6c11b69c5e363edab3551c71dd80a4cc450cdab5 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 29 Jan 2018 15:50:48 +0530 Subject: [PATCH 098/151] Add comment at line 37 --- algorithms/numbers/compare_array_elements.py | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms/numbers/compare_array_elements.py b/algorithms/numbers/compare_array_elements.py index 74b8dc9..666a381 100644 --- a/algorithms/numbers/compare_array_elements.py +++ b/algorithms/numbers/compare_array_elements.py @@ -34,6 +34,7 @@ def compare_array_elements(arr1, arr2): ] ] +# 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)) From 5bf451024e3cc226ad2e6f530a332ce3611727a1 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 29 Jan 2018 15:52:43 +0530 Subject: [PATCH 099/151] see algorithms/numbers --- comparison.py | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 comparison.py diff --git a/comparison.py b/comparison.py deleted file mode 100644 index 92791f6..0000000 --- a/comparison.py +++ /dev/null @@ -1,17 +0,0 @@ -# Comparison is necessary - -a = [1,2,4,5,6] # you can add more elements or delete but both lists or -b = [3,8,1,0,9] # how many lists you want should contain same number of elements -c = [] - -for x in range(len(a)): - e = a[x] - p = b[x] - if e > p: - c.append(e) - else : - c.append(p) - -print(c) - -# If you know about my Sorting algorithms add this to that program if you want \ No newline at end of file From 1197dd9ca16a29ee91fdb320ad238906c69489ee Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 29 Jan 2018 15:58:03 +0530 Subject: [PATCH 100/151] Seriously useless --- pi calculator.py | 26 -------------------------- 1 file changed, 26 deletions(-) delete mode 100644 pi calculator.py diff --git a/pi calculator.py b/pi calculator.py deleted file mode 100644 index 199b76e..0000000 --- a/pi calculator.py +++ /dev/null @@ -1,26 +0,0 @@ -from math import * -#pi for calculations -def pie(): - get_from_user = int(input("Enter number:")) - get_from_use = int(input("Enter next number:")) - get_users_view = input("Enter operator like + - / * :")) - if get_from_user == "pi" and get_users_view == "+": - print(get_from_user+get_from_use) - elif get_from_use == "pi" and get_users_view == "+": - print(get_from_user+get_from_use) - - if get_from_user == "pi" and get_users_view == "-": - print(get_from_user-get_from_use) - elif get_from_use == "pi" and get_users_view == "-": - print(get_from_user-get_from_use) - - if get_from_user == "pi" and get_users_view == "*": - print(get_from_user*get_from_use) - elif get_from_use == "pi" and get_users_view == "*": - print(get_from_user*get_from_use) - - if get_from_user == "pi" and get_users_view == "/": - print(get_from_user/get_from_use) - elif get_from_use == "pi" and get_users_view == "/": - print(get_from_user/get_from_use) - From 91e414c98800ebd6c56e22fa9b1515fddd3411ec Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 29 Jan 2018 15:58:34 +0530 Subject: [PATCH 101/151] see algorithms/numbers --- factorial_recursion.py | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 factorial_recursion.py diff --git a/factorial_recursion.py b/factorial_recursion.py deleted file mode 100644 index e93d350..0000000 --- a/factorial_recursion.py +++ /dev/null @@ -1,10 +0,0 @@ -def factorial(n): - - if (n <= 1): - return 1 - - else: - res = n * factorial(n - 1) - return res - -print(factorial(input("Number PLease : "))) From a05cf21a5ceb83d18083936d4ba0353e10d63e18 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 29 Jan 2018 16:06:33 +0530 Subject: [PATCH 102/151] Update and rename personality_teller.py to simple_scripts/personality_teller.py --- .../personality_teller.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) rename personality_teller.py => simple_scripts/personality_teller.py (51%) diff --git a/personality_teller.py b/simple_scripts/personality_teller.py similarity index 51% rename from personality_teller.py rename to simple_scripts/personality_teller.py index 6561d2c..b3c8a03 100644 --- a/personality_teller.py +++ b/simple_scripts/personality_teller.py @@ -1,13 +1,21 @@ +#!/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'] -def teller(): - input('Tell Your Name : ') - return('According to your name You are ' + random.choice(personalities) + '.') - -print(teller()) +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)) From c0f60bfecb13c3e66b2666e1d2ebdacb2082ef4d Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 29 Jan 2018 16:10:13 +0530 Subject: [PATCH 103/151] Update and rename conditionals_examples.py to simple_scripts/conditionals_examples.py --- .../conditionals_examples.py | 3 +++ 1 file changed, 3 insertions(+) rename conditionals_examples.py => simple_scripts/conditionals_examples.py (94%) diff --git a/conditionals_examples.py b/simple_scripts/conditionals_examples.py similarity index 94% rename from conditionals_examples.py rename to simple_scripts/conditionals_examples.py index b622054..8bbe2fa 100644 --- a/conditionals_examples.py +++ b/simple_scripts/conditionals_examples.py @@ -1,3 +1,6 @@ +# THIS SCRIPT IS TO UNDERSTAND +# THAN TO EXECUTE! + # Conditionals Examples # if , elif , else From 76131aeeac278f67f2d5b062c62c8f6bf41e8d51 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 18 Feb 2018 15:36:22 +0530 Subject: [PATCH 104/151] Update and rename timer.py to useful_scripts/timer.py --- timer.py | 23 ----------------------- useful_scripts/timer.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 23 deletions(-) delete mode 100644 timer.py create mode 100644 useful_scripts/timer.py diff --git a/timer.py b/timer.py deleted file mode 100644 index cc78649..0000000 --- a/timer.py +++ /dev/null @@ -1,23 +0,0 @@ -# Timer in python (Console Application) -import time -import webbrowser - -def timer(minutes): - a = 0 - while a != minutes: - time.sleep(59) - a = a + 1 - print("<<<<<>>>>>") - # I have not used return cause it termites the function - webbrowser.open_new("https://www.youtube.com/watch?v=SlZMVAydqaE") - - -print("Hello,") -while True: - start_or_end = str(input("Start or End : ")) - if start_or_end.strip() == "Start": - get_minutes = int(input("Minutes : ")) - print(timer(get_minutes)) - continue - else: - break diff --git a/useful_scripts/timer.py b/useful_scripts/timer.py new file mode 100644 index 0000000..652fbcf --- /dev/null +++ b/useful_scripts/timer.py @@ -0,0 +1,28 @@ +#!/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) From a59cbd3490c066915e662ca20438be01d8810f14 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sat, 10 Mar 2018 21:53:53 +0530 Subject: [PATCH 105/151] palindrome string check in just 2 lines --- algorithms/string/is_palindrome_two_liner.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 algorithms/string/is_palindrome_two_liner.py diff --git a/algorithms/string/is_palindrome_two_liner.py b/algorithms/string/is_palindrome_two_liner.py new file mode 100644 index 0000000..095dcaf --- /dev/null +++ b/algorithms/string/is_palindrome_two_liner.py @@ -0,0 +1,19 @@ + + +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") From 41abcef010f463dcd1cb0704996644ad2c169ad5 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 11 Mar 2018 00:02:50 +0530 Subject: [PATCH 106/151] Update and rename battleship.py to shell_games/battleship.py Made drastic changes! --- battleship.py | 48 ------------------ shell_games/battleship.py | 100 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 48 deletions(-) delete mode 100644 battleship.py create mode 100644 shell_games/battleship.py diff --git a/battleship.py b/battleship.py deleted file mode 100644 index 98ee206..0000000 --- a/battleship.py +++ /dev/null @@ -1,48 +0,0 @@ -from random import randint - -""" -This Program is one from codecademy python battleship -section i just completed -""" - -board = [] - -for x in range(5): - board.append(["O"] * 5) - -def print_board(board): - for row in board: - print " ".join(row) - -print "Let's play Battleship!" -print_board(board) - -def random_row(board): - return randint(0, len(board) - 1) - -def random_col(board): - return randint(0, len(board[0]) - 1) - -ship_row = random_row(board) -ship_col = random_col(board) - -for turn in range(4): - guess_row = int(raw_input("Guess Row:")) - guess_col = int(raw_input("Guess Col:")) - - if guess_row == ship_row and guess_col == ship_col: - print "Congratulations! You sunk my battleship!" - break - else: - if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4): - print "Oops, that's not even in the ocean." - elif(board[guess_row][guess_col] == "X"): - print "You guessed that one already." - else: - print "You missed my battleship!" - board[guess_row][guess_col] = "X" - print_board(board) - - if turn == 3: - print "Game Over" - print"Turn " , turn + 1 \ No newline at end of file diff --git a/shell_games/battleship.py b/shell_games/battleship.py new file mode 100644 index 0000000..ff33551 --- /dev/null +++ b/shell_games/battleship.py @@ -0,0 +1,100 @@ +# 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() From 3bc0a0f9fd14811b50e0d6b8fce6e78b525c216d Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Sun, 11 Mar 2018 00:07:15 +0530 Subject: [PATCH 107/151] ReadMe to understand battleship.py --- shell_games/battleship_info.txt | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 shell_games/battleship_info.txt diff --git a/shell_games/battleship_info.txt b/shell_games/battleship_info.txt new file mode 100644 index 0000000..9d04cbb --- /dev/null +++ b/shell_games/battleship_info.txt @@ -0,0 +1,12 @@ + + +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! From 1de27450618fe14d0d507ac548434ce66e09b752 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 12 Mar 2018 16:22:08 +0530 Subject: [PATCH 108/151] Update and rename calendar.py to useful_scripts/calendar.py --- calendar.py | 24 ------------------------ useful_scripts/calendar.py | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 24 deletions(-) delete mode 100644 calendar.py create mode 100644 useful_scripts/calendar.py diff --git a/calendar.py b/calendar.py deleted file mode 100644 index 8809a65..0000000 --- a/calendar.py +++ /dev/null @@ -1,24 +0,0 @@ -# calender viewer -import calendar - -# unction to view calendar -def viewCalender(): - yy = int(input('Year : ')) - mm = int(input('Month : ')) - view = calendar.month(yy , mm) - print('\n' + view) - -# main user interaction code -print('Hello,') -while True: - startOrEnd = str(input('Start or End : ')) - if startOrEnd == 'Start': - print(' ') - print(viewCalender()) - continue - elif startOrEnd == 'End' : - print(' ') - quit() # closes interpreter you can import sys to access quit() or dont change it'll work without importing - else : - print('Oops Try Again') - continue \ No newline at end of file diff --git a/useful_scripts/calendar.py b/useful_scripts/calendar.py new file mode 100644 index 0000000..1620b7d --- /dev/null +++ b/useful_scripts/calendar.py @@ -0,0 +1,17 @@ +# calender viewer +import calendar +import sys + +# function to view calendar +def viewCalender(yy, mm): + # Void Function + print('\n\n Calendar > \n' + calendar.month(yy , mm) + "\n") + +# UI +while True: + if str(input("[+] Start [Y/n] ? ")).strip().lower() == "y": + viewCalender(int(input('\nYear : ')), int(input('Month : '))) + else: + print("\nSee Ya Soon!") + sys.exit(0) + From 5d08059df9790f2626995d1e9c47a1a18f1bb358 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 12 Mar 2018 16:30:22 +0530 Subject: [PATCH 109/151] made code more elegant --- useful_scripts/calendar.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/useful_scripts/calendar.py b/useful_scripts/calendar.py index 1620b7d..4f0e26c 100644 --- a/useful_scripts/calendar.py +++ b/useful_scripts/calendar.py @@ -1,17 +1,17 @@ # calender viewer -import calendar import sys +import calendar # function to view calendar -def viewCalender(yy, mm): - # Void Function - print('\n\n Calendar > \n' + calendar.month(yy , mm) + "\n") +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": - viewCalender(int(input('\nYear : ')), int(input('Month : '))) + 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) - From 4096974e0df94c80af6ddd0c2c257c326ec8d76d Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 12 Mar 2018 19:51:45 +0530 Subject: [PATCH 110/151] Update and rename dice rolling.py to shell_games/dice_rolling_simulator.py --- dice rolling.py | 284 -------------------------- shell_games/dice_rolling_simulator.py | 76 +++++++ 2 files changed, 76 insertions(+), 284 deletions(-) delete mode 100644 dice rolling.py create mode 100644 shell_games/dice_rolling_simulator.py diff --git a/dice rolling.py b/dice rolling.py deleted file mode 100644 index 0534914..0000000 --- a/dice rolling.py +++ /dev/null @@ -1,284 +0,0 @@ -""" a program that asks to enter number of users and asks for naming every user -and rolls dice as per chance""" -import random -while "Kalpak" != "Steven Jobs": - print("_______________________________________________________") - print(""" - """) - print("-------------------------------------------------------------------------") - print("""Note: max users can play are from 2 to 8. - y = yes , n = no - type n if you wnat to get other options""") - print("-------------------------------------------------------------------------") - pirates = raw_input("How many users are going to play:") - print("-------------------------------------------------------------------------") - if pirates =="n": - feature_1 = "Other options are Start again or End:" - if feature_1 == "Start again": - continue - elif feature_1 == "End": - break - elif pirates == "2": - print("-------------------------------------------------------------------------") - user1 = raw_input("Assign user1 name:") - print("-------------------------------------------------------------------------") - user2 = raw_input("Assign user2 name:") - print("-------------------------------------------------------------------------") - while 2 == 2 : - print("-------------------------------------------------------------------------") - roll = raw_input("Do you want to roll the dice ,click y :") - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user1)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user2)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - continue - elif pirates == "3": - print("-------------------------------------------------------------------------") - user1 = raw_input("Assign user1 name:") - print("-------------------------------------------------------------------------") - user2 = raw_input("Assign user2 name:") - print("-------------------------------------------------------------------------") - user3 = raw_input("Assign user3 name:") - print("-------------------------------------------------------------------------") - while 2 == 2 : - print("-------------------------------------------------------------------------") - roll = raw_input("Do you want to roll the dice ,click y :") - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user1)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user2)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user3)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - continue - elif pirates == "4": - print("-------------------------------------------------------------------------") - user1 = raw_input("Assign user1 name:") - print("-------------------------------------------------------------------------") - user2 = raw_input("Assign user2 name:") - print("-------------------------------------------------------------------------") - user3 = raw_input("Assign user3 name:") - print("-------------------------------------------------------------------------") - user4 = raw_input("Assign user4 name:") - print("-------------------------------------------------------------------------") - while 2 == 2 : - print("-------------------------------------------------------------------------") - roll = raw_input("Do you want to roll the dice ,click y :") - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user1)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user2)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user3)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user4)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - continue - elif pirates == "5": - print("-------------------------------------------------------------------------") - user1 = raw_input("Assign user1 name:") - print("-------------------------------------------------------------------------") - user2 = raw_input("Assign user2 name:") - print("-------------------------------------------------------------------------") - user3 = raw_input("Assign user3 name:") - print("-------------------------------------------------------------------------") - user4 = raw_input("Assign user4 name:") - print("-------------------------------------------------------------------------") - user5 = raw_input("Assign user5 name:") - while 2 == 2 : - print("-------------------------------------------------------------------------") - roll = raw_input("Do you want to roll the dice ,click y :") - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user1)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user2)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user3)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user4)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user5)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - continue - elif pirates == "6": - print("-------------------------------------------------------------------------") - user1 = raw_input("Assign user1 name:") - print("-------------------------------------------------------------------------") - user2 = raw_input("Assign user2 name:") - print("-------------------------------------------------------------------------") - user3 = raw_input("Assign user3 name:") - print("-------------------------------------------------------------------------") - user4 = raw_input("Assign user4 name:") - print("-------------------------------------------------------------------------") - user5 = raw_input("Assign user5 name:") - print("-------------------------------------------------------------------------") - user6 = raw_input("Assign user6 name:") - print("-------------------------------------------------------------------------") - while 2 == 2 : - roll = raw_input("Do you want to roll the dice ,click y :") - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user1)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user2)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user3)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user4)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user5)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user6)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - continue - elif pirates == "7": - user1 = raw_input("Assign user1 name:") - print("-------------------------------------------------------------------------") - user2 = raw_input("Assign user2 name:") - print("-------------------------------------------------------------------------") - user3 = raw_input("Assign user3 name:") - print("-------------------------------------------------------------------------") - user4 = raw_input("Assign user4 name:") - print("-------------------------------------------------------------------------") - user5 = raw_input("Assign user5 name:") - print("-------------------------------------------------------------------------") - user6 = raw_input("Assign user6 name:") - print("-------------------------------------------------------------------------") - user7 = raw_input("Assign user7 name:") - print("-------------------------------------------------------------------------") - while 2 == 2 : - roll = raw_input("Do you want to roll the dice ,click y :") - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user1)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user2)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user3)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user4)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user5)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user6)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user7)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - continue - elif pirates == "8": - user1 = raw_input("Assign user1 name:") - print("-------------------------------------------------------------------------") - user2 = raw_input("Assign user2 name:") - print("-------------------------------------------------------------------------") - user3 = raw_input("Assign user3 name:") - print("-------------------------------------------------------------------------") - user4 = raw_input("Assign user4 name:") - print("-------------------------------------------------------------------------") - user5 = raw_input("Assign user5 name:") - print("-------------------------------------------------------------------------") - user6 = raw_input("Assign user6 name:") - print("-------------------------------------------------------------------------") - user7 = raw_input("Assign user7 name:") - print("-------------------------------------------------------------------------") - user8 = raw_input("Assign user8 name:") - while 2 == 2 : - print("-------------------------------------------------------------------------") - roll = raw_input("Do you want to roll the dice ,click y :") - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user1)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user2)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user3)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user4)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user5)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user6)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user7)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - print("Chance of %s"%(user8)) - dice = random.randint(1,6) - print(dice) - print("-------------------------------------------------------------------------") - continue - else : - print("Error: Invalid number of users") - print(""" Number of players you entered are invalid - Breaking Program..... - Restarting.. - """) - print("_______________________________________________________") - continue - - - diff --git a/shell_games/dice_rolling_simulator.py b/shell_games/dice_rolling_simulator.py new file mode 100644 index 0000000..1ad484d --- /dev/null +++ b/shell_games/dice_rolling_simulator.py @@ -0,0 +1,76 @@ +# 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() From 54c9eae57f4090fe309d1c33e2a9f50600089ae0 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 12 Mar 2018 19:55:30 +0530 Subject: [PATCH 111/151] ReadMe to understand dice_rolling_simulator --- shell_games/dice_rolling_simulator_info.txt | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 shell_games/dice_rolling_simulator_info.txt diff --git a/shell_games/dice_rolling_simulator_info.txt b/shell_games/dice_rolling_simulator_info.txt new file mode 100644 index 0000000..077ec1c --- /dev/null +++ b/shell_games/dice_rolling_simulator_info.txt @@ -0,0 +1,12 @@ + + + +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 From b6fda8cfc47876584c9c804afe18b972b2203467 Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Mon, 12 Mar 2018 20:25:31 +0530 Subject: [PATCH 112/151] Create are_you_connected_to_world.py --- network/are_you_connected_to_world.py | 59 +++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 network/are_you_connected_to_world.py diff --git a/network/are_you_connected_to_world.py b/network/are_you_connected_to_world.py new file mode 100644 index 0000000..082ad2f --- /dev/null +++ b/network/are_you_connected_to_world.py @@ -0,0 +1,59 @@ + + +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) From 590b3da1eb116ddb59de587e82007588e7179e1b Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Thu, 15 Mar 2018 23:13:08 +0530 Subject: [PATCH 113/151] Improved readability, comments, code --- geoMean.py | 25 ------------------------- math/geoMean.py | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+), 25 deletions(-) delete mode 100644 geoMean.py create mode 100644 math/geoMean.py diff --git a/geoMean.py b/geoMean.py deleted file mode 100644 index 588071c..0000000 --- a/geoMean.py +++ /dev/null @@ -1,25 +0,0 @@ -import math -# function to calculate geometricMean mean of two numbers -# pre code -def geometricMean(): - gOne = int(input('First num : ')) - gTwo = int(input('Second num : ')) - gMult = (gOne * gTwo) - gMean = math.sqrt(gMult) - print('The geometric Mean of ' + str(gOne) + ' and ' + str(gTwo) + ' is ' + str(gMean)) - -# main code -# to make this code work in python 3.5 convert raw_input() to str(input()) -print("Hello,") -while True: - startOrEnd = raw_input('Start or End : ') - if startOrEnd.strip() == 'Start': - print('Okay let\'s get started \n') - print(geometricMean()) - continue - elif startOrEnd.strip() == 'End': - print('\n Program ended...') - break - else : - print('\n Invalid Input try again') - continue diff --git a/math/geoMean.py b/math/geoMean.py new file mode 100644 index 0000000..cc43cd6 --- /dev/null +++ b/math/geoMean.py @@ -0,0 +1,19 @@ +# 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 From 0c99d5a6c25e5d84f19bd7dcce6d3fc05629190c Mon Sep 17 00:00:00 2001 From: Kalpak Take Date: Fri, 16 Mar 2018 15:25:11 +0530 Subject: [PATCH 114/151] Update and rename number_determiner.py to math/number_lesser_greater.py --- math/number_lesser_greater.py | 17 +++++++++++++++++ number_determiner.py | 17 ----------------- 2 files changed, 17 insertions(+), 17 deletions(-) create mode 100644 math/number_lesser_greater.py delete mode 100644 number_determiner.py diff --git a/math/number_lesser_greater.py b/math/number_lesser_greater.py new file mode 100644 index 0000000..5af39a1 --- /dev/null +++ b/math/number_lesser_greater.py @@ -0,0 +1,17 @@ + +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) diff --git a/number_determiner.py b/number_determiner.py deleted file mode 100644 index 512b97c..0000000 --- a/number_determiner.py +++ /dev/null @@ -1,17 +0,0 @@ -# Determines weather the number is positive negative or zero -# If you want to run this code in Python 3 version replace raw_input() with input() -def pos_neg_zero(x): - if x < 0: - return "Negative" - elif x > 0: - return "Positive" - return "Zero" - -print('Hello,') -while True: - start_or_end = str(raw_input('Start or End : ')).strip().lower() - if start_or_end == 'start': - print(pos_neg_zero(float(raw_input('Number: '))), "\n") - continue - else: - break From 87a3adabd085308b1ce99df630033b545a29ae4d Mon Sep 17 00:00:00 2001 From: Nikhil Singh <30321610+nikhils4@users.noreply.github.com> Date: Tue, 2 Oct 2018 00:26:19 +0530 Subject: [PATCH 115/151] Updated spelling of any --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 071fd27..c64af25 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,4 +1,4 @@ # 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 anu value to the repo i'll definitely merge it! +I'll check and review the changed program if it adds any value to the repo i'll definitely merge it! From 56d36e35f02620402c0905deb1135de01004d940 Mon Sep 17 00:00:00 2001 From: Sam Redmond Date: Thu, 4 Oct 2018 12:41:21 +1300 Subject: [PATCH 116/151] Added comments and error handling Added more comments for beginners to understand, added Python 3 support and made a function. --- shell_games/number_guessing_game.py | 60 +++++++++++++++++------------ 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/shell_games/number_guessing_game.py b/shell_games/number_guessing_game.py index 1f428ba..44aee9f 100644 --- a/shell_games/number_guessing_game.py +++ b/shell_games/number_guessing_game.py @@ -1,40 +1,50 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- +#!/usr/bin/python3 +from random import randint -from random import randint as r_int +MAX_ = 500 # Specify biggest possible value from random number generation -# generates a random number -# in inclusive list from 0 to 10 -n = r_int(0, 10) -print("Hint: number is between 0 to 10 including 0 and 10\n") +# 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: - usr = int(raw_input("Guess a number: ")) - - # Make sure user got the hint - if usr <= 10 and usr >= 0: + guess = get_guess() + if guess >= 0 and guess <= MAX_: # Check if guess between 0 and max - # if correct - if usr == n: + # Correct number! + if guess == num_to_guess: print("That's a correct guess!\nYou got it!\n") break - # brings user closer to answer - elif usr < n: - print("Try a bigger num!") + # Incorrect - give hint + elif guess < num_to_guess: + print("Try a bigger num!") # Number to small else: - print("Try a smaller num!") + print("Try a smaller num!") # Number to big + # Number is not in range else: - print("Pls read the hint!") + print("Enter a number in between 0 and ", MAX_) - # Continue till guess does not match 'n' - # the random number print("") - continue -# Is an infinite loop if usr keeps guessing wrong -# an extra loop can be added to play game as long as user wants -# or can play number of times the user entered! -# Also can be made more harder to play +''' + +*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 + +''' From 233bcd6d0204674744668ae9c55991a7abda7b14 Mon Sep 17 00:00:00 2001 From: GeethOnion <41124555+GeethOnion@users.noreply.github.com> Date: Fri, 5 Oct 2018 03:25:40 +0530 Subject: [PATCH 117/151] For Loop Example --- ForLoopExample.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 ForLoopExample.py diff --git a/ForLoopExample.py b/ForLoopExample.py new file mode 100644 index 0000000..5bad689 --- /dev/null +++ b/ForLoopExample.py @@ -0,0 +1,4 @@ +n = int(input()) +s = '#' +for i in range( 1 , n+1): + print (' ' *(n-i) + s*i) From 6d393ab58d30ea49c7004c28ec9fa71433ec65f8 Mon Sep 17 00:00:00 2001 From: GeethOnion <41124555+GeethOnion@users.noreply.github.com> Date: Fri, 5 Oct 2018 03:33:25 +0530 Subject: [PATCH 118/151] ExampleForList --- simple_scripts/ListExample.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 simple_scripts/ListExample.py diff --git a/simple_scripts/ListExample.py b/simple_scripts/ListExample.py new file mode 100644 index 0000000..131a26a --- /dev/null +++ b/simple_scripts/ListExample.py @@ -0,0 +1,23 @@ +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]) From 03a0e2cf4f74a39f1925225bb9a7a3ab66d3f4af Mon Sep 17 00:00:00 2001 From: Aslam Date: Sun, 21 Oct 2018 23:26:31 +0530 Subject: [PATCH 119/151] Selection Sort and Insertion Sort --- algorithms/sorting/insertion_sort.py | 76 +++++++++++++++++++++++++ algorithms/sorting/selection_sort.py | 85 ++++++++++++++++++++++++++++ 2 files changed, 161 insertions(+) create mode 100644 algorithms/sorting/insertion_sort.py create mode 100644 algorithms/sorting/selection_sort.py diff --git a/algorithms/sorting/insertion_sort.py b/algorithms/sorting/insertion_sort.py new file mode 100644 index 0000000..54adf00 --- /dev/null +++ b/algorithms/sorting/insertion_sort.py @@ -0,0 +1,76 @@ +# -*- 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! + From 713fc2f9e2549cd29cdb235acdd7f5b0448a9fd4 Mon Sep 17 00:00:00 2001 From: Harsh Upadhyay <31928299+harshup18@users.noreply.github.com> Date: Mon, 29 Oct 2018 22:47:20 +0530 Subject: [PATCH 120/151] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 69c471f..445bf37 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Basic python CLI programs as examples
All the examples are useful examples
This examples are of beginners level

-Hey guys i wrote these programs when i was just starting up with programming, now i realize that many of 'em feel very un-professional and useless so i decided to go one by one through all and make 'em more usefull and professional ! +Hey guys I wrote these programs when I was just starting up with programming, now I realize that many of 'em feel very un-professional and useless so I decided to go one by one through all and make 'em more usefull and professional !
Note: In 2.x versions input isn't useful , lly , 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! From 992a15f9985c614ceeb7cceed33ce3e16694043d Mon Sep 17 00:00:00 2001 From: reesepalma <45537971+reesepalma@users.noreply.github.com> Date: Mon, 3 Dec 2018 12:54:12 +0800 Subject: [PATCH 121/151] Star --- star_turtle.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 star_turtle.py diff --git a/star_turtle.py b/star_turtle.py new file mode 100644 index 0000000..76aaf33 --- /dev/null +++ b/star_turtle.py @@ -0,0 +1,12 @@ +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) + + +>>> From e3055b1230927c528f37969ba3b79e2c1d734210 Mon Sep 17 00:00:00 2001 From: crackCodeLogn Date: Tue, 12 Feb 2019 22:25:16 +0530 Subject: [PATCH 122/151] Updating and Optimizing the prime number verification program --- primeNumbers.py | 50 +++++++++++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/primeNumbers.py b/primeNumbers.py index 14b5975..41845a3 100644 --- a/primeNumbers.py +++ b/primeNumbers.py @@ -1,25 +1,35 @@ # Prime number Determiner # replace input() with raw_input() in Python version 2.7 input() works with version 3 +import math as Math -while True: - startOrEnd = str(input('Start or End : ')) - if startOrEnd == 'Start': - toCheckNum = int(input('Number to Check : ')) - if toCheckNum > 1: - for x in range(2, toCheckNum): - if toCheckNum % x == 0: - print(str(toCheckNum) + ' is divisible by ' + str(x)) - print(str(toCheckNum) + ' is not a Prime number') - break - elif toCheckNum % x > 0: - print(str(toCheckNum) + ' is a prime number') - break - continue - else : - print(str(toCheckNum) + ' is not a prime number') - continue - else : - print('Progarm Ended...') - break +POSITIVE_MESSAGE = " is a prime number" +NEGATIVE_MESSAGE = " is not a prime number" + + +def is_number_prime(number): + 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 + 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 From 0e6ca0f3388626c33a1d4f59266af441c75b1422 Mon Sep 17 00:00:00 2001 From: crackCodeLogn Date: Wed, 13 Feb 2019 21:52:45 +0530 Subject: [PATCH 123/151] Adding comments for understanding --- primeNumbers.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/primeNumbers.py b/primeNumbers.py index 41845a3..dcdb9a0 100644 --- a/primeNumbers.py +++ b/primeNumbers.py @@ -7,6 +7,20 @@ 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 @@ -14,6 +28,7 @@ def is_number_prime(number): 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 From 26058f88354a139f10985ca46cc1aececa542573 Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+AsciiKay@users.noreply.github.com> Date: Sun, 7 Jul 2019 22:51:25 +0530 Subject: [PATCH 124/151] Being less pretentious --- simple_scripts/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/simple_scripts/README.md b/simple_scripts/README.md index 62e18b5..b572e3f 100644 --- a/simple_scripts/README.md +++ b/simple_scripts/README.md @@ -3,7 +3,6 @@ 'simple_scripts' Sub-directory contains all simplest programs, these programs are simple to read/write.
-The programs have been re-checked and re-mastered by me!
+The programs have been re-checked and improved a bit
Although i've tried to keep it as orignal as possible.
-Keep Patience It'll take time to go through every program!!
Thanks From b5824126c26401a683b6c3a34e0ea7f3f805a127 Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+AsciiKay@users.noreply.github.com> Date: Sun, 7 Jul 2019 23:28:13 +0530 Subject: [PATCH 125/151] Update and rename ForLoopExample.py to simple_scripts/for_loop_mountain.py Made program more comprehensive --- ForLoopExample.py | 4 ---- simple_scripts/for_loop_mountain.py | 27 +++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) delete mode 100644 ForLoopExample.py create mode 100644 simple_scripts/for_loop_mountain.py diff --git a/ForLoopExample.py b/ForLoopExample.py deleted file mode 100644 index 5bad689..0000000 --- a/ForLoopExample.py +++ /dev/null @@ -1,4 +0,0 @@ -n = int(input()) -s = '#' -for i in range( 1 , n+1): - print (' ' *(n-i) + s*i) diff --git a/simple_scripts/for_loop_mountain.py b/simple_scripts/for_loop_mountain.py new file mode 100644 index 0000000..b311c8e --- /dev/null +++ b/simple_scripts/for_loop_mountain.py @@ -0,0 +1,27 @@ + +# 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) From 599dc3212ca5c8e336b46904d30433e7faa0fff5 Mon Sep 17 00:00:00 2001 From: akshara Date: Sat, 25 Jul 2020 21:12:41 +0530 Subject: [PATCH 126/151] Fixed an error in the function --- cartesian_plane_quadrant.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cartesian_plane_quadrant.py b/cartesian_plane_quadrant.py index 606aec8..3631e97 100644 --- a/cartesian_plane_quadrant.py +++ b/cartesian_plane_quadrant.py @@ -12,7 +12,7 @@ def determine_quadrant(x, y): elif x > 0 and y < 0 : return 'IV(+,-)' else : - return 'Invalid parameters were provided') + 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)) From 8940262bd35bff621e51d72d082214b474a2fe7b Mon Sep 17 00:00:00 2001 From: Lakshita2002 Date: Fri, 7 Aug 2020 16:18:20 +0530 Subject: [PATCH 127/151] Grammatical correction --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 445bf37..9e4be0d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Beginners-Python-Programs Basic python CLI programs as examples
All the examples are useful examples
-This examples are of beginners level
+These examples are of beginners' level

Hey guys I wrote these programs when I was just starting up with programming, now I realize that many of 'em feel very un-professional and useless so I decided to go one by one through all and make 'em more usefull and professional !
From a38341906ae06c9dd152b983a68936650032bf4a Mon Sep 17 00:00:00 2001 From: HenryBass <63601449+HenryBass@users.noreply.github.com> Date: Fri, 2 Oct 2020 18:25:41 -0400 Subject: [PATCH 128/151] Added a freefall calculator --- math/FreefallCalculator | 62 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 math/FreefallCalculator diff --git a/math/FreefallCalculator b/math/FreefallCalculator new file mode 100644 index 0000000..47e8164 --- /dev/null +++ b/math/FreefallCalculator @@ -0,0 +1,62 @@ +# 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() From fe27fb36ce9ee13e1e80806adedaf28982462836 Mon Sep 17 00:00:00 2001 From: Dennis thomas <52597699+denz647@users.noreply.github.com> Date: Mon, 12 Oct 2020 11:24:30 +0530 Subject: [PATCH 129/151] Amstrong_python.py --- Amstrong | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Amstrong diff --git a/Amstrong b/Amstrong new file mode 100644 index 0000000..a988381 --- /dev/null +++ b/Amstrong @@ -0,0 +1,20 @@ +# Python program to check if the number is an Armstrong number or not + +# take input from the user +num = int(input("Enter a number: ")) + +# initialize sum +sum = 0 + +# find the sum of the cube of each digit +temp = num +while temp > 0: + digit = temp % 10 + sum += digit ** 3 + temp //= 10 + +# display the result +if num == sum: + print(num,"is an Armstrong number") +else: + print(num,"is not an Armstrong number") From 39d424d7a0c83018d1c2c08161a287fe272c8c35 Mon Sep 17 00:00:00 2001 From: Keshav099 <56930509+Keshav099@users.noreply.github.com> Date: Sat, 24 Oct 2020 11:31:09 +0530 Subject: [PATCH 130/151] Update sum_array.py --- sum_array.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sum_array.py b/sum_array.py index b926753..8639cff 100644 --- a/sum_array.py +++ b/sum_array.py @@ -5,7 +5,7 @@ def sum_arr(n): return res nums = [52345,746587,98589,54398,9348,45887,49856] -test = sum_arr(nums) +test = sum_arr(nums) #Python built in method of adding list all element if test == sum(nums): print("Sum of arr: {}".format(test)) else: From 91fc4f90600e7ef2f21cba14d859af395e30efcb Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+AsciiKay@users.noreply.github.com> Date: Fri, 30 Oct 2020 01:07:51 +0530 Subject: [PATCH 131/151] Update sum_array.py --- sum_array.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sum_array.py b/sum_array.py index 8639cff..039a30d 100644 --- a/sum_array.py +++ b/sum_array.py @@ -5,7 +5,9 @@ def sum_arr(n): return res nums = [52345,746587,98589,54398,9348,45887,49856] -test = sum_arr(nums) #Python built in method of adding list all element +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: From 4f02b31ee1727d0d8ab6661fd45c527784cd7063 Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+AsciiKay@users.noreply.github.com> Date: Fri, 30 Oct 2020 01:30:27 +0530 Subject: [PATCH 132/151] Update and rename Amstrong to armstrong_number.py --- Amstrong => armstrong_number.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) rename Amstrong => armstrong_number.py (54%) diff --git a/Amstrong b/armstrong_number.py similarity index 54% rename from Amstrong rename to armstrong_number.py index a988381..5ca59c3 100644 --- a/Amstrong +++ b/armstrong_number.py @@ -1,4 +1,5 @@ -# Python program to check if the number is an Armstrong number or not +# 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: ")) @@ -15,6 +16,6 @@ # display the result if num == sum: - print(num,"is an Armstrong number") + print(num, "is an Armstrong number.") else: - print(num,"is not an Armstrong number") + print(num, "is not an Armstrong number.") From 0ae839c62de8dbdab100850b14d6a817b81bcf70 Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+AsciiKay@users.noreply.github.com> Date: Fri, 30 Oct 2020 01:35:16 +0530 Subject: [PATCH 133/151] Delete armstrong_number.py --- armstrong_number.py | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 armstrong_number.py diff --git a/armstrong_number.py b/armstrong_number.py deleted file mode 100644 index 5ca59c3..0000000 --- a/armstrong_number.py +++ /dev/null @@ -1,21 +0,0 @@ -# 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 - -# find the sum of the cube of each digit -temp = num -while temp > 0: - digit = temp % 10 - sum += digit ** 3 - temp //= 10 - -# display the result -if num == sum: - print(num, "is an Armstrong number.") -else: - print(num, "is not an Armstrong number.") From 19a3eebaaddd6df5821e067ea4748df1cc082bcb Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+AsciiKay@users.noreply.github.com> Date: Fri, 30 Oct 2020 01:35:22 +0530 Subject: [PATCH 134/151] Revert "Amstrong_python.py" From 66e26de15a3f0f502c597445b0869fc56410503d Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+AsciiKay@users.noreply.github.com> Date: Fri, 30 Oct 2020 01:39:02 +0530 Subject: [PATCH 135/151] Create armstrong_number.py --- armstrong_number.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 armstrong_number.py diff --git a/armstrong_number.py b/armstrong_number.py new file mode 100644 index 0000000..dd09992 --- /dev/null +++ b/armstrong_number.py @@ -0,0 +1,25 @@ +# 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 + +# find the sum of the cube of each digit +temp = num +while temp > 0: + digit = temp % 10 + sum += digit ** 3 + 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 From 65d35a5356fc9cca9921f80c284ec2d2e72ba8de Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+AsciiKay@users.noreply.github.com> Date: Fri, 30 Oct 2020 01:41:41 +0530 Subject: [PATCH 136/151] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9e4be0d..d511d5d 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Basic python CLI programs as examples
All the examples are useful examples
These examples are of beginners' level

-Hey guys I wrote these programs when I was just starting up with programming, now I realize that many of 'em feel very un-professional and useless so I decided to go one by one through all and make 'em more usefull and professional ! +Hey guys I wrote these programs when I was just starting up with programming, now I realize that many of 'em feel very un-professional and useless so I decided to go one by one through all and make 'em more useful and professional !
Note: In 2.x versions input isn't useful , lly , 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! From f74b8c2d25c794cea6c9b5f1ee60eaa3d0166f0a Mon Sep 17 00:00:00 2001 From: Panav Sinha <72135200+panavsinha@users.noreply.github.com> Date: Wed, 25 Nov 2020 16:59:00 +0530 Subject: [PATCH 137/151] Update README.md Rectified some grammatical mistakes. --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d511d5d..16e2c9f 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # Beginners-Python-Programs -Basic python CLI programs as examples
-All the examples are useful examples
-These examples are of beginners' level
+Basic python CLI programs as examples.
+All the examples are useful examples.
+These examples are of beginners' level.

-Hey guys I wrote these programs when I was just starting up with programming, now I realize that many of 'em feel very un-professional and useless so I decided to go one by one through all and make 'em more useful and professional ! +Hey guys, I wrote these programs when I was just starting up with programming, now I realize that many of 'em feel very un-professional and useless so I decided to go one by one through all and make 'em more useful and professional!
-Note: In 2.x versions input isn't useful , lly , 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! +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!
 NOTE: WORK IN PROGRESS!

From 51b353b0f089183de9a65e35d4a609037e317984 Mon Sep 17 00:00:00 2001
From: senay21 <76999954+senay21@users.noreply.github.com>
Date: Tue, 6 Jul 2021 16:06:38 +0300
Subject: [PATCH 138/151] Update dictionary.py

---
 dictionary.py | 36 ++++++++++++++++++------------------
 1 file changed, 18 insertions(+), 18 deletions(-)

diff --git a/dictionary.py b/dictionary.py
index ea2c9b2..4d6a6b3 100644
--- a/dictionary.py
+++ b/dictionary.py
@@ -9,53 +9,53 @@ def __init__(self, word, meaning):
 
 	def add_new(self):
 		dictionary[self.word] = self.meaning
-		print "Word Successfully Added"
+		print ("Word Successfully Added")
 
 	def delete_word(self):
 		try:
 			del dictionary[self.word]
-			print "Word Successfully Deleted"
+			print ("Word Successfully Deleted")
 		except KeyError:
-			print "The Word Does Not Exist in Dictionary. Try Again!"	
+			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"
+			print ("Word Was Successfully Edited")
 		except KeyError:
-			print "The Word You Trying To Edit Does Not Exist in Dictionary!"	
+			print ("The Word You Trying To Edit Does Not Exist in Dictionary!")	
 
 	def view_word(self):
 		try:
-			print dictionary[self.word]
+			print (dictionary[self.word])
 		except KeyError:
-			print "The Word is not in Dictionary."
+			print ("The Word is not in Dictionary.")
 
 	def view_all(self):		
 		for i in dictionary.keys():
-			print(i + " : " + dictionary[i])
+			print(f"{i} : {dictionary[i]}")
 
 def start():
-	get_op = raw_input("Add, Delete, Edit, View, View all : ")
+	get_op = input("Add, Delete, Edit, View, View all : ")
 	if get_op in ["add", "Add"]:
-		get_word = raw_input("Word to add : ")
-		get_meaning = raw_input("Meaning : ")
+		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 = raw_input("Word to 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 = raw_input("Word to edit : ")
-		get_new_meaning = raw_input("New meaning : ")
+		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 = raw_input("Word to view : ")
+		get_word_to_view = input("Word to view : ")
 		view = Dict(get_word_to_view, None)
 		view.view_word()
 
@@ -64,14 +64,14 @@ def start():
 		nothing.view_all()
 
 	else:
-		print "Invalid Input. Try again!"			
+		print ("Invalid Input. Try again!")			
 
 def end():
 	quit()
 
 def main():
 	while True:
-		s_or_e = raw_input("Start or End : ")
+		s_or_e = input("Start or End : ")
 		if s_or_e == "Start":
 			start()
 			print("  ")
@@ -82,4 +82,4 @@ def main():
 
 
 if __name__ == "__main__":
-	main()		
\ No newline at end of file
+	main()		

From d92cd825c94d591e56d9d589c89cad2be956674e Mon Sep 17 00:00:00 2001
From: dany pm 
Date: Tue, 9 Aug 2022 21:59:43 +0430
Subject: [PATCH 139/151] Update hello_world.py

Add new print ways .
---
 hello_world.py | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)

diff --git a/hello_world.py b/hello_world.py
index 48de24b..dc0ea25 100644
--- a/hello_world.py
+++ b/hello_world.py
@@ -2,7 +2,34 @@
 # 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)
+
+

From 93047ddd9bb253d85d166f0d8386a01ae374cfc8 Mon Sep 17 00:00:00 2001
From: sanjail3 <86285670+sanjail3@users.noreply.github.com>
Date: Tue, 30 Aug 2022 21:48:56 +0530
Subject: [PATCH 140/151] Added snake game

---
 .idea/.gitignore                              |   3 +
 .idea/Beginners-Python-Examples.iml           |  12 ++
 .idea/inspectionProfiles/Project_Default.xml  |  43 ++++++
 .../inspectionProfiles/profiles_settings.xml  |   6 +
 .idea/misc.xml                                |   4 +
 .idea/modules.xml                             |   8 ++
 .idea/vcs.xml                                 |   6 +
 snake game/.idea/.gitignore                   |   3 +
 .../inspectionProfiles/profiles_settings.xml  |   6 +
 snake game/.idea/misc.xml                     |   7 +
 snake game/.idea/modules.xml                  |   8 ++
 snake game/.idea/snake game.iml               |  10 ++
 snake game/donut.png                          | Bin 0 -> 5214 bytes
 snake game/index.html                         |  15 ++
 snake game/main.py                            | 134 ++++++++++++++++++
 15 files changed, 265 insertions(+)
 create mode 100644 .idea/.gitignore
 create mode 100644 .idea/Beginners-Python-Examples.iml
 create mode 100644 .idea/inspectionProfiles/Project_Default.xml
 create mode 100644 .idea/inspectionProfiles/profiles_settings.xml
 create mode 100644 .idea/misc.xml
 create mode 100644 .idea/modules.xml
 create mode 100644 .idea/vcs.xml
 create mode 100644 snake game/.idea/.gitignore
 create mode 100644 snake game/.idea/inspectionProfiles/profiles_settings.xml
 create mode 100644 snake game/.idea/misc.xml
 create mode 100644 snake game/.idea/modules.xml
 create mode 100644 snake game/.idea/snake game.iml
 create mode 100644 snake game/donut.png
 create mode 100644 snake game/index.html
 create mode 100644 snake game/main.py

diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..26d3352
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,3 @@
+# Default ignored files
+/shelf/
+/workspace.xml
diff --git a/.idea/Beginners-Python-Examples.iml b/.idea/Beginners-Python-Examples.iml
new file mode 100644
index 0000000..8b8c395
--- /dev/null
+++ b/.idea/Beginners-Python-Examples.iml
@@ -0,0 +1,12 @@
+
+
+  
+    
+    
+    
+  
+  
+    
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml
new file mode 100644
index 0000000..cbe978f
--- /dev/null
+++ b/.idea/inspectionProfiles/Project_Default.xml
@@ -0,0 +1,43 @@
+
+  
+    
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644
index 0000000..105ce2d
--- /dev/null
+++ b/.idea/inspectionProfiles/profiles_settings.xml
@@ -0,0 +1,6 @@
+
+  
+    
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..dc9ea49
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,4 @@
+
+
+  
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 0000000..9dd9f1a
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+  
+    
+      
+    
+  
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..94a25f7
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+  
+    
+  
+
\ No newline at end of file
diff --git a/snake game/.idea/.gitignore b/snake game/.idea/.gitignore
new file mode 100644
index 0000000..26d3352
--- /dev/null
+++ b/snake game/.idea/.gitignore	
@@ -0,0 +1,3 @@
+# Default ignored files
+/shelf/
+/workspace.xml
diff --git a/snake game/.idea/inspectionProfiles/profiles_settings.xml b/snake game/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644
index 0000000..105ce2d
--- /dev/null
+++ b/snake game/.idea/inspectionProfiles/profiles_settings.xml	
@@ -0,0 +1,6 @@
+
+  
+    
+
\ No newline at end of file
diff --git a/snake game/.idea/misc.xml b/snake game/.idea/misc.xml
new file mode 100644
index 0000000..4f58316
--- /dev/null
+++ b/snake game/.idea/misc.xml	
@@ -0,0 +1,7 @@
+
+
+  
+  
+    
+
\ No newline at end of file
diff --git a/snake game/.idea/modules.xml b/snake game/.idea/modules.xml
new file mode 100644
index 0000000..603a4d9
--- /dev/null
+++ b/snake game/.idea/modules.xml	
@@ -0,0 +1,8 @@
+
+
+  
+    
+      
+    
+  
+
\ No newline at end of file
diff --git a/snake game/.idea/snake game.iml b/snake game/.idea/snake game.iml
new file mode 100644
index 0000000..74d515a
--- /dev/null
+++ b/snake game/.idea/snake game.iml	
@@ -0,0 +1,10 @@
+
+
+  
+    
+      
+    
+    
+    
+  
+
\ No newline at end of file
diff --git a/snake game/donut.png b/snake game/donut.png
new file mode 100644
index 0000000000000000000000000000000000000000..236483050fb524ac76ce01ce050932581aac7867
GIT binary patch
literal 5214
zcmbtYcT`i^w+)dnqIp6;F+3oys>I
zeKy}8tW5OxksAqv^y!cn)Dj8+R3~%nz?tbX1JTyxETHnW=p0>O!<#x00RZlo`-34}
zmRke>U;F-g{hXBX9dAB;J
zX_57`tB+*`M3hBNGBPk^B%j;)k-ZmOWqt}w2kU8^;5ov2l#}COxg*|J?fXiRt+cwX
z*lCFqJRqrK;o&;5dQJk|+>Ua39!`qISTwEtrJB0X)?$RmMFkbH6DN)wJF6(ADtvNw
zB7AE$3r1BkIEv!Z_~oKpn`TUKQmCr_@iUhLw9W0sbwp)G-}n`moNsGH
zXsU`qge6}+L0(OfYV`@t&$iy24Lzp_0`VPBxnVp%5?F3Sh`yr#xY9Mr@S?4iOj@$(
zSRbBBwXLsm9`D0DI?EL1S-)+=(1NJ6po-lf>Ncfpk3yw|J*0(H(LyR|QIBb{4YY{b
zO>)@|nM#XzL<_4~91GmNTt*9hK#Qs!@AIdT@6&>+1JtZ8DVctFjhh}K*4SPCK`fz>
zAH?c9!$DA5RL#e?_%JQl>O^pYkxRC**Bw*uZ}@!TdBZv1I}={nBkz1uj66m?Gdi8G
z&?2k83C+R@Q|GiX`$4PMwIh8>A#UW
zl8CTAYwYptu`4aH^dTPo1eas0q-1F0drkw4_5dTG(B?AKc4JDJSwLx#?Gbe|Q+uu`
zf)U&~WI3V=b%|rTBd9dmoE_>g5*l~?0%d(Lf|gy{6mX~?i@Pi!NJF7pUcFydQQ?_qE-rEq^Uae@~7F62VlQ^11S=4qMN;ltI
z)!rLm*%;UxK(`N3{kG?{AFpqD$7TH3+pF5V5lc;MZk=A(-T8zdG%vMXSp0lpqTzjY
zeqY&Y{3VM;GkV)nurNoGqosu=($7~Oj`BmG?1BRZB%nya5`6H4P%5?Siae$e>F|2ufN{mtC8pNhk0{li)y#uMdu>Nzsu$
z;MJsm?=LGz(?JB3r>3o;@h=En(vilHNO(;J1u~f|Pga)qBX}t&K_CzXMX&-G45A}I
z#LGAmoC3lTPth6Jfd?FhXd;q;#gnjpIN&}f9N`y0(vg;C2mYdll1KzB;x{{vC=Wka
z3D{SWr#r0xM-dg2@ps$BW;T&
z`UMb>=mUm*rC%fl1T>t4M(KhT=^iM8L10B~h5y*vxAC`v5rt%i(nYAKL6p#Ho**?a
zSOcVjREK~N5ETuOq7qVBT|*hJ=&9=Yo9L&?ziEsSbQV>xDp*YwqNJjv4pG(k+w#HY
zzwt1?03>GL6XU-=_+N{GBFz0Kw;=
z1W-r?v=7=BjU(+RN$FRTP)JP@mgIx}J4H|*(!WzguRTp4IL=E)ngT+hJ>da9BxzlH
z+<_VjD5I_lY|RAH-+0RD|G~FkblM94u=M}%4F8Y%-mk!eHruZ~`Uc%C
zZ0U|{6g&H4VfkihHP)t%oXiP6byrTxuxbDq3&5XSG?>O_W}0WOO=wIsjiMP8tl8NJrouvG!O5*ZwF}3MJ>#y8^9Gr4
ziT3N|d$eT~7(m+4((Ef++=)r^T!^M<(G%<08o?;&+wTIry`I!IM0HND=Z`JbHYX;}
z^M{^^7)NEEJp3{9ed+wVnur}=nSG?p(bdc^755(&FEz75XFqrSK^?yJiH}FiqdVwX
zTU8BMk9XH1T~IjeRhER(?OK#MZSdo#e%*T|#zh_pU)|-heGdT>3dUY95T0=RN)5A}
zPxa~VFW5$eWeAG~2aiRrdp1dcn=n5nm~I$I_jf%+u|Tw*FtF6ft9
zGvjMPak0FIklj1-EEV4R%}3lk64u9YFF0fUcSY6{X5E}tJG_)LVk{>Al96CUmBnLP
z^DN)$h4}g9uX^W1hy75^=5M;`zWX-LK{@KslLp3f_HfVwI;<@Ol~Kl#@5*+j2Hm<4wmeG_@ZHV)mJvylTerrrgqWeLBAvB{lxIv*{cUj#LL^V!h%FzbJmSUe%9mgL@8{Do*+
zJiR28HVu+nTTDp&kZ$8RzP#BOlbO(G&&Aobk$DyEHX6cf!FNY^JZ>T?jCKBHSBZFo
zR`1O9TZ(7Yq=G)BviW0m^Q4gmbp>c}P63EnxUPQ-62edHWk3EY3JTrB3{Ce3H{Lm2
zy-YF{iP;!Dty|TeY4fB@>=T;&^mZ=e(Yo3xKR({%V=mRyEBU+=$i;ERNMr!wIygD`pn`Xc?QB!@VIgu)rRRWKKV_V|#+e+f
zW_gyKHP_|w$2}@%UVV*NqNIxYfZAi&Jb7V
zrH&-CgI=7BiEr%-ad9~8YpAIgws0;@nYmB7Nsv$i9H}i#-;q%F@!12ijdMzF6uax_
zN%=a=+{B93QV~Ze*h1J)ZQ#Uq$jr9#OzLW0SMjbCq&|eWa>?dHnw%u9_lbtzaGy;C
z$Q&0V7+u;f)zld4dN$%pm2&l=crnn^@C9Nde2u5=vaaHn29o5Ns2ewn>oF111dx3}8#nwD%ZS2Y9fj>QBzvw64p7-r_ZXZaB
zJL_KG}
zQexpx_9G&d#H}dvj2jEb
zTxH|G^FB^NlwcOm?k&@dZOQ1BiCN0)GAIpXR<05P2fWaMm&o7{8O56y#9u=u&r}IB
zGzZFNV?OL^y_|phpj@iszUpRNwNT-9^x-V%tnzT?xXZ4aO_FTW#&8_T*jw(?OoPFd
zfbNdemsX9RLSNbHViSXPGZT#zm+Z}j|;`QA#kLv}sBPI`RAgxY&M_k43t
z-A>TxQ-0;L)EUHrm{#AH<@@rDH?QRSW#&R|k?rJ`U!(@mzG=Z*JmgRUZh+wNG$!Ae
zkIaRI6WjWq3r*bR?w6KQmVD}Zh{cnxKRg?z6(+0P?wR`;Cq2IuhnPuWkrd^1I8@n@
zA%0wo)oE|@bfPiWMU|<|WE%gEQL@QHcKo?iy=psK$Z5h=q)x-}&Ku&%vni(+`*>{v
zB=g(AF6X&^L?pg>1Yd8DbI9%L>aD;@%y_$}t9OWN0Ked(Tx={o1fVGscLUD=x*94u
zx5ZRbTuIYc6nej`KOe|(D4LZE(urgLhAoj?A6^x-Js|{P^wTV-dix3Sn{0G&l~nEs
zII***UEt4cTKif_CLYb{DJZvw=$~sjwE3)dFL{_zNV?)tsrO!tiEiN)1_Q{KTfXjg
zOu-kdhQsoKveclbyiVLRi{p+4+I`Bf^l<%k9=pSYS75}
zfatWSeQb}g5WD>r!+&19*{1v6*ym8q)5Iz2Kn})1k=)-&PGurublrrP!A92J>W;Jh
z&tSAaN{n6}_WHtK*SNMF*Ui?Q;t~wW5`ad2(m0IV%_(Y;RdPxdS-w
zPNpurX$n_Xy`jP6Vb~C|6s2B^e1SDjSUajxH{pSKe3#O@jhQ*+R|LH4-y(7NwYXze
z<7b>NkLt{=Xn!W|c^K$xs}dvG;@q2{fSGX5Z&6|xW_Oz%Xl>C4^~s^I{F!uUR#WSD
zUh4pph(>jGnDd?@R`(i9t9x%HK1hQ;fj8QlXQ
z=T5zfcJ5fVh?Q)ZzViZeTxTi_Rav_v8lKo<0A4D4s@GAnn;_7Eb*U+^LcXef2fJP#
z%Zqs`?48_de7I?V921%TYB{t%3&Pkuo6wr+*7!81ccCjOEz@SrrCW`bZtEeS#5z$j
z+t3Cb?E$UgsiVDyD!e)n}UzhMUq5-{D|
zMl)8W+XnUbuS$U@#I%Ihu4UdOeD6fI*F8&~nvcyaHSJ_cPHG4bA|LiXcI#Skd}3n2
z-Pqf2A1_nG9qK+89TE7-U{)e4yz#_pLv)M{ItUh6+_{S
z51XdNgTH+6)FsdK3T~R;U>&?l6U`|;FHRoFjo}dZ_~hF_(`{w1kCxhZf(q8c^>QUu
Uu`P`)`~MfrjI0bR&w51u7dxyh!2kdN

literal 0
HcmV?d00001

diff --git a/snake game/index.html b/snake game/index.html
new file mode 100644
index 0000000..06edd87
--- /dev/null
+++ b/snake game/index.html	
@@ -0,0 +1,15 @@
+
+
+
+
+  
+    

Live streaming

+
+ + +
+ + + + + diff --git a/snake game/main.py b/snake game/main.py new file mode 100644 index 0000000..843844a --- /dev/null +++ b/snake game/main.py @@ -0,0 +1,134 @@ +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() \ No newline at end of file From 1346afc2456ae4a41c56eee73667714e16710c61 Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+zeta-punk-x1@users.noreply.github.com> Date: Tue, 17 Jan 2023 18:30:28 +0530 Subject: [PATCH 141/151] Create decimal_to_binary_converter.py I came up with this algorithm to convert decimal(natural numbers) to binary completely from scratch and therefore it might not be the best most efficient implementation. Optimizations are welcome. --- math/decimal_to_binary_converter.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 math/decimal_to_binary_converter.py diff --git a/math/decimal_to_binary_converter.py b/math/decimal_to_binary_converter.py new file mode 100644 index 0000000..5aa4f28 --- /dev/null +++ b/math/decimal_to_binary_converter.py @@ -0,0 +1,16 @@ + +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(dec_to_bin(i)) From 906103c746cf53f3d1e7a6a272657dbb272b10b6 Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+zeta-punk-x1@users.noreply.github.com> Date: Wed, 18 Jan 2023 10:32:43 +0530 Subject: [PATCH 142/151] Update test cases code block --- math/decimal_to_binary_converter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/decimal_to_binary_converter.py b/math/decimal_to_binary_converter.py index 5aa4f28..a954d0e 100644 --- a/math/decimal_to_binary_converter.py +++ b/math/decimal_to_binary_converter.py @@ -13,4 +13,4 @@ def dec_to_bin(n): return binary for i in range(0,101): - print(dec_to_bin(i)) + print("Decimal:"+str(i)+" Binary:"+str(dec_to_bin(i))) From f8c5ddb6bb43f286e03c17585e85e1b5f893d257 Mon Sep 17 00:00:00 2001 From: Kalpak Take <20800689+zeta-punk-x1@users.noreply.github.com> Date: Fri, 3 Feb 2023 19:06:35 +0530 Subject: [PATCH 143/151] Add introductory comment --- math/decimal_to_binary_converter.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/math/decimal_to_binary_converter.py b/math/decimal_to_binary_converter.py index a954d0e..eb5003f 100644 --- a/math/decimal_to_binary_converter.py +++ b/math/decimal_to_binary_converter.py @@ -1,3 +1,8 @@ +""" +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 @@ -13,4 +18,4 @@ def dec_to_bin(n): return binary for i in range(0,101): - print("Decimal:"+str(i)+" Binary:"+str(dec_to_bin(i))) + print("Natural Number:"+str(i)+" Binary:"+str(dec_to_bin(i))) From 859a8a64c533982eb3de8762905befc38f8cf021 Mon Sep 17 00:00:00 2001 From: Anonymous InfoBro <132287085+IntelligentInfoBro@users.noreply.github.com> Date: Wed, 15 Nov 2023 18:27:43 -0800 Subject: [PATCH 144/151] Create for_loop_fibonnaci A simple program using for loop to print fibonacci sequence till nth member of the sequence --- simple_scripts/for_loop_fibonnaci | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 simple_scripts/for_loop_fibonnaci diff --git a/simple_scripts/for_loop_fibonnaci b/simple_scripts/for_loop_fibonnaci new file mode 100644 index 0000000..0f17dab --- /dev/null +++ b/simple_scripts/for_loop_fibonnaci @@ -0,0 +1,9 @@ +#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) From ef824f5400b4b917bb6f555302b6be84e5f765a7 Mon Sep 17 00:00:00 2001 From: Anonymously known <132287085+IntelligentInfoBro@users.noreply.github.com> Date: Fri, 17 Nov 2023 11:09:52 -0800 Subject: [PATCH 145/151] Create Binary_to_decimal A program to convert binary string(s) to decimal. --- math/Binary_to_decimal | 62 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 math/Binary_to_decimal diff --git a/math/Binary_to_decimal b/math/Binary_to_decimal new file mode 100644 index 0000000..5a82316 --- /dev/null +++ b/math/Binary_to_decimal @@ -0,0 +1,62 @@ +# 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() + + + From 7f28e0da493b9b2031e365e9f3a1adabc78f3454 Mon Sep 17 00:00:00 2001 From: virinchi-addanki <123866097+virinchi-addanki@users.noreply.github.com> Date: Sat, 20 Jan 2024 13:42:47 +0530 Subject: [PATCH 146/151] Add files via upload --- algorithms/string/check_anagram.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 algorithms/string/check_anagram.py diff --git a/algorithms/string/check_anagram.py b/algorithms/string/check_anagram.py new file mode 100644 index 0000000..ec2532a --- /dev/null +++ b/algorithms/string/check_anagram.py @@ -0,0 +1,26 @@ +'''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") \ No newline at end of file From bb89e002684443267de85b1f0ac29066385aefa7 Mon Sep 17 00:00:00 2001 From: "Do (A)I Matter?" <20800689+zeta-punk-x1@users.noreply.github.com> Date: Fri, 2 Aug 2024 20:35:21 +0000 Subject: [PATCH 147/151] Update README.md --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 16e2c9f..5e56f1e 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,19 @@ # Beginners-Python-Programs Basic python CLI programs as examples.
All the examples are useful examples.
-These examples are of beginners' level.
+These examples are of beginner level.

-Hey guys, I wrote these programs when I was just starting up with programming, now I realize that many of 'em feel very un-professional and useless so I decided to go one by one through all and make 'em more useful and professional! +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.
-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! +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.
-NOTE: WORK IN PROGRESS!
-Files Outside Particular Folders/Directories have not been checked yet!
-Files inside, directories offer much elegant code and explaination
+NOTE: Work in progress
+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
-contact kalpaktake@gmail.com +contact electric.vision.x19@gmail.com From 87d706005ff72b55724a98a85515052847990b5d Mon Sep 17 00:00:00 2001 From: "Do (A)I Matter?" <20800689+zeta-punk-x1@users.noreply.github.com> Date: Fri, 2 Aug 2024 20:37:19 +0000 Subject: [PATCH 148/151] Update README.md --- README.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 5e56f1e..415e98e 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,16 @@ 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.
-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. - -
-NOTE: Work in progress
-Files outside particular directories have not been checked yet
+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
contact electric.vision.x19@gmail.com From 5430199480c06187fe0543efe270230d78385adb Mon Sep 17 00:00:00 2001 From: "Do (A)I Matter?" <20800689+zeta-punk-x1@users.noreply.github.com> Date: Fri, 2 Aug 2024 20:37:54 +0000 Subject: [PATCH 149/151] Update README.md --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 415e98e..4f7338e 100644 --- a/README.md +++ b/README.md @@ -8,10 +8,9 @@ Note: In 2.x versions input isn't useful. Similarly, in 3.x versions raw_input i
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
contact electric.vision.x19@gmail.com From 19e68eaeac610aa44648fbc3b92cad400396c36a Mon Sep 17 00:00:00 2001 From: "Do (A)I Matter?" <20800689+zeta-punk-x1@users.noreply.github.com> Date: Fri, 2 Aug 2024 20:38:11 +0000 Subject: [PATCH 150/151] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 4f7338e..1be585e 100644 --- a/README.md +++ b/README.md @@ -12,5 +12,6 @@ Update: I wrote these programs when I was just starting out with programming, no 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
contact electric.vision.x19@gmail.com From a7b718c524b0f20a89b15a3d69479cc7a98b4140 Mon Sep 17 00:00:00 2001 From: Kal <20800689+kal179@users.noreply.github.com> Date: Sun, 12 Jan 2025 19:36:33 +0530 Subject: [PATCH 151/151] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 1be585e..68cd977 100644 --- a/README.md +++ b/README.md @@ -14,4 +14,3 @@ Files inside, directories offer better code and explanation

Also see this : Beginners-Python-Examples/CONTRIBUTING.md
-contact electric.vision.x19@gmail.com