[
  {
    "path": ".gitattributes",
    "content": "src/docs/* linguist-documentation\nscripts/* linguist-documentation\ngatsby-browser.js linguist-documentation\ngatsby-config.js linguist-documentation\ngatsby-node.js linguist-documentation\ngatsby-ssr.js linguist-documentation\n.travis/* linguist-documentation\nconfig.js linguist-documentation\n"
  },
  {
    "path": ".gitignore",
    "content": "# IDE Specific\r\n.vscode\r\n.idea/codeStyles/Project.xml\r\n\r\n# dotenv environment variables file\r\n.env\r\n\r\n# gatsby files\r\n.cache/\r\npublic\r\n\r\n# Mac files\r\n.DS_Store\r\n\r\n# Logs\r\nlogs\r\n*.log\r\nnpm-debug.log*\r\nyarn-debug.log*\r\nyarn-error.log*\r\n\r\n# Runtime data\r\npids\r\n*.pid\r\n*.seed\r\n*.pid.lock\r\n\r\n# Directory for instrumented libs generated by jscoverage/JSCover\r\nlib-cov\r\n\r\n# Coverage directory used by tools like istanbul\r\ncoverage\r\n\r\n# nyc test coverage\r\n.nyc_output\r\n\r\n# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\r\n.grunt\r\n\r\n# Bower dependency directory (https://bower.io/)\r\nbower_components\r\n\r\n# node-waf configuration\r\n.lock-wscript\r\n\r\n# Compiled binary addons (https://nodejs.org/api/addons.html)\r\nbuild/Release\r\n\r\n# Dependency directories\r\nnode_modules/\r\njspm_packages/\r\n\r\n# TypeScript v1 declaration files\r\ntypings/\r\n\r\n# Optional npm cache directory\r\n.npm\r\n\r\n# Optional eslint cache\r\n.eslintcache\r\n\r\n# Optional REPL history\r\n.node_repl_history\r\n\r\n# Output of 'npm pack'\r\n*.tgz\r\n\r\n# Yarn\r\nyarn-error.log\r\n.pnp/\r\n.pnp.js\r\n\r\n# Yarn Integrity file\r\n.yarn-integrity\r\n\r\n# dotenv environment variables file\r\n.env\r\n\r\n# next.js build output\r\n.next\r\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\r\n\r\n## Our Pledge\r\n\r\nIn the interest of fostering an open and welcoming environment, we as\r\ncontributors and maintainers pledge to making participation in our project and\r\nour community a harassment-free experience for everyone, regardless of age, body\r\nsize, disability, ethnicity, gender identity and expression, level of experience,\r\neducation, socio-economic status, nationality, personal appearance, race,\r\nreligion, or sexual identity and orientation.\r\n\r\n## Our Standards\r\n\r\nExamples of behavior that contributes to creating a positive environment\r\ninclude:\r\n\r\n* Using welcoming and inclusive language\r\n* Being respectful of differing viewpoints and experiences\r\n* Gracefully accepting constructive criticism\r\n* Focusing on what is best for the community\r\n* Showing empathy towards other community members\r\n\r\nExamples of unacceptable behavior by participants include:\r\n\r\n* The use of sexualized language or imagery and unwelcome sexual attention or\r\n  advances\r\n* Trolling, insulting/derogatory comments, and personal or political attacks\r\n* Public or private harassment\r\n* Publishing others' private information, such as a physical or electronic\r\n  address, without explicit permission\r\n* Other conduct which could reasonably be considered inappropriate in a\r\n  professional setting\r\n\r\n## Our Responsibilities\r\n\r\nProject maintainers are responsible for clarifying the standards of acceptable\r\nbehavior and are expected to take appropriate and fair corrective action in\r\nresponse to any instances of unacceptable behavior.\r\n\r\nProject maintainers have the right and responsibility to remove, edit, or\r\nreject comments, commits, code, wiki edits, issues, and other contributions\r\nthat are not aligned to this Code of Conduct, or to ban temporarily or\r\npermanently any contributor for other behaviors that they deem inappropriate,\r\nthreatening, offensive, or harmful.\r\n\r\n## Scope\r\n\r\nThis Code of Conduct applies both within project spaces and in public spaces\r\nwhen an individual is representing the project or its community. Examples of\r\nrepresenting a project or community include using an official project e-mail\r\naddress, posting via an official social media account, or acting as an appointed\r\nrepresentative at an online or offline event. Representation of a project may be\r\nfurther defined and clarified by project maintainers.\r\n\r\n## Enforcement\r\n\r\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\r\nreported by contacting the project team at [mst10041967@gmail.com]. All\r\ncomplaints will be reviewed and investigated and will result in a response that\r\nis deemed necessary and appropriate to the circumstances. The project team is\r\nobligated to maintain confidentiality with regard to the reporter of an incident.\r\nFurther details of specific enforcement policies may be posted separately.\r\n\r\nProject maintainers who do not follow or enforce the Code of Conduct in good\r\nfaith may face temporary or permanent repercussions as determined by other\r\nmembers of the project's leadership.\r\n\r\n## Attribution\r\n\r\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\r\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\r\n\r\n[homepage]: https://www.contributor-covenant.org\r\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contribution Guidelines\r\n\r\n**30 seconds of code** is powered by the community, so feel free to contribute in any way you can to help us!\r\n\r\n## How you can help\r\n\r\n- Submit pull requests with new snippets (see guidelines below) or snippet updates (tags, descriptions, explanations, typos, examples, code improvements).\r\n- Open issues for things you want to see added, modified, discuss ideas or help out with existing issues.\r\n\r\n## Ground rules\r\n\r\nBreaking any of these rules will result in your pull request being closed. Please follow these guidelines above all else:\r\n\r\n- **Always be polite and respectful to others** and try to follow the advice of the moderators/collaborators/owners.\r\n- **Only modify snippet files**, never modify the generated files in the `snippet_data` directory.\r\n- **Use the snippet template** to create new snippets, ensure they have the correct name and are in the correct location.\r\n- **Follow snippet format exactly**, otherwise your snippets will not be recognized correctly by the tools responsible for publishing them on the website. This includes such things as spacing and empty lines - if you accidentally make a mistake, consult the repository's [snippet template](snippet-template.md).\r\n- **Snippets should solve real-world problems**, no matter how simple and should be abstract enough to be applied to different scenarios.\r\n\r\n## Snippet creation\r\n\r\nIn order to create a new snippet, you should follow the steps below:\r\n\r\n- Create a copy of the [snippet template](snippet-template.md) in the `snippets` directory.\r\n- Change the name of the newly created file to the name of your snippet.\r\n- Edit the file, adding your snippet based on the guidelines.\r\n\r\n## Snippet guidelines\r\n\r\n- Snippet must follow [these general writing guidelines](https://github.com/30-seconds/brand-and-design/blob/master/writing-guidelines.md).\r\n- Snippets must have all their frontmatter sections (title, tags etc.) filled.\r\n- Snippet titles must correspond to the filename and follow the language and repository's naming conventions.\r\n- Snippet tags must be comma-separated, contain a primary tag as seen on the website as their first tag.\r\n- Snippets must have their `firstSeen` dates formatted using [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).\r\n- Snippet descriptions must be short and to the point. Explain *what* the snippet does and detail *how* the snippet works and the language features used in it.\r\n- Snippet code and examples must be enclosed in appropriate, language-tagged blocks as shown in the snippet template, be short and use modern techniques and features. Also make sure to test your code before submitting.\r\n- If your snippet contains arguments with default parameters, explain what happens if they are omitted when calling the function and what the default case is. Specify default parameters for arguments only if necessary.\r\n- If your snippet uses recursion, use the `recursion` tag and explain the base cases.\r\n- Try to strike a balance between readability, brevity, and performance.\r\n- Always use soft tabs (2 spaces), never hard tabs.\r\n- Leave a single space after a comma (`,`) character (both in the description and code).\r\n- Define multiple variables on the same line, if possible. Use meaningful names (e.g. `letter` instead of `lt`) and follow existing conventions as seen in other snippets. Do not use trailing or leading underscores in variable names.\r\n- Snippet should only use native `python 3.6` modules. Snippets using external modules will be disqualified immediately.\r\n"
  },
  {
    "path": "LICENSE",
    "content": "Attribution 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an \"as-is\" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n     Considerations for licensors: Our public licenses are\n     intended for use by those authorized to give the public\n     permission to use material in ways otherwise restricted by\n     copyright and certain other rights. Our licenses are\n     irrevocable. Licensors should read and understand the terms\n     and conditions of the license they choose before applying it.\n     Licensors should also secure all rights necessary before\n     applying our licenses so that the public can reuse the\n     material as expected. Licensors should clearly mark any\n     material not subject to the license. This includes other CC-\n     licensed material, or material used under an exception or\n     limitation to copyright. More considerations for licensors:\n    wiki.creativecommons.org/Considerations_for_licensors\n\n     Considerations for the public: By using one of our public\n     licenses, a licensor grants the public permission to use the\n     licensed material under specified terms and conditions. If\n     the licensor's permission is not necessary for any reason--for\n     example, because of any applicable exception or limitation to\n     copyright--then that use is not regulated by the license. Our\n     licenses grant only permissions under copyright and certain\n     other rights that a licensor has authority to grant. Use of\n     the licensed material may still be restricted for other\n     reasons, including because others have copyright or other\n     rights in the material. A licensor may make special requests,\n     such as asking that all changes be marked or described.\n     Although not required by our licenses, you are encouraged to\n     respect those requests where reasonable. More considerations\n     for the public:\n    wiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution 4.0 International Public License (\"Public License\"). To the\nextent this Public License may be interpreted as a contract, You are\ngranted the Licensed Rights in consideration of Your acceptance of\nthese terms and conditions, and the Licensor grants You such rights in\nconsideration of benefits the Licensor receives from making the\nLicensed Material available under these terms and conditions.\n\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n\n  d. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  e. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  f. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  g. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  h. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  i. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  j. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  k. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part; and\n\n            b. produce, reproduce, and Share Adapted Material.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n       4. If You Share Adapted Material You produce, the Adapter's\n          License You apply must not prevent recipients of the Adapted\n          Material from complying with this Public License.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material; and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n\n=======================================================================\n\nCreative Commons is not a party to its public\nlicenses. Notwithstanding, Creative Commons may elect to apply one of\nits public licenses to material it publishes and in those instances\nwill be considered the “Licensor.” The text of the Creative Commons\npublic licenses is dedicated to the public domain under the CC0 Public\nDomain Dedication. Except for the limited purpose of indicating that\nmaterial is shared under a Creative Commons public license or as\notherwise permitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the\npublic licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n"
  },
  {
    "path": "README.md",
    "content": "> **IMPORTANT NOTICE:**\n>\n> As of May, 2023, all 30-seconds content repositories have been merged into [30-seconds-of-code](https://github.com/30-seconds/30-seconds-of-code).\n>\n> Please watch, star and follow relevant activity there.\n\n[![Logo](/logo.png)](https://30secondsofcode.org/python/p/1)\n\n# 30 seconds of code\n\n> Short Python code snippets for all your development needs\n\n* Visit [our website](https://30secondsofcode.org) to view our snippet collection.\n* Use the [Search page](https://30secondsofcode.org/search) to find snippets that suit your needs. You can search by name, tag, language or using a snippet's description. Just start typing a term and see what comes up.\n* Browse the [Python Snippet collection](https://30secondsofcode.org/python/p/1) to see all the snippets in this project or click individual tags at the top of the same page to narrow down your search to a specific tag.\n* Click on each snippet card to view the whole snippet, including code, explanation and examples.\n* You can use the button at the bottom of a snippet card to copy the code to clipboard.\n* If you like the project, give it a star. It means a lot to the people maintaining it.\n\n## Want to contribute?\n\n* If you want to help us improve, take a minute to read the [Contribution Guidelines](/CONTRIBUTING.md) first.\n* Use the [Snippet Template](/snippet-template.md) to add new snippets to the collection.\n* If you find a problem with a specific snippet, please [open an issue](https://github.com/30-seconds/30-seconds-of-python/issues/new).\n* If you find a problem with the website, please [report it in the web repository](https://github.com/30-seconds/30-seconds-web/issues/new).\n\n## Credits\n\n* This repository is maintained by the [30 seconds of code organization on GitHub](https://github.com/30-seconds).\n* All snippets are licensed under the CC-BY-4.0 License, unless explicitly stated otherwise.\n* Logos, names and trademarks are not to be used without the explicit consent of the owners of the 30 seconds of code GitHub organization.\n* Our website is powered by [Netlify](https://www.netlify.com/), [Next.js](https://nextjs.org/) & [GitHub](https://github.com/).\n"
  },
  {
    "path": "language_fix.py",
    "content": "print('This file is here only to tag the repository language. Do not delete, please!')"
  },
  {
    "path": "snippet-template.md",
    "content": "---\r\ntitle: Function name\r\ntype: snippet\r\ntags: [utility]\r\ncover: image\r\ndateModified: 2021-06-13T05:00:00-04:00\r\n---\r\n\r\nExplain briefly what the snippet does.\r\n\r\n- Explain briefly how the snippet works.\r\n- Use bullet points for your snippet's explanation.\r\n- Try to explain everything briefly but clearly.\r\n\r\n```py\r\ndef function_name(args):\r\n  # code\r\n  return 0\r\n```\r\n\r\n```py\r\nfunction_name(val) # result\r\n```\r\n"
  },
  {
    "path": "snippets/add-days.md",
    "content": "---\ntitle: Add days to date\ntype: snippet\ntags: [date]\ncover: orange-flower\ndateModified: 2020-10-28T16:19:04+02:00\n---\n\nCalculates the date of `n` days from the given date.\n\n- Use `datetime.timedelta` and the `+` operator to calculate the new `datetime.datetime` value after adding `n` days to `d`.\n- Omit the second argument, `d`, to use a default value of `datetime.today()`.\n\n```py\nfrom datetime import datetime, timedelta\n\ndef add_days(n, d = datetime.today()):\n  return d + timedelta(n)\n```\n\n```py\nfrom datetime import date\n\nadd_days(5, date(2020, 10, 25)) # date(2020, 10, 30)\nadd_days(-5, date(2020, 10, 25)) # date(2020, 10, 20)\n```\n"
  },
  {
    "path": "snippets/all-equal.md",
    "content": "---\ntitle: Check if list elements are identical\ntype: snippet\ntags: [list]\ncover: fallen-leaves\ndateModified: 2020-10-11T13:40:42+03:00\n---\n\nChecks if all elements in a list are equal.\n\n- Use `set()` to eliminate duplicate elements and then use `len()` to check if length is `1`.\n\n```py\ndef all_equal(lst):\n  return len(set(lst)) == 1\n```\n\n```py\nall_equal([1, 2, 3, 4, 5, 6]) # False\nall_equal([1, 1, 1, 1]) # True\n```\n"
  },
  {
    "path": "snippets/all-unique.md",
    "content": "---\ntitle: Check if list has no duplicates\ntype: snippet\ntags: [list]\ncover: touch-flower\ndateModified: 2021-01-07T23:30:28+02:00\n---\n\nChecks if all the values in a list are unique.\n\n- Use `set()` on the given list to keep only unique occurrences.\n- Use `len()` to compare the length of the unique values to the original list.\n\n```py\ndef all_unique(lst):\n  return len(lst) == len(set(lst))\n```\n\n```py\nx = [1, 2, 3, 4, 5, 6]\ny = [1, 2, 2, 3, 4, 5]\nall_unique(x) # True\nall_unique(y) # False\n```\n"
  },
  {
    "path": "snippets/arithmetic-progression.md",
    "content": "---\ntitle: Arithmetic progression\ntype: snippet\ntags: [math]\ncover: number-2\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nGenerates a list of numbers in the arithmetic progression starting with the given positive integer and up to the specified limit.\n\n- Use `range()` and `list()` with the appropriate start, step and end values.\n\n```py\ndef arithmetic_progression(n, lim):\n  return list(range(n, lim + 1, n))\n```\n\n```py\narithmetic_progression(5, 25) # [5, 10, 15, 20, 25]\n```\n"
  },
  {
    "path": "snippets/average-by.md",
    "content": "---\ntitle: Mapped list average\ntype: snippet\ntags: [math,list]\ncover: flower-vase\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nCalculates the average of a list, after mapping each element to a value using the provided function.\n\n- Use `map()` to map each element to the value returned by `fn`.\n- Use `sum()` to sum all of the mapped values, divide by `len(lst)`.\n- Omit the last argument, `fn`, to use the default identity function.\n\n```py\ndef average_by(lst, fn = lambda x: x):\n  return sum(map(fn, lst), 0.0) / len(lst)\n```\n\n```py\naverage_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda x: x['n'])\n# 5.0\n```\n"
  },
  {
    "path": "snippets/average.md",
    "content": "---\ntitle: Average\ntype: snippet\ntags: [math,list]\ncover: digital-nomad-15\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nCalculates the average of two or more numbers.\n\n- Use `sum()` to sum all of the `args` provided, divide by `len()`.\n\n```py\ndef average(*args):\n  return sum(args, 0.0) / len(args)\n```\n\n```py\naverage(*[1, 2, 3]) # 2.0\naverage(1, 2, 3) # 2.0\n```\n"
  },
  {
    "path": "snippets/bifurcate-by.md",
    "content": "---\ntitle: Bifurcate list based on function\ntype: snippet\ntags: [list]\ncover: two-flower-vases\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nSplits values into two groups, based on the result of the given filtering function.\n\n- Use a list comprehension to add elements to groups, based on the value returned by `fn` for each element.\n- If `fn` returns a truthy value for any element, add it to the first group, otherwise add it to the second group.\n\n```py\ndef bifurcate_by(lst, fn):\n  return [\n    [x for x in lst if fn(x)],\n    [x for x in lst if not fn(x)]\n  ]\n```\n\n```py\nbifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b')\n# [ ['beep', 'boop', 'bar'], ['foo'] ]\n```\n"
  },
  {
    "path": "snippets/bifurcate.md",
    "content": "---\ntitle: Bifurcate list based on values\ntype: snippet\ntags: [list]\ncover: mug-flower-book\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nSplits values into two groups, based on the result of the given `filter` list.\n\n- Use a list comprehension and `zip()` to add elements to groups, based on `filter`.\n- If `filter` has a truthy value for any element, add it to the first group, otherwise add it to the second group.\n\n```py\ndef bifurcate(lst, filter):\n  return [\n    [x for x, flag in zip(lst, filter) if flag],\n    [x for x, flag in zip(lst, filter) if not flag]\n  ]\n```\n\n```py\nbifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True])\n# [ ['beep', 'boop', 'bar'], ['foo'] ]\n```\n"
  },
  {
    "path": "snippets/binomial-coefficient.md",
    "content": "---\ntitle: Binomial coefficient\ntype: snippet\ntags: [math]\ncover: digital-nomad-5\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nCalculates the number of ways to choose `k` items from `n` items without repetition and without order.\n\n- Use `math.comb()` to calculate the binomial coefficient.\n\n```py\nfrom math import comb\n\ndef binomial_coefficient(n, k):\n  return comb(n, k)\n```\n\n```py\nbinomial_coefficient(8, 2) # 28\n```\n"
  },
  {
    "path": "snippets/byte-size.md",
    "content": "---\ntitle: Byte size of string\ntype: snippet\ntags: [string]\ncover: river-house-lights\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nReturns the length of a string in bytes.\n\n- Use `str.encode()` to encode the given string and return its length.\n\n```py\ndef byte_size(s):\n  return len(s.encode('utf-8'))\n```\n\n```py\nbyte_size('😀') # 4\nbyte_size('Hello World') # 11\n```\n"
  },
  {
    "path": "snippets/camel.md",
    "content": "---\ntitle: Camelcase string\ntype: snippet\ntags: [string,regexp]\ncover: digital-nomad-9\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nConverts a string to camelcase.\n\n- Use `re.sub()` to replace any `-` or `_` with a space, using the regexp `r\"(_|-)+\"`.\n- Use `str.title()` to capitalize the first letter of each word and convert the rest to lowercase.\n- Finally, use `str.replace()` to remove spaces between words.\n\n```py\nfrom re import sub\n\ndef camel(s):\n  s = sub(r\"(_|-)+\", \" \", s).title().replace(\" \", \"\")\n  return ''.join([s[0].lower(), s[1:]])\n```\n\n```py\ncamel('some_database_field_name') # 'someDatabaseFieldName'\ncamel('Some label that needs to be camelized')\n# 'someLabelThatNeedsToBeCamelized'\ncamel('some-javascript-property') # 'someJavascriptProperty'\ncamel('some-mixed_string with spaces_underscores-and-hyphens')\n# 'someMixedStringWithSpacesUnderscoresAndHyphens'\n```\n"
  },
  {
    "path": "snippets/capitalize-every-word.md",
    "content": "---\ntitle: Capitalize every word\ntype: snippet\ntags: [string]\ncover: trippy-chemicals\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nCapitalizes the first letter of every word in a string.\n\n- Use `str.title()` to capitalize the first letter of every word in the string.\n\n```py\ndef capitalize_every_word(s):\n  return s.title()\n```\n\n```py\ncapitalize_every_word('hello world!') # 'Hello World!'\n```\n"
  },
  {
    "path": "snippets/capitalize.md",
    "content": "---\ntitle: Capitalize string\ntype: snippet\ntags: [string]\ncover: palm-tree-house\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nCapitalizes the first letter of a string.\n\n- Use list slicing and `str.upper()` to capitalize the first letter of the string.\n- Use `str.join()` to combine the capitalized first letter with the rest of the characters.\n- Omit the `lower_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to lowercase.\n\n```py\ndef capitalize(s, lower_rest = False):\n  return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])])\n```\n\n```py\ncapitalize('fooBar') # 'FooBar'\ncapitalize('fooBar', True) # 'Foobar'\n```\n"
  },
  {
    "path": "snippets/cast-list.md",
    "content": "---\ntitle: Cast to list\ntype: snippet\ntags: [list]\ncover: colorful-pots\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nCasts the provided value as a list if it's not one.\n\n- Use `isinstance()` to check if the given value is enumerable.\n- Return it by using `list()` or encapsulated in a list accordingly.\n\n```py\ndef cast_list(val):\n  return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]\n```\n\n```py\ncast_list('foo') # ['foo']\ncast_list([1]) # [1]\ncast_list(('foo', 'bar')) # ['foo', 'bar']\n```\n"
  },
  {
    "path": "snippets/celsius-to-fahrenheit.md",
    "content": "---\ntitle: Celsius to Fahrenheit\ntype: snippet\ntags: [math]\nunlisted: true\ncover: last-light\ndateModified: 2021-01-04T12:47:04+02:00\n---\n\nConverts Celsius to Fahrenheit.\n\n- Follow the conversion formula `F = 1.8 * C + 32`.\n\n```py\ndef celsius_to_fahrenheit(degrees):\n  return ((degrees * 1.8) + 32)\n```\n\n```py\ncelsius_to_fahrenheit(180) # 356.0\n```\n"
  },
  {
    "path": "snippets/check-prop.md",
    "content": "---\ntitle: Check property\ntype: snippet\ntags: [function]\ncover: lake-trees\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nCreates a function that will invoke a predicate function for the specified property on a given dictionary.\n\n- Return a `lambda` function that takes a dictionary and applies the predicate function, `fn` to the specified property.\n\n```py\ndef check_prop(fn, prop):\n  return lambda obj: fn(obj[prop])\n```\n\n```py\ncheck_age = check_prop(lambda x: x >= 18, 'age')\nuser = {'name': 'Mark', 'age': 18}\ncheck_age(user) # True\n```\n"
  },
  {
    "path": "snippets/chunk-into-n.md",
    "content": "---\ntitle: Split list into n chunks\ntype: snippet\ntags: [list]\ncover: succulent-10\ndateModified: 2020-10-23T05:35:06+03:00\n---\n\nChunks a list into `n` smaller lists.\n\n- Use `math.ceil()` and `len()` to get the size of each chunk.\n- Use `list()` and `range()` to create a new list of size `n`.\n- Use `map()` to map each element of the new list to a chunk the length of `size`.\n- If the original list can't be split evenly, the final chunk will contain the remaining elements.\n\n```py\nfrom math import ceil\n\ndef chunk_into_n(lst, n):\n  size = ceil(len(lst) / n)\n  return list(\n    map(lambda x: lst[x * size:x * size + size],\n    list(range(n)))\n  )\n```\n\n```py\nchunk_into_n([1, 2, 3, 4, 5, 6, 7], 4) # [[1, 2], [3, 4], [5, 6], [7]]\n```\n"
  },
  {
    "path": "snippets/chunk.md",
    "content": "---\ntitle: Split list into chunks\ntype: snippet\ntags: [list]\ncover: red-berries\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nChunks a list into smaller lists of a specified size.\n\n- Use `list()` and `range()` to create a list of the desired `size`.\n- Use `map()` on the list and fill it with splices of the given list.\n- Finally, return the created list.\n\n```py\nfrom math import ceil\n\ndef chunk(lst, size):\n  return list(\n    map(lambda x: lst[x * size:x * size + size],\n      list(range(ceil(len(lst) / size)))))\n```\n\n```py\nchunk([1, 2, 3, 4, 5], 2) # [[1, 2], [3, 4], [5]]\n```\n"
  },
  {
    "path": "snippets/clamp-number.md",
    "content": "---\ntitle: Clamp number\ntype: snippet\ntags: [math]\ncover: highlands\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nClamps `num` within the inclusive range specified by the boundary values.\n\n- If `num` falls within the range (`a`, `b`), return `num`.\n- Otherwise, return the nearest number in the range.\n\n```py\ndef clamp_number(num, a, b):\n  return max(min(num, max(a, b)), min(a, b))\n```\n\n```py\nclamp_number(2, 3, 5) # 3\nclamp_number(1, -1, -5) # -1\n```\n"
  },
  {
    "path": "snippets/collect-dictionary.md",
    "content": "---\ntitle: Invert dictionary\ntype: snippet\ntags: [dictionary]\ncover: working-bee\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nInverts a dictionary with non-unique hashable values.\n\n- Create a `collections.defaultdict` with `list` as the default value for each key.\n- Use `dictionary.items()` in combination with a loop to map the values of the dictionary to keys using `dict.append()`.\n- Use `dict()` to convert the `collections.defaultdict` to a regular dictionary.\n\n```py\nfrom collections import defaultdict\n\ndef collect_dictionary(obj):\n  inv_obj = defaultdict(list)\n  for key, value in obj.items():\n    inv_obj[value].append(key)\n  return dict(inv_obj)\n```\n\n```py\nages = {\n  'Peter': 10,\n  'Isabel': 10,\n  'Anna': 9,\n}\ncollect_dictionary(ages) # { 10: ['Peter', 'Isabel'], 9: ['Anna'] }\n```\n"
  },
  {
    "path": "snippets/combine-values.md",
    "content": "---\ntitle: Combine dictionary values\ntype: snippet\ntags: [dictionary]\ncover: fruit-feast\ndateModified: 2021-04-04T14:32:35+03:00\n---\n\nCombines two or more dictionaries, creating a list of values for each key.\n\n- Create a new `collections.defaultdict` with `list` as the default value for each key and loop over `dicts`.\n- Use `dict.append()` to map the values of the dictionary to keys.\n- Use `dict()` to convert the `collections.defaultdict` to a regular dictionary.\n\n```py\nfrom collections import defaultdict\n\ndef combine_values(*dicts):\n  res = defaultdict(list)\n  for d in dicts:\n    for key in d:\n      res[key].append(d[key])\n  return dict(res)\n```\n\n```py\nd1 = {'a': 1, 'b': 'foo', 'c': 400}\nd2 = {'a': 3, 'b': 200, 'd': 400}\n\ncombine_values(d1, d2) # {'a': [1, 3], 'b': ['foo', 200], 'c': [400], 'd': [400]}\n```\n"
  },
  {
    "path": "snippets/compact.md",
    "content": "---\ntitle: Compact list\ntype: snippet\ntags: [list]\ncover: new-plant\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nRemoves falsy values from a list.\n\n- Use `filter()` to filter out falsy values (`False`, `None`, `0`, and `\"\"`).\n\n```py\ndef compact(lst):\n  return list(filter(None, lst))\n```\n\n```py\ncompact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]\n```\n"
  },
  {
    "path": "snippets/compose-right.md",
    "content": "---\ntitle: Reverse compose functions\ntype: snippet\ntags: [function]\ncover: lavender-shelf\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nPerforms left-to-right function composition.\n\n- Use `functools.reduce()` to perform left-to-right function composition.\n- The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.\n\n```py\nfrom functools import reduce\n\ndef compose_right(*fns):\n  return reduce(lambda f, g: lambda *args: g(f(*args)), fns)\n```\n\n```py\nadd = lambda x, y: x + y\nsquare = lambda x: x * x\nadd_and_square = compose_right(add, square)\nadd_and_square(1, 2) # 9\n```\n"
  },
  {
    "path": "snippets/compose.md",
    "content": "---\ntitle: Compose functions\ntype: snippet\ntags: [function]\ncover: tram-car-2\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nPerforms right-to-left function composition.\n\n- Use `functools.reduce()` to perform right-to-left function composition.\n- The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.\n\n```py\nfrom functools import reduce\n\ndef compose(*fns):\n  return reduce(lambda f, g: lambda *args: f(g(*args)), fns)\n```\n\n```py\nadd5 = lambda x: x + 5\nmultiply = lambda x, y: x * y\nmultiply_and_add_5 = compose(add5, multiply)\nmultiply_and_add_5(5, 2) # 15\n```\n"
  },
  {
    "path": "snippets/count-by.md",
    "content": "---\ntitle: Count grouped elements\ntype: snippet\ntags: [list]\ncover: rabbit-call\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nGroups the elements of a list based on the given function and returns the count of elements in each group.\n\n- Use `collections.defaultdict` to initialize a dictionary.\n- Use `map()` to map the values of the given list using the given function.\n- Iterate over the map and increase the element count each time it occurs.\n\n```py\nfrom collections import defaultdict\n\ndef count_by(lst, fn = lambda x: x):\n  count = defaultdict(int)\n  for val in map(fn, lst):\n    count[val] += 1\n  return dict(count)\n```\n\n```py\nfrom math import floor\n\ncount_by([6.1, 4.2, 6.3], floor) # {6: 2, 4: 1}\ncount_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}\n```\n"
  },
  {
    "path": "snippets/count-occurrences.md",
    "content": "---\ntitle: Count occurrences\ntype: snippet\ntags: [list]\ncover: pineapple-at-work\ndateModified: 2021-01-10T00:00:36+02:00\n---\n\nCounts the occurrences of a value in a list.\n\n- Use `list.count()` to count the number of occurrences of `val` in `lst`.\n\n```py\ndef count_occurrences(lst, val):\n  return lst.count(val)\n```\n\n```py\ncount_occurrences([1, 1, 2, 1, 2, 3], 1) # 3\n```\n"
  },
  {
    "path": "snippets/cumsum.md",
    "content": "---\ntitle: Partial sum list\ntype: snippet\ntags: [list]\ncover: digital-nomad-16\ndateModified: 2021-01-13T23:30:41+02:00\n---\n\nCreates a list of partial sums.\n\n- Use `itertools.accumulate()` to create the accumulated sum for each element.\n- Use `list()` to convert the result into a list.\n\n```py\nfrom itertools import accumulate\n\ndef cumsum(lst):\n  return list(accumulate(lst))\n```\n\n```py\ncumsum(range(0, 15, 3)) # [0, 3, 9, 18, 30]\n```\n"
  },
  {
    "path": "snippets/curry.md",
    "content": "---\ntitle: Curry function\ntype: snippet\ntags: [function]\ncover: leaves-read\ndateModified: 2020-11-02T19:27:07+02:00\n---\n\nCurries a function.\n\n- Use `functools.partial()` to return a new partial object which behaves like `fn` with the given arguments, `args`, partially applied.\n\n```py\nfrom functools import partial\n\ndef curry(fn, *args):\n  return partial(fn, *args)\n```\n\n```py\nadd = lambda x, y: x + y\nadd10 = curry(add, 10)\nadd10(20) # 30\n```\n"
  },
  {
    "path": "snippets/daterange.md",
    "content": "---\ntitle: Date range\ntype: snippet\ntags: [date]\ncover: maple-leaf-palette\ndateModified: 2021-01-07T23:30:28+02:00\n---\n\nCreates a list of dates between `start` (inclusive) and `end` (not inclusive).\n\n- Use  `datetime.timedelta.days` to get the days between `start` and `end`.\n- Use `int()` to convert the result to an integer and `range()` to iterate over each day.\n- Use a list comprehension and `datetime.timedelta` to create a list of `datetime.date` objects.\n\n```py\nfrom datetime import timedelta, date\n\ndef daterange(start, end):\n  return [start + timedelta(n) for n in range(int((end - start).days))]\n```\n\n```py\nfrom datetime import date\n\ndaterange(date(2020, 10, 1), date(2020, 10, 5))\n# [date(2020, 10, 1), date(2020, 10, 2), date(2020, 10, 3), date(2020, 10, 4)]\n```\n"
  },
  {
    "path": "snippets/days-ago.md",
    "content": "---\ntitle: Days ago\ntype: snippet\ntags: [date]\ncover: cup-of-orange\ndateModified: 2020-10-28T16:19:30+02:00\n---\n\nCalculates the date of `n` days ago from today.\n\n- Use `datetime.date.today()` to get the current day.\n- Use `datetime.timedelta` to subtract `n` days from today's date.\n\n```py\nfrom datetime import timedelta, date\n\ndef days_ago(n):\n  return date.today() - timedelta(n)\n```\n\n```py\ndays_ago(5) # date(2020, 10, 23)\n```\n"
  },
  {
    "path": "snippets/days-diff.md",
    "content": "---\ntitle: Date difference in days\ntype: snippet\ntags: [date]\ncover: succulent-9\ndateModified: 2020-10-28T16:19:39+02:00\n---\n\nCalculates the day difference between two dates.\n\n- Subtract `start` from `end` and use `datetime.timedelta.days` to get the day difference.\n\n```py\ndef days_diff(start, end):\n  return (end - start).days\n```\n\n```py\nfrom datetime import date\n\ndays_diff(date(2020, 10, 25), date(2020, 10, 28)) # 3\n```\n"
  },
  {
    "path": "snippets/days-from-now.md",
    "content": "---\ntitle: Days from now\ntype: snippet\ntags: [date]\ncover: clutter\ndateModified: 2020-10-28T16:19:51+02:00\n---\n\nCalculates the date of `n` days from today.\n\n- Use `datetime.date.today()` to get the current day.\n- Use `datetime.timedelta` to add `n` days from today's date.\n\n```py\nfrom datetime import timedelta, date\n\ndef days_from_now(n):\n  return date.today() + timedelta(n)\n```\n\n```py\ndays_from_now(5) # date(2020, 11, 02)\n```\n"
  },
  {
    "path": "snippets/decapitalize.md",
    "content": "---\ntitle: Decapitalize string\ntype: snippet\ntags: [string]\ncover: succulent-crowd\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nDecapitalizes the first letter of a string.\n\n- Use list slicing and `str.lower()` to decapitalize the first letter of the string.\n- Use `str.join()` to combine the lowercase first letter with the rest of the characters.\n- Omit the `upper_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to uppercase.\n\n```py\ndef decapitalize(s, upper_rest = False):\n  return ''.join([s[:1].lower(), (s[1:].upper() if upper_rest else s[1:])])\n```\n\n```py\ndecapitalize('FooBar') # 'fooBar'\ndecapitalize('FooBar', True) # 'fOOBAR'\n```\n"
  },
  {
    "path": "snippets/deep-flatten.md",
    "content": "---\ntitle: Deep flatten list\ntype: snippet\ntags: [list,recursion]\ncover: mask-quiet\ndateModified: 2020-12-29T19:53:45+02:00\n---\n\nDeep flattens a list.\n\n- Use recursion.\n- Use `isinstance()` with `collections.abc.Iterable` to check if an element is iterable.\n- If it is iterable, apply `deep_flatten()` recursively, otherwise return `[lst]`.\n\n```py\nfrom collections.abc import Iterable\n\ndef deep_flatten(lst):\n  return ([a for i in lst for a in\n          deep_flatten(i)] if isinstance(lst, Iterable) else [lst])\n```\n\n```py\ndeep_flatten([1, [2], [[3], 4], 5]) # [1, 2, 3, 4, 5]\n```\n"
  },
  {
    "path": "snippets/degrees-to-rads.md",
    "content": "---\ntitle: Degrees to radians\ntype: snippet\ntags: [math]\ncover: digital-nomad-6\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nConverts an angle from degrees to radians.\n\n- Use `math.pi` and the degrees to radians formula to convert the angle from degrees to radians.\n\n```py\nfrom math import pi\n\ndef degrees_to_rads(deg):\n  return (deg * pi) / 180.0\n```\n\n```py\ndegrees_to_rads(180) # ~3.1416\n```\n"
  },
  {
    "path": "snippets/delay.md",
    "content": "---\ntitle: Delayed function execution\ntype: snippet\ntags: [function]\ncover: succulent-10\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nInvokes the provided function after `ms` milliseconds.\n\n- Use `time.sleep()` to delay the execution of `fn` by `ms / 1000` seconds.\n\n```py\nfrom time import sleep\n\ndef delay(fn, ms, *args):\n  sleep(ms / 1000)\n  return fn(*args)\n```\n\n```py\ndelay(lambda x: print(x), 1000, 'later') # prints 'later' after one second\n```\n"
  },
  {
    "path": "snippets/dict-to-list.md",
    "content": "---\ntitle: Dictionary to list\ntype: snippet\ntags: [dictionary,list]\ncover: new-york\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nConverts a dictionary to a list of tuples.\n\n- Use `dict.items()` and `list()` to get a list of tuples from the given dictionary.\n\n```py\ndef dict_to_list(d):\n  return list(d.items())\n```\n\n```py\nd = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}\ndict_to_list(d)\n# [('one', 1), ('three', 3), ('five', 5), ('two', 2), ('four', 4)]\n```\n"
  },
  {
    "path": "snippets/difference-by.md",
    "content": "---\ntitle: List difference based on function\ntype: snippet\ntags: [list,function]\ncover: coconuts\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nReturns the difference between two lists, after applying the provided function to each list element of both.\n\n- Create a `set`, using `map()` to apply `fn` to each element in `b`.\n- Use a list comprehension in combination with `fn` on `a` to only keep values not contained in the previously created set, `_b`.\n\n```py\ndef difference_by(a, b, fn):\n  _b = set(map(fn, b))\n  return [item for item in a if fn(item) not in _b]\n```\n\n```py\nfrom math import floor\n\ndifference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2]\ndifference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x'])\n# [ { x: 2 } ]\n```\n"
  },
  {
    "path": "snippets/difference.md",
    "content": "---\ntitle: List difference\ntype: snippet\ntags: [list]\ncover: frog-blue-flower\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nCalculates the difference between two iterables, without filtering duplicate values.\n\n- Create a `set` from `b`.\n- Use a list comprehension on `a` to only keep values not contained in the previously created set, `_b`.\n\n```py\ndef difference(a, b):\n  _b = set(b)\n  return [item for item in a if item not in _b]\n```\n\n```py\ndifference([1, 2, 3], [1, 2, 4]) # [3]\n```\n"
  },
  {
    "path": "snippets/digitize.md",
    "content": "---\ntitle: Digitize number\ntype: snippet\ntags: [math,list]\ncover: laptop-with-code\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nConverts a number to a list of digits.\n\n- Use `map()` combined with `int` on the string representation of `n` and return a list from the result.\n\n```py\ndef digitize(n):\n  return list(map(int, str(n)))\n```\n\n```py\ndigitize(123) # [1, 2, 3]\n```\n"
  },
  {
    "path": "snippets/drop-right.md",
    "content": "---\ntitle: Drop list elements from the right\ntype: snippet\ntags: [list]\nauthor: chalarangelo\ncover: digital-nomad-7\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nReturns a list with `n` elements removed from the right.\n\n- Use slice notation to remove the specified number of elements from the right.\n- Omit the last argument, `n`, to use a default value of `1`.\n\n```py\ndef drop_right(a, n = 1):\n  return a[:-n]\n```\n\n```py\ndrop_right([1, 2, 3]) # [1, 2]\ndrop_right([1, 2, 3], 2) # [1]\ndrop_right([1, 2, 3], 42) # []\n```\n"
  },
  {
    "path": "snippets/drop.md",
    "content": "---\ntitle: Drop list elements from the left\ntype: snippet\ntags: [list]\nauthor: chalarangelo\ncover: pink-flower\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nReturns a list with `n` elements removed from the left.\n\n- Use slice notation to remove the specified number of elements from the left.\n- Omit the last argument, `n`, to use a default value of `1`.\n\n```py\ndef drop(a, n = 1):\n  return a[n:]\n```\n\n```py\ndrop([1, 2, 3]) # [2, 3]\ndrop([1, 2, 3], 2) # [3]\ndrop([1, 2, 3], 42) # []\n```\n"
  },
  {
    "path": "snippets/every-nth.md",
    "content": "---\ntitle: Every nth element in list\ntype: snippet\ntags: [list]\ncover: cherry-trees\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nReturns every `nth` element in a list.\n\n- Use slice notation to create a new list that contains every `nth` element of the given list.\n\n```py\ndef every_nth(lst, nth):\n  return lst[nth - 1::nth]\n```\n\n```py\nevery_nth([1, 2, 3, 4, 5, 6], 2) # [ 2, 4, 6 ]\n```\n"
  },
  {
    "path": "snippets/every.md",
    "content": "---\ntitle: Test if every list element is truthy\ntype: snippet\ntags: [list]\ncover: walking\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nChecks if the provided function returns `True` for every element in the list.\n\n- Use `all()` in combination with `map()` and `fn` to check if `fn` returns `True` for all elements in the list.\n\n```py\ndef every(lst, fn = lambda x: x):\n  return all(map(fn, lst))\n```\n\n```py\nevery([4, 2, 3], lambda x: x > 1) # True\nevery([1, 2, 3]) # True\n```\n"
  },
  {
    "path": "snippets/factorial.md",
    "content": "---\ntitle: Factorial\ntype: snippet\ntags: [math,recursion]\ncover: succulent-11\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nCalculates the factorial of a number.\n\n- Use recursion.\n- If `num` is less than or equal to `1`, return `1`.\n- Otherwise, return the product of `num` and the factorial of `num - 1`.\n- Throws an exception if `num` is a negative or a floating point number.\n\n```py\ndef factorial(num):\n  if not ((num >= 0) and (num % 1 == 0)):\n    raise Exception(\"Number can't be floating point or negative.\")\n  return 1 if num == 0 else num * factorial(num - 1)\n```\n\n```py\nfactorial(6) # 720\n```\n"
  },
  {
    "path": "snippets/fahrenheit-to-celsius.md",
    "content": "---\ntitle: Fahrenheit to Celsius\ntype: snippet\ntags: [math]\nunlisted: true\ncover: last-light\ndateModified: 2021-01-04T12:47:04+02:00\n---\n\nConverts Fahrenheit to Celsius.\n\n- Follow the conversion formula `C = (F - 32) * 5 / 9`.\n\n```py\ndef fahrenheit_to_celsius(degrees):\n  return ((degrees - 32) * 5 / 9)\n```\n\n```py\nfahrenheit_to_celsius(77) # 25.0\n```\n"
  },
  {
    "path": "snippets/fibonacci.md",
    "content": "---\ntitle: Fibonacci\ntype: snippet\ntags: [math,list]\ncover: san-francisco-skyline\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nGenerates a list, containing the Fibonacci sequence, up until the nth term.\n\n- Starting with `0` and `1`, use `list.append()` to add the sum of the last two numbers of the list to the end of the list, until the length of the list reaches `n`.\n- If `n` is less or equal to `0`, return a list containing `0`.\n\n```py\ndef fibonacci(n):\n  if n <= 0:\n    return [0]\n  sequence = [0, 1]\n  while len(sequence) <= n:\n    next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]\n    sequence.append(next_value)\n  return sequence\n```\n\n```py\nfibonacci(7) # [0, 1, 1, 2, 3, 5, 8, 13]\n```\n"
  },
  {
    "path": "snippets/filter-non-unique.md",
    "content": "---\ntitle: Filter non-unique list values\ntype: snippet\ntags: [list]\ncover: cobbled-street\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nCreates a list with the non-unique values filtered out.\n\n- Use `collections.Counter` to get the count of each value in the list.\n- Use a list comprehension to create a list containing only the unique values.\n\n```py\nfrom collections import Counter\n\ndef filter_non_unique(lst):\n  return [item for item, count in Counter(lst).items() if count == 1]\n```\n\n```py\nfilter_non_unique([1, 2, 2, 3, 4, 4, 5]) # [1, 3, 5]\n```\n"
  },
  {
    "path": "snippets/filter-unique.md",
    "content": "---\ntitle: Filter unique list values\ntype: snippet\ntags: [list]\ncover: feathers\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nCreates a list with the unique values filtered out.\n\n- Use `collections.Counter` to get the count of each value in the list.\n- Use a list comprehension to create a list containing only the non-unique values.\n\n```py\nfrom collections import Counter\n\ndef filter_unique(lst):\n  return [item for item, count in Counter(lst).items() if count > 1]\n```\n\n```py\nfilter_unique([1, 2, 2, 3, 4, 4, 5]) # [2, 4]\n```\n"
  },
  {
    "path": "snippets/find-index-of-all.md",
    "content": "---\ntitle: Find all matching indexes\ntype: snippet\ntags: [list]\ncover: tree-roots\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nFinds the indexes of all elements in the given list that satisfy the provided testing function.\n\n- Use `enumerate()` and a list comprehension to return the indexes of the all element in `lst` for which `fn` returns `True`.\n\n```py\ndef find_index_of_all(lst, fn):\n  return [i for i, x in enumerate(lst) if fn(x)]\n```\n\n```py\nfind_index_of_all([1, 2, 3, 4], lambda n: n % 2 == 1) # [0, 2]\n```\n"
  },
  {
    "path": "snippets/find-index.md",
    "content": "---\ntitle: Find matching index\ntype: snippet\ntags: [list]\ncover: book-chair\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nFinds the index of the first element in the given list that satisfies the provided testing function.\n\n- Use a list comprehension, `enumerate()` and `next()` to return the index of the first element in `lst` for which `fn` returns `True`.\n\n```py\ndef find_index(lst, fn):\n  return next(i for i, x in enumerate(lst) if fn(x))\n```\n\n```py\nfind_index([1, 2, 3, 4], lambda n: n % 2 == 1) # 0\n```\n"
  },
  {
    "path": "snippets/find-key.md",
    "content": "---\ntitle: Find key of value\ntype: snippet\ntags: [dictionary]\ncover: blue-red-mountain\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nFinds the first key in the provided dictionary that has the given value.\n\n- Use `dictionary.items()` and `next()` to return the first key that has a value equal to `val`.\n\n```py\ndef find_key(dict, val):\n  return next(key for key, value in dict.items() if value == val)\n```\n\n```py\nages = {\n  'Peter': 10,\n  'Isabel': 11,\n  'Anna': 9,\n}\nfind_key(ages, 11) # 'Isabel'\n```\n"
  },
  {
    "path": "snippets/find-keys.md",
    "content": "---\ntitle: Find keys with value\ntype: snippet\ntags: [dictionary]\ncover: laptop-plants-2\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nFinds all keys in the provided dictionary that have the given value.\n\n- Use `dictionary.items()`, a generator and `list()` to return all keys that have a value equal to `val`.\n\n```py\ndef find_keys(dict, val):\n  return list(key for key, value in dict.items() if value == val)\n```\n\n```py\nages = {\n  'Peter': 10,\n  'Isabel': 11,\n  'Anna': 10,\n}\nfind_keys(ages, 10) # [ 'Peter', 'Anna' ]\n```\n"
  },
  {
    "path": "snippets/find-last-index.md",
    "content": "---\ntitle: Find last matching index\ntype: snippet\ntags: [list]\ncover: succulent-8\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nFinds the index of the last element in the given list that satisfies the provided testing function.\n\n- Use a list comprehension, `enumerate()` and `next()` to return the index of the last element in `lst` for which `fn` returns `True`.\n\n```py\ndef find_last_index(lst, fn):\n  return len(lst) - 1 - next(i for i, x in enumerate(lst[::-1]) if fn(x))\n```\n\n```py\nfind_last_index([1, 2, 3, 4], lambda n: n % 2 == 1) # 2\n```\n"
  },
  {
    "path": "snippets/find-last.md",
    "content": "---\ntitle: Find last matching value\ntype: snippet\ntags: [list]\ncover: tropical-waterfall\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nFinds the value of the last element in the given list that satisfies the provided testing function.\n\n- Use a list comprehension and `next()` to return the last element in `lst` for which `fn` returns `True`.\n\n```py\ndef find_last(lst, fn):\n  return next(x for x in lst[::-1] if fn(x))\n```\n\n```py\nfind_last([1, 2, 3, 4], lambda n: n % 2 == 1) # 3\n```\n"
  },
  {
    "path": "snippets/find-parity-outliers.md",
    "content": "---\ntitle: Find parity outliers\ntype: snippet\ntags: [list,math]\ncover: beach-pineapple\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nFinds the items that are parity outliers in a given list.\n\n- Use `collections.Counter` with a list comprehension to count even and odd values in the list.\n- Use `collections.Counter.most_common()` to get the most common parity.\n- Use a list comprehension to find all elements that do not match the most common parity.\n\n```py\nfrom collections import Counter\n\ndef find_parity_outliers(nums):\n  return [\n    x for x in nums\n    if x % 2 != Counter([n % 2 for n in nums]).most_common()[0][0]\n  ]\n```\n\n```py\nfind_parity_outliers([1, 2, 3, 4, 6]) # [1, 3]\n```\n"
  },
  {
    "path": "snippets/find.md",
    "content": "---\ntitle: Find matching value\ntype: snippet\ntags: [list]\ncover: duck-plants\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nFinds the value of the first element in the given list that satisfies the provided testing function.\n\n- Use a list comprehension and `next()` to return the first element in `lst` for which `fn` returns `True`.\n\n```py\ndef find(lst, fn):\n  return next(x for x in lst if fn(x))\n```\n\n```py\nfind([1, 2, 3, 4], lambda n: n % 2 == 1) # 1\n```\n"
  },
  {
    "path": "snippets/flatten.md",
    "content": "---\ntitle: Flatten list\ntype: snippet\ntags: [list]\ncover: jars-on-shelf\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nFlattens a list of lists once.\n\n- Use a list comprehension to extract each value from sub-lists in order.\n\n```py\ndef flatten(lst):\n  return [x for y in lst for x in y]\n```\n\n```py\nflatten([[1, 2, 3, 4], [5, 6, 7, 8]]) # [1, 2, 3, 4, 5, 6, 7, 8]\n```\n"
  },
  {
    "path": "snippets/for-each-right.md",
    "content": "---\ntitle: Execute function for each list element in reverse\ntype: snippet\ntags: [list]\ncover: bridge-drop\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nExecutes the provided function once for each list element, starting from the list's last element.\n\n- Use a `for` loop in combination with slice notation to execute `fn` for each element in `itr`, starting from the last one.\n\n```py\ndef for_each_right(itr, fn):\n  for el in itr[::-1]:\n    fn(el)\n```\n\n```py\nfor_each_right([1, 2, 3], print) # 3 2 1\n```\n"
  },
  {
    "path": "snippets/for-each.md",
    "content": "---\ntitle: Execute function for each list element\ntype: snippet\ntags: [list]\ncover: green-plant\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nExecutes the provided function once for each list element.\n\n- Use a `for` loop to execute `fn` for each element in `itr`.\n\n```py\ndef for_each(itr, fn):\n  for el in itr:\n    fn(el)\n```\n\n```py\nfor_each([1, 2, 3], print) # 1 2 3\n```\n"
  },
  {
    "path": "snippets/frequencies.md",
    "content": "---\ntitle: Value frequencies\ntype: snippet\ntags: [list]\ncover: succulent-6\ndateModified: 2020-11-02T19:27:53+02:00\n---\n\nCreates a dictionary with the unique values of a list as keys and their frequencies as the values.\n\n- Use `collections.defaultdict` to store the frequencies of each unique element.\n- Use `dict()` to return a dictionary with the unique elements of the list as keys and their frequencies as the values.\n\n```py\nfrom collections import defaultdict\n\ndef frequencies(lst):\n  freq = defaultdict(int)\n  for val in lst:\n    freq[val] += 1\n  return dict(freq)\n```\n\n```py\nfrequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']) # { 'a': 4, 'b': 2, 'c': 1 }\n```\n"
  },
  {
    "path": "snippets/from-iso-date.md",
    "content": "---\ntitle: Date from ISO format\ntype: snippet\ntags: [date]\ncover: purple-leaves\ndateModified: 2021-01-07T23:30:28+02:00\n---\n\nConverts a date from its ISO-8601 representation.\n\n- Use `datetime.datetime.fromisoformat()` to convert the given ISO-8601 date to a `datetime.datetime` object.\n\n```py\nfrom datetime import datetime\n\ndef from_iso_date(d):\n  return datetime.fromisoformat(d)\n```\n\n```py\nfrom_iso_date('2020-10-28T12:30:59.000000') # 2020-10-28 12:30:59\n```\n"
  },
  {
    "path": "snippets/gcd.md",
    "content": "---\ntitle: Greatest common divisor\ntype: snippet\ntags: [math]\ncover: digital-nomad-12\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nCalculates the greatest common divisor of a list of numbers.\n\n- Use `functools.reduce()` and `math.gcd()` over the given list.\n\n```py\nfrom functools import reduce\nfrom math import gcd as _gcd\n\ndef gcd(numbers):\n  return reduce(_gcd, numbers)\n```\n\n```py\ngcd([8, 36, 28]) # 4\n```\n"
  },
  {
    "path": "snippets/geometric-progression.md",
    "content": "---\ntitle: Geometric progression\ntype: snippet\ntags: [math,list]\ncover: kettle-laptop\nexcerpt: Initializes a list containing the numbers in the specified geometric progression range.\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nInitializes a list containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`.\n\n- Use `range()`, `math.log()` and `math.floor()` and a list comprehension to create a list of the appropriate length, applying the step for each element.\n- Returns an error if `step` equals `1`.\n- Omit the second argument, `start`, to use a default value of `1`.\n- Omit the third argument, `step`, to use a default value of `2`.\n\n```py\nfrom math import floor, log\n\ndef geometric_progression(end, start=1, step=2):\n  return [start * step ** i for i in range(floor(log(end / start)\n          / log(step)) + 1)]\n```\n\n```py\ngeometric_progression(256) # [1, 2, 4, 8, 16, 32, 64, 128, 256]\ngeometric_progression(256, 3) # [3, 6, 12, 24, 48, 96, 192]\ngeometric_progression(256, 1, 4) # [1, 4, 16, 64, 256]\n```\n"
  },
  {
    "path": "snippets/get.md",
    "content": "---\ntitle: Get nested value\ntype: snippet\ntags: [dictionary,list]\ncover: digital-nomad-2\ndateModified: 2020-10-28T12:21:39+02:00\n---\n\nRetrieves the value of the nested key indicated by the given selector list from a dictionary or list.\n\n- Use `functools.reduce()` to iterate over the `selectors` list.\n- Apply `operator.getitem()` for each key in `selectors`, retrieving the value to be used as the iteratee for the next iteration.\n\n```py\nfrom functools import reduce\nfrom operator import getitem\n\ndef get(d, selectors):\n  return reduce(getitem, selectors, d)\n```\n\n```py\nusers = {\n  'freddy': {\n    'name': {\n      'first': 'fred',\n      'last': 'smith'\n    },\n    'postIds': [1, 2, 3]\n  }\n}\nget(users, ['freddy', 'name', 'last']) # 'smith'\nget(users, ['freddy', 'postIds', 1]) # 2\n```\n"
  },
  {
    "path": "snippets/group-by.md",
    "content": "---\ntitle: Group list elements\ntype: snippet\ntags: [list,dictionary]\ncover: body-of-water\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nGroups the elements of a list based on the given function.\n\n- Use `collections.defaultdict` to initialize a dictionary.\n- Use `fn` in combination with a `for` loop and `dict.append()` to populate the dictionary.\n- Use `dict()` to convert it to a regular dictionary.\n\n```py\nfrom collections import defaultdict\n\ndef group_by(lst, fn):\n  d = defaultdict(list)\n  for el in lst:\n    d[fn(el)].append(el)\n  return dict(d)\n```\n\n```py\nfrom math import floor\n\ngroup_by([6.1, 4.2, 6.3], floor) # {4: [4.2], 6: [6.1, 6.3]}\ngroup_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}\n```\n"
  },
  {
    "path": "snippets/hamming-distance.md",
    "content": "---\ntitle: Hamming distance\ntype: snippet\ntags: [math]\ncover: tulips-and-reeds\ndateModified: 2021-02-18T14:22:25+02:00\n---\n\nCalculates the Hamming distance between two values.\n\n- Use the XOR operator (`^`) to find the bit difference between the two numbers.\n- Use `bin()` to convert the result to a binary string.\n- Convert the string to a list and use `count()` of `str` class to count and return the number of `1`s in it.\n\n```py\ndef hamming_distance(a, b):\n  return bin(a ^ b).count('1')\n```\n\n```py\nhamming_distance(2, 3) # 1\n```\n"
  },
  {
    "path": "snippets/has-duplicates.md",
    "content": "---\ntitle: Check for duplicates in list\ntype: snippet\ntags: [list]\ncover: jars-on-shelf-2\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nChecks if there are duplicate values in a flat list.\n\n- Use `set()` on the given list to remove duplicates, compare its length with the length of the list.\n\n```py\ndef has_duplicates(lst):\n  return len(lst) != len(set(lst))\n```\n\n```py\nx = [1, 2, 3, 4, 5, 5]\ny = [1, 2, 3, 4, 5]\nhas_duplicates(x) # True\nhas_duplicates(y) # False\n```\n"
  },
  {
    "path": "snippets/have-same-contents.md",
    "content": "---\ntitle: Check lists have same contents\ntype: snippet\ntags: [list]\ncover: racoon\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nChecks if two lists contain the same elements regardless of order.\n\n- Use `set()` on the combination of both lists to find the unique values.\n- Iterate over them with a `for` loop comparing the `count()` of each unique value in each list.\n- Return `False` if the counts do not match for any element, `True` otherwise.\n\n```py\ndef have_same_contents(a, b):\n  for v in set(a + b):\n    if a.count(v) != b.count(v):\n      return False\n  return True\n```\n\n```py\nhave_same_contents([1, 2, 4], [2, 4, 1]) # True\n```\n"
  },
  {
    "path": "snippets/head.md",
    "content": "---\ntitle: List head\ntype: snippet\ntags: [list]\ncover: purple-laptop\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nReturns the head of a list.\n\n- Use `lst[0]` to return the first element of the passed list.\n\n```py\ndef head(lst):\n  return lst[0]\n```\n\n```py\nhead([1, 2, 3]) # 1\n```\n"
  },
  {
    "path": "snippets/hex-to-rgb.md",
    "content": "---\ntitle: Hex to RGB\ntype: snippet\ntags: [string,math]\ncover: sleepy-cat\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nConverts a hexadecimal color code to a tuple of integers corresponding to its RGB components.\n\n- Use a list comprehension in combination with `int()` and list slice notation to get the RGB components from the hexadecimal string.\n- Use `tuple()` to convert the resulting list to a tuple.\n\n```py\ndef hex_to_rgb(hex):\n  return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))\n```\n\n```py\nhex_to_rgb('FFA501') # (255, 165, 1)\n```\n"
  },
  {
    "path": "snippets/in-range.md",
    "content": "---\ntitle: Number in range\ntype: snippet\ntags: [math]\ncover: pineapple-on-green\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nChecks if the given number falls within the given range.\n\n- Use arithmetic comparison to check if the given number is in the specified range.\n- If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`.\n\n```py\ndef in_range(n, start, end = 0):\n  return start <= n <= end if end >= start else end <= n <= start\n```\n\n```py\nin_range(3, 2, 5) # True\nin_range(3, 4) # True\nin_range(2, 3, 5) # False\nin_range(3, 2) # False\n```\n"
  },
  {
    "path": "snippets/includes-all.md",
    "content": "---\ntitle: List includes all values\ntype: snippet\ntags: [list]\ncover: switzerland-night\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nChecks if all the elements in `values` are included in `lst`.\n\n- Check if every value in `values` is contained in `lst` using a `for` loop.\n- Return `False` if any one value is not found, `True` otherwise.\n\n```py\ndef includes_all(lst, values):\n  for v in values:\n    if v not in lst:\n      return False\n  return True\n```\n\n```py\nincludes_all([1, 2, 3, 4], [1, 4]) # True\nincludes_all([1, 2, 3, 4], [1, 5]) # False\n```\n"
  },
  {
    "path": "snippets/includes-any.md",
    "content": "---\ntitle: List includes any values\ntype: snippet\ntags: [list]\ncover: forest-balcony\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nChecks if any element in `values` is included in `lst`.\n\n- Check if any value in `values` is contained in `lst` using a `for` loop.\n- Return `True` if any one value is found, `False` otherwise.\n\n```py\ndef includes_any(lst, values):\n  for v in values:\n    if v in lst:\n      return True\n  return False\n```\n\n```py\nincludes_any([1, 2, 3, 4], [2, 9]) # True\nincludes_any([1, 2, 3, 4], [8, 9]) # False\n```\n"
  },
  {
    "path": "snippets/index-of-all.md",
    "content": "---\ntitle: All indexes of value\ntype: snippet\ntags: [list]\ncover: purple-flower-bunch\ndateModified: 2020-10-11T13:45:19+03:00\n---\n\nReturns a list of indexes of all the occurrences of an element in a list.\n\n- Use `enumerate()` and a list comprehension to check each element for equality with `value` and adding `i` to the result.\n\n```py\ndef index_of_all(lst, value):\n  return [i for i, x in enumerate(lst) if x == value]\n```\n\n```py\nindex_of_all([1, 2, 1, 4, 5, 1], 1) # [0, 2, 5]\nindex_of_all([1, 2, 3, 4], 6) # []\n```\n"
  },
  {
    "path": "snippets/initial.md",
    "content": "---\ntitle: List without last element\ntype: snippet\ntags: [list]\ncover: pop-of-green\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nReturns all the elements of a list except the last one.\n\n- Use `lst[:-1]` to return all but the last element of the list.\n\n```py\ndef initial(lst):\n  return lst[:-1]\n```\n\n```py\ninitial([1, 2, 3]) # [1, 2]\n```\n"
  },
  {
    "path": "snippets/initialize-2-d-list.md",
    "content": "---\ntitle: Initialize 2D list\ntype: snippet\ntags: [list]\ncover: succulent-7\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nInitializes a 2D list of given width and height and value.\n\n- Use a list comprehension and `range()` to generate `h` rows where each is a list with length `h`, initialized with `val`.\n- Omit the last argument, `val`, to set the default value to `None`.\n\n```py\ndef initialize_2d_list(w, h, val = None):\n  return [[val for x in range(w)] for y in range(h)]\n```\n\n```py\ninitialize_2d_list(2, 2, 0) # [[0, 0], [0, 0]]\n```\n"
  },
  {
    "path": "snippets/initialize-list-with-range.md",
    "content": "---\ntitle: Initialize list with range\ntype: snippet\ntags: [list]\ncover: succulent-3\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nInitializes a list containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`.\n\n- Use `list()` and `range()` to generate a list of the appropriate length, filled with the desired values in the given range.\n- Omit `start` to use the default value of `0`.\n- Omit `step` to use the default value of `1`.\n\n```py\ndef initialize_list_with_range(end, start = 0, step = 1):\n  return list(range(start, end + 1, step))\n```\n\n```py\ninitialize_list_with_range(5) # [0, 1, 2, 3, 4, 5]\ninitialize_list_with_range(7, 3) # [3, 4, 5, 6, 7]\ninitialize_list_with_range(9, 0, 2) # [0, 2, 4, 6, 8]\n```\n"
  },
  {
    "path": "snippets/initialize-list-with-values.md",
    "content": "---\ntitle: Initialize list with values\ntype: snippet\ntags: [list]\ncover: dog-waiting\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nInitializes and fills a list with the specified value.\n\n- Use a list comprehension and `range()` to generate a list of length equal to `n`, filled with the desired values.\n- Omit `val` to use the default value of `0`.\n\n```py\ndef initialize_list_with_values(n, val = 0):\n  return [val for x in range(n)]\n```\n\n```py\ninitialize_list_with_values(5, 2) # [2, 2, 2, 2, 2]\n```\n"
  },
  {
    "path": "snippets/intersection-by.md",
    "content": "---\ntitle: List intersection based on function\ntype: snippet\ntags: [list,function]\ncover: duck-plants\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nReturns a list of elements that exist in both lists, after applying the provided function to each list element of both.\n\n- Create a `set`, using `map()` to apply `fn` to each element in `b`.\n- Use a list comprehension in combination with `fn` on `a` to only keep values contained in both lists.\n\n```py\ndef intersection_by(a, b, fn):\n  _b = set(map(fn, b))\n  return [item for item in a if fn(item) in _b]\n```\n\n```py\nfrom math import floor\n\nintersection_by([2.1, 1.2], [2.3, 3.4], floor) # [2.1]\n```\n"
  },
  {
    "path": "snippets/intersection.md",
    "content": "---\ntitle: List intersection\ntype: snippet\ntags: [list]\ncover: wooden-bowl\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nReturns a list of elements that exist in both lists.\n\n- Create a `set` from `a` and `b`.\n- Use the built-in set operator `&` to only keep values contained in both sets, then transform the `set` back into a `list`.\n\n```py\ndef intersection(a, b):\n  _a, _b = set(a), set(b)\n  return list(_a & _b)\n```\n\n```py\nintersection([1, 2, 3], [4, 3, 2]) # [2, 3]\n```\n"
  },
  {
    "path": "snippets/invert-dictionary.md",
    "content": "---\ntitle: Invert dictionary\ntype: snippet\ntags: [dictionary]\ncover: rustic-cup\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nInverts a dictionary with unique hashable values.\n\n- Use `dictionary.items()` in combination with a list comprehension to create a new dictionary with the values and keys inverted.\n\n```py\ndef invert_dictionary(obj):\n  return { value: key for key, value in obj.items() }\n```\n\n```py\nages = {\n  'Peter': 10,\n  'Isabel': 11,\n  'Anna': 9,\n}\ninvert_dictionary(ages) # { 10: 'Peter', 11: 'Isabel', 9: 'Anna' }\n```\n"
  },
  {
    "path": "snippets/is-anagram.md",
    "content": "---\ntitle: String is anagram\ntype: snippet\ntags: [string]\ncover: digital-nomad-8\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nChecks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).\n\n- Use `str.isalnum()` to filter out non-alphanumeric characters, `str.lower()` to transform each character to lowercase.\n- Use `collections.Counter` to count the resulting characters for each string and compare the results.\n\n```py\nfrom collections import Counter\n\ndef is_anagram(s1, s2):\n  return Counter(\n    c.lower() for c in s1 if c.isalnum()\n  ) == Counter(\n    c.lower() for c in s2 if c.isalnum()\n  )\n```\n\n```py\nis_anagram('#anagram', 'Nag a ram!')  # True\n```\n"
  },
  {
    "path": "snippets/is-contained-in.md",
    "content": "---\ntitle: List is contained in other list\ntype: snippet\ntags: [list]\ncover: tropical-bike\ndateModified: 2021-01-07T23:30:28+02:00\n---\n\nChecks if the elements of the first list are contained in the second one regardless of order.\n\n- Use `count()` to check if any value in `a` has more occurrences than it has in `b`.\n- Return `False` if any such value is found, `True` otherwise.\n\n```py\ndef is_contained_in(a, b):\n  for v in set(a):\n    if a.count(v) > b.count(v):\n      return False\n  return True\n```\n\n```py\nis_contained_in([1, 4], [2, 4, 1]) # True\n```\n"
  },
  {
    "path": "snippets/is-divisible.md",
    "content": "---\ntitle: Number is divisible\ntype: snippet\ntags: [math]\nunlisted: true\ncover: interior-9\ndateModified: 2021-01-04T12:47:04+02:00\n---\n\nChecks if the first numeric argument is divisible by the second one.\n\n- Use the modulo operator (`%`) to check if the remainder is equal to `0`.\n\n```py\ndef is_divisible(dividend, divisor):\n  return dividend % divisor == 0\n```\n\n```py\nis_divisible(6, 3) # True\n```\n"
  },
  {
    "path": "snippets/is-empty.md",
    "content": "---\r\ntitle: Collection is empty\r\ntype: snippet\r\ntags: [list,dictionary,string]\r\nauthor: chalarangelo\r\ncover: salad-1\r\ndateModified: 2023-01-12T05:00:00-04:00\r\n---\r\n\r\nChecks if the a value is an empty sequence or collection.\r\n\r\n- Use `not` to test the truth value of the provided sequence or collection.\r\n\r\n```py\r\ndef is_empty(val):\r\n  return not val\r\n```\r\n\r\n```py\r\nis_empty([]) # True\r\nis_empty({}) # True\r\nis_empty('') # True\r\nis_empty(set()) # True\r\nis_empty(range(0)) # True\r\nis_empty([1, 2]) # False\r\nis_empty({ 'a': 1, 'b': 2 }) # False\r\nis_empty('text') # False\r\nis_empty(set([1, 2])) # False\r\nis_empty(range(2)) # False\r\n```\r\n"
  },
  {
    "path": "snippets/is-even.md",
    "content": "---\ntitle: Number is even\ntype: snippet\ntags: [math]\nunlisted: true\ncover: interior-3\ndateModified: 2021-01-04T12:47:04+02:00\n---\n\nChecks if the given number is even.\n\n- Check whether a number is odd or even using the modulo (`%`) operator.\n- Return `True` if the number is even, `False` if the number is odd.\n\n```py\ndef is_even(num):\n  return num % 2 == 0\n```\n\n```py\nis_even(3) # False\n```\n"
  },
  {
    "path": "snippets/is-odd.md",
    "content": "---\ntitle: Number is odd\ntype: snippet\ntags: [math]\nunlisted: true\ncover: interior-6\ndateModified: 2021-01-04T12:47:04+02:00\n---\n\nChecks if the given number is odd.\n\n- Checks whether a number is even or odd using the modulo (`%`) operator.\n- Returns `True` if the number is odd, `False` if the number is even.\n\n```py\ndef is_odd(num):\n  return num % 2 != 0\n```\n\n```py\nis_odd(3) # True\n```\n"
  },
  {
    "path": "snippets/is-prime.md",
    "content": "---\ntitle: Number is prime\ntype: snippet\ntags: [math]\ncover: carrots\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nChecks if the provided integer is a prime number.\n\n- Return `False` if the number is `0`, `1`, a negative number or a multiple of `2`.\n- Use `all()` and `range()` to check numbers from `3` to the square root of the given number.\n- Return `True` if none divides the given number, `False` otherwise.\n\n```py\nfrom math import sqrt\n\ndef is_prime(n):\n  if n <= 1 or (n % 2 == 0 and n > 2):\n    return False\n  return all(n % i for i in range(3, int(sqrt(n)) + 1, 2))\n```\n\n```py\nis_prime(11) # True\n```\n"
  },
  {
    "path": "snippets/is-weekday.md",
    "content": "---\ntitle: Date is weekday\ntype: snippet\ntags: [date]\ncover: succulent-4\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nChecks if the given date is a weekday.\n\n- Use `datetime.datetime.weekday()` to get the day of the week as an integer.\n- Check if the day of the week is less than or equal to `4`.\n- Omit the second argument, `d`, to use a default value of `datetime.today()`.\n\n```py\nfrom datetime import datetime\n\ndef is_weekday(d = datetime.today()):\n  return d.weekday() <= 4\n```\n\n```py\nfrom datetime import date\n\nis_weekday(date(2020, 10, 25)) # False\nis_weekday(date(2020, 10, 28)) # True\n```\n"
  },
  {
    "path": "snippets/is-weekend.md",
    "content": "---\ntitle: Date is weekend\ntype: snippet\ntags: [date]\ncover: two-lighthouses\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nChecks if the given date is a weekend.\n\n- Use `datetime.datetime.weekday()` to get the day of the week as an integer.\n- Check if the day of the week is greater than `4`.\n- Omit the second argument, `d`, to use a default value of `datetime.today()`.\n\n```py\nfrom datetime import datetime\n\ndef is_weekend(d = datetime.today()):\n  return d.weekday() > 4\n```\n\n```py\nfrom datetime import date\n\nis_weekend(date(2020, 10, 25)) # True\nis_weekend(date(2020, 10, 28)) # False\n```\n"
  },
  {
    "path": "snippets/kebab.md",
    "content": "---\ntitle: Kebabcase string\ntype: snippet\ntags: [string,regexp]\ncover: mask-quiet\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nConverts a string to kebab case.\n\n- Use `re.sub()` to replace any `-` or `_` with a space, using the regexp `r\"(_|-)+\"`.\n- Use `re.sub()` to match all words in the string, `str.lower()` to lowercase them.\n- Finally, use `str.join()` to combine all word using `-` as the separator.\n\n```py\nfrom re import sub\n\ndef kebab(s):\n  return '-'.join(\n    sub(r\"(\\s|_|-)+\",\" \",\n    sub(r\"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+\",\n    lambda mo: ' ' + mo.group(0).lower(), s)).split())\n```\n\n```py\nkebab('camelCase') # 'camel-case'\nkebab('some text') # 'some-text'\nkebab('some-mixed_string With spaces_underscores-and-hyphens')\n# 'some-mixed-string-with-spaces-underscores-and-hyphens'\nkebab('AllThe-small Things') # 'all-the-small-things'\n```\n"
  },
  {
    "path": "snippets/key-in-dict.md",
    "content": "---\ntitle: Key in dictionary\ntype: snippet\ntags: [dictionary]\ncover: rocky-mountains\ndateModified: 2020-10-16T21:30:49+03:00\n---\n\nChecks if the given key exists in a dictionary.\n\n- Use the `in` operator to check if `d` contains `key`.\n\n```py\ndef key_in_dict(d, key):\n  return (key in d)\n```\n\n```py\nd = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}\nkey_in_dict(d, 'three') # True\n```\n"
  },
  {
    "path": "snippets/key-of-max.md",
    "content": "---\ntitle: Key of max value\ntype: snippet\ntags: [dictionary]\ncover: succulent-7\ndateModified: 2021-01-07T23:15:48+02:00\n---\n\nFinds the key of the maximum value in a dictionary.\n\n- Use `max()` with the `key` parameter set to `dict.get()` to find and return the key of the maximum value in the given dictionary.\n\n```py\ndef key_of_max(d):\n  return max(d, key = d.get)\n```\n\n```py\nkey_of_max({'a':4, 'b':0, 'c':13}) # c\n```\n"
  },
  {
    "path": "snippets/key-of-min.md",
    "content": "---\ntitle: Key of min value\ntype: snippet\ntags: [dictionary]\ncover: goat-wooden-cottage\ndateModified: 2021-01-07T23:15:48+02:00\n---\n\nFinds the key of the minimum value in a dictionary.\n\n- Use `min()` with the `key` parameter set to `dict.get()` to find and return the key of the minimum value in the given dictionary.\n\n```py\ndef key_of_min(d):\n  return min(d, key = d.get)\n```\n\n```py\nkey_of_min({'a':4, 'b':0, 'c':13}) # b\n```\n"
  },
  {
    "path": "snippets/keys-only.md",
    "content": "---\ntitle: Dictionary keys\ntype: snippet\ntags: [dictionary,list]\ncover: succulent-5\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nCreates a flat list of all the keys in a flat dictionary.\n\n- Use `dict.keys()` to return the keys in the given dictionary.\n- Return a `list()` of the previous result.\n\n```py\ndef keys_only(flat_dict):\n  return list(flat_dict.keys())\n```\n\n```py\nages = {\n  'Peter': 10,\n  'Isabel': 11,\n  'Anna': 9,\n}\nkeys_only(ages) # ['Peter', 'Isabel', 'Anna']\n```\n"
  },
  {
    "path": "snippets/km-to-miles.md",
    "content": "---\ntitle: Km to miles\ntype: snippet\ntags: [math]\nunlisted: true\ncover: interior-5\ndateModified: 2021-01-04T12:47:04+02:00\n---\n\nConverts kilometers to miles.\n\n- Follows the conversion formula `mi = km * 0.621371`.\n\n```py\ndef km_to_miles(km):\n  return km * 0.621371\n```\n\n```py\nkm_to_miles(8.1) # 5.0331051\n```\n"
  },
  {
    "path": "snippets/last.md",
    "content": "---\ntitle: Last list element\ntype: snippet\ntags: [list]\ncover: lake-runner\ndateModified: 2020-11-02T19:28:05+02:00\n---\n\nReturns the last element in a list.\n\n- Use `lst[-1]` to return the last element of the passed list.\n\n```py\ndef last(lst):\n  return lst[-1]\n```\n\n```py\nlast([1, 2, 3]) # 3\n```\n"
  },
  {
    "path": "snippets/lcm.md",
    "content": "---\ntitle: Least common multiple\ntype: snippet\ntags: [math,list]\ncover: fruit-feast\ndateModified: 2020-11-02T19:31:15+02:00\n---\n\nReturns the least common multiple of a list of numbers.\n\n- Use `functools.reduce()`, `math.gcd()` and `lcm(x, y) = x * y / gcd(x, y)` over the given list.\n\n```py\nfrom functools import reduce\nfrom math import gcd\n\ndef lcm(numbers):\n  return reduce((lambda x, y: int(x * y / gcd(x, y))), numbers)\n```\n\n```py\nlcm([12, 7]) # 84\nlcm([1, 3, 4, 5]) # 60\n```\n"
  },
  {
    "path": "snippets/longest-item.md",
    "content": "---\ntitle: Longest item\ntype: snippet\ntags: [list,string]\ncover: keyboard-tea\ndateModified: 2021-10-17T18:24:43+02:00\n---\n\nTakes any number of iterable objects or objects with a length property and returns the longest one.\n\n- Use `max()` with `len()` as the `key` to return the item with the greatest length.\n- If multiple items have the same length, the first one will be returned.\n\n```py\ndef longest_item(*args):\n  return max(args, key = len)\n```\n\n```py\nlongest_item('this', 'is', 'a', 'testcase') # 'testcase'\nlongest_item([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]) # [1, 2, 3, 4, 5]\nlongest_item([1, 2, 3], 'foobar') # 'foobar'\n```\n"
  },
  {
    "path": "snippets/map-dictionary.md",
    "content": "---\ntitle: Map list to dictionary\ntype: snippet\ntags: [list,dictionary]\nexcerpt: Maps the values of a list to a dictionary using a function.\ncover: colors-mural\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nMaps the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value.\n\n- Use `map()` to apply `fn` to each value of the list.\n- Use `zip()` to pair original values to the values produced by `fn`.\n- Use `dict()` to return an appropriate dictionary.\n\n```py\ndef map_dictionary(itr, fn):\n  return dict(zip(itr, map(fn, itr)))\n```\n\n```py\nmap_dictionary([1, 2, 3], lambda x: x * x) # { 1: 1, 2: 4, 3: 9 }\n```\n"
  },
  {
    "path": "snippets/map-values.md",
    "content": "---\ntitle: Map dictionary values\ntype: snippet\ntags: [dictionary]\ncover: pineapple-laptop\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nCreates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value.\n\n- Use `dict.items()` to iterate over the dictionary, assigning the values produced by `fn` to each key of a new dictionary.\n\n```py\ndef map_values(obj, fn):\n  return dict((k, fn(v)) for k, v in obj.items())\n```\n\n```py\nusers = {\n  'fred': { 'user': 'fred', 'age': 40 },\n  'pebbles': { 'user': 'pebbles', 'age': 1 }\n}\nmap_values(users, lambda u : u['age']) # {'fred': 40, 'pebbles': 1}\n```\n"
  },
  {
    "path": "snippets/max-by.md",
    "content": "---\ntitle: Max list value based on function\ntype: snippet\ntags: [math,list]\ncover: digital-nomad-3\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nReturns the maximum value of a list, after mapping each element to a value using the provided function.\n\n- Use `map()` with `fn` to map each element to a value using the provided function.\n- Use `max()` to return the maximum value.\n\n```py\ndef max_by(lst, fn):\n  return max(map(fn, lst))\n```\n\n```py\nmax_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 8\n```\n"
  },
  {
    "path": "snippets/max-element-index.md",
    "content": "---\ntitle: Index of max element\ntype: snippet\ntags: [math,list]\ncover: dark-cloud\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nReturns the index of the element with the maximum value in a list.\n\n- Use `max()` and `list.index()` to get the maximum value in the list and return its index.\n\n```py\ndef max_element_index(arr):\n  return arr.index(max(arr))\n```\n\n```py\nmax_element_index([5, 8, 9, 7, 10, 3, 0]) # 4\n```\n"
  },
  {
    "path": "snippets/max-n.md",
    "content": "---\ntitle: N max elements\ntype: snippet\ntags: [list,math]\ncover: red-succulent\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nReturns the `n` maximum elements from the provided list.\n\n- Use `sorted()` to sort the list.\n- Use slice notation to get the specified number of elements.\n- Omit the second argument, `n`, to get a one-element list.\n- If `n` is greater than or equal to the provided list's length, then return the original list (sorted in descending order).\n\n```py\ndef max_n(lst, n = 1):\n  return sorted(lst, reverse = True)[:n]\n```\n\n```py\nmax_n([1, 2, 3]) # [3]\nmax_n([1, 2, 3], 2) # [3, 2]\n```\n"
  },
  {
    "path": "snippets/median.md",
    "content": "---\ntitle: Median\ntype: snippet\ntags: [math]\ncover: little-bird\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nFinds the median of a list of numbers.\n\n- Sort the numbers of the list using `list.sort()`.\n- Find the median, which is either the middle element of the list if the list length is odd or the average of the two middle elements if the list length is even.\n- [`statistics.median()`](https://docs.python.org/3/library/statistics.html#statistics.median) provides similar functionality to this snippet.\n\n```py\ndef median(list):\n  list.sort()\n  list_length = len(list)\n  if list_length % 2 == 0:\n    return (list[int(list_length / 2) - 1] + list[int(list_length / 2)]) / 2\n  return float(list[int(list_length / 2)])\n```\n\n```py\nmedian([1, 2, 3]) # 2.0\nmedian([1, 2, 3, 4]) # 2.5\n```\n"
  },
  {
    "path": "snippets/merge-dictionaries.md",
    "content": "---\ntitle: Merge dictionaries\ntype: snippet\ntags: [dictionary]\ncover: plant-candle\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nMerges two or more dictionaries.\n\n- Create a new `dict` and loop over `dicts`, using `dictionary.update()` to add the key-value pairs from each one to the result.\n\n```py\ndef merge_dictionaries(*dicts):\n  res = dict()\n  for d in dicts:\n    res.update(d)\n  return res\n```\n\n```py\nages_one = {\n  'Peter': 10,\n  'Isabel': 11,\n}\nages_two = {\n  'Anna': 9\n}\nmerge_dictionaries(ages_one, ages_two)\n# { 'Peter': 10, 'Isabel': 11, 'Anna': 9 }\n```\n"
  },
  {
    "path": "snippets/merge.md",
    "content": "---\ntitle: Merge lists\ntype: snippet\ntags: [list]\ncover: succulent-2\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nMerges two or more lists into a list of lists, combining elements from each of the input lists based on their positions.\n\n- Use `max()` combined with a list comprehension to get the length of the longest list in the arguments.\n- Use `range()` in combination with the `max_length` variable to loop as many times as there are elements in the longest list.\n- If a list is shorter than `max_length`, use `fill_value` for the remaining items (defaults to `None`).\n- [`zip()`](https://docs.python.org/3/library/functions.html#zip) and [`itertools.zip_longest()`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) provide similar functionality to this snippet.\n\n```py\ndef merge(*args, fill_value = None):\n  max_length = max([len(lst) for lst in args])\n  result = []\n  for i in range(max_length):\n    result.append([\n      args[k][i] if i < len(args[k]) else fill_value for k in range(len(args))\n    ])\n  return result\n```\n\n```py\nmerge(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]\nmerge(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]\nmerge(['a'], [1, 2], [True, False], fill_value = '_')\n# [['a', 1, True], ['_', 2, False]]\n```\n"
  },
  {
    "path": "snippets/miles-to-km.md",
    "content": "---\ntitle: Miles to km\ntype: snippet\ntags: [math]\nunlisted: true\ncover: interior-5\ndateModified: 2021-01-04T12:47:04+02:00\n---\n\nConverts miles to kilometers.\n\n- Follows the conversion formula `km = mi * 1.609344`.\n\n```py\ndef miles_to_km(miles):\n  return miles * 1.609344\n```\n\n```py\nmiles_to_km(5.03) # 8.09500032\n```\n"
  },
  {
    "path": "snippets/min-by.md",
    "content": "---\ntitle: Min list value based on function\ntype: snippet\ntags: [math,list]\ncover: purple-flower-field\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nReturns the minimum value of a list, after mapping each element to a value using the provided function.\n\n- Use `map()` with `fn` to map each element to a value using the provided function.\n- Use `min()` to return the minimum value.\n\n```py\ndef min_by(lst, fn):\n  return min(map(fn, lst))\n```\n\n```py\nmin_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 2\n```\n"
  },
  {
    "path": "snippets/min-element-index.md",
    "content": "---\ntitle: Index of min element\ntype: snippet\ntags: [math,list]\ncover: two-cities\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nReturns the index of the element with the minimum value in a list.\n\n- Use `min()` and `list.index()` to obtain the minimum value in the list and then return its index.\n\n```py\ndef min_element_index(arr):\n  return arr.index(min(arr))\n```\n\n```py\nmin_element_index([3, 5, 2, 6, 10, 7, 9]) # 2\n```\n"
  },
  {
    "path": "snippets/min-n.md",
    "content": "---\ntitle: N min elements\ntype: snippet\ntags: [list,math]\ncover: balloons\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nReturns the `n` minimum elements from the provided list.\n\n- Use `sorted()` to sort the list.\n- Use slice notation to get the specified number of elements.\n- Omit the second argument, `n`, to get a one-element list.\n- If `n` is greater than or equal to the provided list's length, then return the original list (sorted in ascending order).\n\n```py\ndef min_n(lst, n = 1):\n  return sorted(lst, reverse = False)[:n]\n```\n\n```py\nmin_n([1, 2, 3]) # [1]\nmin_n([1, 2, 3], 2) # [1, 2]\n```\n"
  },
  {
    "path": "snippets/months-diff.md",
    "content": "---\ntitle: Date difference in months\ntype: snippet\ntags: [date]\ncover: succulent-11\ndateModified: 2020-10-28T16:20:39+02:00\n---\n\nCalculates the month difference between two dates.\n\n- Subtract `start` from `end` and use `datetime.timedelta.days` to get the day difference.\n- Divide by `30` and use `math.ceil()` to get the difference in months (rounded up).\n\n```py\nfrom math import ceil\n\ndef months_diff(start, end):\n  return ceil((end - start).days / 30)\n```\n\n```py\nfrom datetime import date\n\nmonths_diff(date(2020, 10, 28), date(2020, 11, 25)) # 1\n```\n"
  },
  {
    "path": "snippets/most-frequent.md",
    "content": "---\ntitle: Most frequent element\ntype: snippet\ntags: [list]\ncover: secret-tree\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nReturns the most frequent element in a list.\n\n- Use `set()` to get the unique values in `lst`.\n- Use `max()` to find the element that has the most appearances.\n\n```py\ndef most_frequent(lst):\n  return max(set(lst), key = lst.count)\n```\n\n```py\nmost_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2]) #2\n```\n"
  },
  {
    "path": "snippets/n-times-string.md",
    "content": "---\ntitle: Repeat string\ntype: snippet\ntags: [string]\ncover: playing-fetch\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nGenerates a string with the given string value repeated `n` number of times.\n\n- Repeat the string `n` times, using the `*` operator.\n\n```py\ndef n_times_string(s, n):\n  return (s * n)\n```\n\n```py\nn_times_string('py', 4) #'pypypypy'\n```\n"
  },
  {
    "path": "snippets/none.md",
    "content": "---\ntitle: Test if every list element is falsy\ntype: snippet\ntags: [list]\ncover: jars-on-shelf-2\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nChecks if the provided function returns `True` for at least one element in the list.\n\n- Use `all()` and `fn` to check if `fn` returns `False` for all the elements in the list.\n\n```py\ndef none(lst, fn = lambda x: x):\n  return all(not fn(x) for x in lst)\n```\n\n```py\nnone([0, 1, 2, 0], lambda x: x >= 2 ) # False\nnone([0, 0, 0]) # True\n```\n"
  },
  {
    "path": "snippets/num-to-range.md",
    "content": "---\ntitle: Map number to range\ntype: snippet\ntags: [math]\ncover: round-leaves\ndateModified: 2021-04-05T18:25:46+03:00\n---\n\nMaps a number from one range to another range.\n\n- Return `num` mapped between `outMin`-`outMax` from `inMin`-`inMax`.\n\n```py\ndef num_to_range(num, inMin, inMax, outMin, outMax):\n  return outMin + (float(num - inMin) / float(inMax - inMin) * (outMax\n                  - outMin))\n```\n\n```py\nnum_to_range(5, 0, 10, 0, 100) # 50.0\n```\n"
  },
  {
    "path": "snippets/offset.md",
    "content": "---\ntitle: Offset list elements\ntype: snippet\ntags: [list]\ncover: digital-nomad-10\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nMoves the specified amount of elements to the end of the list.\n\n- Use slice notation to get the two slices of the list and combine them before returning.\n\n```py\ndef offset(lst, offset):\n  return lst[offset:] + lst[:offset]\n```\n\n```py\noffset([1, 2, 3, 4, 5], 2) # [3, 4, 5, 1, 2]\noffset([1, 2, 3, 4, 5], -2) # [4, 5, 1, 2, 3]\n```\n"
  },
  {
    "path": "snippets/pad-number.md",
    "content": "---\ntitle: Pad number\ntype: snippet\ntags: [string,math]\ncover: umbrellas\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nPads a given number to the specified length.\n\n- Use `str.zfill()` to pad the number to the specified length, after converting it to a string.\n\n```py\ndef pad_number(n, l):\n  return str(n).zfill(l)\n```\n\n```py\npad_number(1234, 6); # '001234'\n```\n"
  },
  {
    "path": "snippets/pad.md",
    "content": "---\ntitle: Pad string\ntype: snippet\ntags: [string]\nauthor: chalarangelo\ncover: digital-nomad-11\ndateModified: 2020-10-04T01:53:05+03:00\n---\n\nPads a string on both sides with the specified character, if it's shorter than the specified length.\n\n- Use `str.ljust()` and `str.rjust()` to pad both sides of the given string.\n- Omit the third argument, `char`, to use the whitespace character as the default padding character.\n\n```py\nfrom math import floor\n\ndef pad(s, length, char = ' '):\n  return s.rjust(floor((len(s) + length)/2), char).ljust(length, char)\n```\n\n```py\npad('cat', 8) # '  cat   '\npad('42', 6, '0') # '004200'\npad('foobar', 3) # 'foobar'\n```\n"
  },
  {
    "path": "snippets/palindrome.md",
    "content": "---\ntitle: Palindrome\ntype: snippet\ntags: [string]\ncover: succulent-6\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nChecks if the given string is a palindrome.\n\n- Use `str.lower()` and `re.sub()` to convert to lowercase and remove non-alphanumeric characters from the given string.\n- Then, compare the new string with its reverse, using slice notation.\n\n```py\nfrom re import sub\n\ndef palindrome(s):\n  s = sub('[\\W_]', '', s.lower())\n  return s == s[::-1]\n```\n\n```py\npalindrome('taco cat') # True\n```\n"
  },
  {
    "path": "snippets/pluck.md",
    "content": "---\ntitle: Pluck values from list of dictionaries\ntype: snippet\ntags: [list,dictionary]\ncover: succulent-9\ndateModified: 2020-10-22T10:09:44+03:00\n---\n\nConverts a list of dictionaries into a list of values corresponding to the specified `key`.\n\n- Use a list comprehension and `dict.get()` to get the value of `key` for each dictionary in `lst`.\n\n```py\ndef pluck(lst, key):\n  return [x.get(key) for x in lst]\n```\n\n```py\nsimpsons = [\n  { 'name': 'lisa', 'age': 8 },\n  { 'name': 'homer', 'age': 36 },\n  { 'name': 'marge', 'age': 34 },\n  { 'name': 'bart', 'age': 10 }\n]\npluck(simpsons, 'age') # [8, 36, 34, 10]\n```\n"
  },
  {
    "path": "snippets/powerset.md",
    "content": "---\ntitle: Powerset\ntype: snippet\ntags: [math,list]\nauthor: chalarangelo\ncover: rock-climbing\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nReturns the powerset of a given iterable.\n\n- Use `list()` to convert the given value to a list.\n- Use `range()` and `itertools.combinations()` to create a generator that returns all subsets.\n- Use `itertools.chain.from_iterable()` and `list()` to consume the generator and return a list.\n\n```py\nfrom itertools import chain, combinations\n\ndef powerset(iterable):\n  s = list(iterable)\n  return list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1)))\n```\n\n```py\npowerset([1, 2]) # [(), (1,), (2,), (1, 2)]\n```\n"
  },
  {
    "path": "snippets/rads-to-degrees.md",
    "content": "---\ntitle: Radians to degrees\ntype: snippet\ntags: [math]\ncover: watermelon-bike\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nConverts an angle from radians to degrees.\n\n- Use `math.pi` and the radian to degree formula to convert the angle from radians to degrees.\n\n```py\nfrom math import pi\n\ndef rads_to_degrees(rad):\n  return (rad * 180.0) / pi\n```\n\n```py\nfrom math import pi\n\nrads_to_degrees(pi / 2) # 90.0\n```\n"
  },
  {
    "path": "snippets/reverse-number.md",
    "content": "---\ntitle: Reverse number\ntype: snippet\ntags: [math]\ncover: taking-photos\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nReverses a number.\n\n- Use `str()` to convert the number to a string, slice notation to reverse it and `str.replace()` to remove the sign.\n- Use `float()` to convert the result to a number and `math.copysign()` to copy the original sign.\n\n```py\nfrom math import copysign\n\ndef reverse_number(n):\n  return copysign(float(str(n)[::-1].replace('-', '')), n)\n```\n\n```py\nreverse_number(981) # 189\nreverse_number(-500) # -5\nreverse_number(73.6) # 6.37\nreverse_number(-5.23) # -32.5\n```\n"
  },
  {
    "path": "snippets/reverse.md",
    "content": "---\ntitle: Reverse list\ntype: snippet\ntags: [list,string]\ncover: industrial-tokyo\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nReverses a list or a string.\n\n- Use slice notation to reverse the list or string.\n\n```py\ndef reverse(itr):\n  return itr[::-1]\n```\n\n```py\nreverse([1, 2, 3]) # [3, 2, 1]\nreverse('snippet') # 'teppins'\n```\n"
  },
  {
    "path": "snippets/rgb-to-hex.md",
    "content": "---\ntitle: RGB to hex\ntype: snippet\ntags: [string,math]\ncover: campfire\ndateModified: 2020-11-02T19:28:27+02:00\n---\n\nConverts the values of RGB components to a hexadecimal color code.\n\n- Create a placeholder for a zero-padded hexadecimal value using `'{:02X}'` and copy it three times.\n- Use `str.format()` on the resulting string to replace the placeholders with the given values.\n\n```py\ndef rgb_to_hex(r, g, b):\n  return ('{:02X}' * 3).format(r, g, b)\n```\n\n```py\nrgb_to_hex(255, 165, 1) # 'FFA501'\n```\n"
  },
  {
    "path": "snippets/roll.md",
    "content": "---\ntitle: Rotate list elements\ntype: snippet\ntags: [list]\ncover: colorful-pots\ndateModified: 2020-11-02T19:15:44+02:00\n---\n\nMoves the specified amount of elements to the start of the list.\n\n- Use slice notation to get the two slices of the list and combine them before returning.\n\n```py\ndef roll(lst, offset):\n  return lst[-offset:] + lst[:-offset]\n```\n\n```py\nroll([1, 2, 3, 4, 5], 2) # [4, 5, 1, 2, 3]\nroll([1, 2, 3, 4, 5], -2) # [3, 4, 5, 1, 2]\n```\n"
  },
  {
    "path": "snippets/sample.md",
    "content": "---\ntitle: Random element in list\ntype: snippet\ntags: [list,random]\ncover: walking-on-top\ndateModified: 2020-10-28T11:45:34+02:00\n---\n\nReturns a random element from a list.\n\n- Use `random.choice()` to get a random element from `lst`.\n\n```py\nfrom random import choice\n\ndef sample(lst):\n  return choice(lst)\n```\n\n```py\nsample([3, 7, 9, 11]) # 9\n```\n"
  },
  {
    "path": "snippets/shuffle.md",
    "content": "---\ntitle: Shuffle list\ntype: snippet\ntags: [list,random]\ncover: tent-stars\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nRandomizes the order of the values of an list, returning a new list.\n\n- Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list.\n- [`random.shuffle`](https://docs.python.org/3/library/random.html#random.shuffle) provides similar functionality to this snippet.\n\n```py\nfrom copy import deepcopy\nfrom random import randint\n\ndef shuffle(lst):\n  temp_lst = deepcopy(lst)\n  m = len(temp_lst)\n  while (m):\n    m -= 1\n    i = randint(0, m)\n    temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]\n  return temp_lst\n```\n\n```py\nfoo = [1, 2, 3]\nshuffle(foo) # [2, 3, 1], foo = [1, 2, 3]\n```\n"
  },
  {
    "path": "snippets/similarity.md",
    "content": "---\ntitle: List similarity\ntype: snippet\ntags: [list]\ncover: sunflowers\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nReturns a list of elements that exist in both lists.\n\n- Use a list comprehension on `a` to only keep values contained in both lists.\n\n```py\ndef similarity(a, b):\n  return [item for item in a if item in b]\n```\n\n```py\nsimilarity([1, 2, 3], [1, 2, 4]) # [1, 2]\n```\n"
  },
  {
    "path": "snippets/slugify.md",
    "content": "---\ntitle: String to slug\ntype: snippet\ntags: [string,regexp]\ncover: sliced-fruits\ndateModified: 2020-10-25T12:43:20+02:00\n---\n\nConverts a string to a URL-friendly slug.\n\n- Use `str.lower()` and `str.strip()` to normalize the input string.\n- Use `re.sub()` to to replace spaces, dashes and underscores with `-` and remove special characters.\n\n```py\nimport re\n\ndef slugify(s):\n  s = s.lower().strip()\n  s = re.sub(r'[^\\w\\s-]', '', s)\n  s = re.sub(r'[\\s_-]+', '-', s)\n  s = re.sub(r'^-+|-+$', '', s)\n  return s\n```\n\n```py\nslugify('Hello World!') # 'hello-world'\n```\n"
  },
  {
    "path": "snippets/snake.md",
    "content": "---\ntitle: Snakecase string\ntype: snippet\ntags: [string,regexp]\ncover: organizer\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nConverts a string to snake case.\n\n- Use `re.sub()` to match all words in the string, `str.lower()` to lowercase them.\n- Use `re.sub()` to replace any `-` characters with spaces.\n- Finally, use `str.join()` to combine all words using `-` as the separator.\n\n```py\nfrom re import sub\n\ndef snake(s):\n  return '_'.join(\n    sub('([A-Z][a-z]+)', r' \\1',\n    sub('([A-Z]+)', r' \\1',\n    s.replace('-', ' '))).split()).lower()\n```\n\n```py\nsnake('camelCase') # 'camel_case'\nsnake('some text') # 'some_text'\nsnake('some-mixed_string With spaces_underscores-and-hyphens')\n# 'some_mixed_string_with_spaces_underscores_and_hyphens'\nsnake('AllThe-small Things') # 'all_the_small_things'\n```\n"
  },
  {
    "path": "snippets/some.md",
    "content": "---\ntitle: Test if some list elements are truthy\ntype: snippet\ntags: [list]\ncover: pink-flower-tree\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nChecks if the provided function returns `True` for at least one element in the list.\n\n- Use `any()` in combination with `map()` to check if `fn` returns `True` for any element in the list.\n\n```py\ndef some(lst, fn = lambda x: x):\n  return any(map(fn, lst))\n```\n\n```py\nsome([0, 1, 2, 0], lambda x: x >= 2 ) # True\nsome([0, 0, 1, 0]) # True\n```\n"
  },
  {
    "path": "snippets/sort-by-indexes.md",
    "content": "---\ntitle: Sort list by indexes\ntype: snippet\ntags: [list]\ncover: little-white-flowers\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nSorts one list based on another list containing the desired indexes.\n\n- Use `zip()` and `sorted()` to combine and sort the two lists, based on the values of `indexes`.\n- Use a list comprehension to get the first element of each pair from the result.\n- Use the `reverse` parameter in `sorted()` to sort the dictionary in reverse order, based on the third argument.\n\n```py\ndef sort_by_indexes(lst, indexes, reverse=False):\n  return [val for (_, val) in sorted(zip(indexes, lst), key=lambda x: \\\n          x[0], reverse=reverse)]\n```\n\n```py\na = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk']\nb = [3, 2, 6, 4, 1, 5]\nsort_by_indexes(a, b) # ['apples', 'bread', 'eggs', 'jam', 'milk', 'oranges']\nsort_by_indexes(a, b, True)\n# ['oranges', 'milk', 'jam', 'eggs', 'bread', 'apples']\n```\n"
  },
  {
    "path": "snippets/sort-dict-by-key.md",
    "content": "---\ntitle: Sort dictionary by key\ntype: snippet\ntags: [dictionary]\ncover: laptop-plants\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nSorts the given dictionary by key.\n\n- Use `dict.items()` to get a list of tuple pairs from `d` and sort it using `sorted()`.\n- Use `dict()` to convert the sorted list back to a dictionary.\n- Use the `reverse` parameter in `sorted()` to sort the dictionary in reverse order, based on the second argument.\n\n```py\ndef sort_dict_by_key(d, reverse = False):\n  return dict(sorted(d.items(), reverse = reverse))\n```\n\n```py\nd = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}\nsort_dict_by_key(d) # {'five': 5, 'four': 4, 'one': 1, 'three': 3, 'two': 2}\nsort_dict_by_key(d, True)\n# {'two': 2, 'three': 3, 'one': 1, 'four': 4, 'five': 5}\n```\n"
  },
  {
    "path": "snippets/sort-dict-by-value.md",
    "content": "---\ntitle: Sort dictionary by value\ntype: snippet\ntags: [dictionary]\ncover: jars-on-shelf\ndateModified: 2021-01-08T00:56:50+02:00\n---\n\nSorts the given dictionary by value.\n\n- Use `dict.items()` to get a list of tuple pairs from `d` and sort it using a lambda function and `sorted()`.\n- Use `dict()` to convert the sorted list back to a dictionary.\n- Use the `reverse` parameter in `sorted()` to sort the dictionary in reverse order, based on the second argument.\n- **⚠️ NOTICE:** Dictionary values must be of the same type.\n\n```py\ndef sort_dict_by_value(d, reverse = False):\n  return dict(sorted(d.items(), key = lambda x: x[1], reverse = reverse))\n```\n\n```py\nd = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}\nsort_dict_by_value(d) # {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}\nsort_dict_by_value(d, True)\n# {'five': 5, 'four': 4, 'three': 3, 'two': 2, 'one': 1}\n```\n"
  },
  {
    "path": "snippets/split-lines.md",
    "content": "---\ntitle: Split into lines\ntype: snippet\ntags: [string]\ncover: succulent-4\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nSplits a multiline string into a list of lines.\n\n- Use `str.split()` and `'\\n'` to match line breaks and create a list.\n- [`str.splitlines()`](https://docs.python.org/3/library/stdtypes.html#str.splitlines) provides similar functionality to this snippet.\n\n```py\ndef split_lines(s):\n  return s.split('\\n')\n```\n\n```py\nsplit_lines('This\\nis a\\nmultiline\\nstring.\\n')\n# ['This', 'is a', 'multiline', 'string.' , '']\n```\n"
  },
  {
    "path": "snippets/spread.md",
    "content": "---\ntitle: Spread list\ntype: snippet\ntags: [list]\ncover: digital-nomad-14\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nFlattens a list, by spreading its elements into a new list.\n\n- Loop over elements, use `list.extend()` if the element is a list, `list.append()` otherwise.\n\n```py\ndef spread(arg):\n  ret = []\n  for i in arg:\n    ret.extend(i) if isinstance(i, list) else ret.append(i)\n  return ret\n```\n\n```py\nspread([1, 2, 3, [4, 5, 6], [7], 8, 9]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n"
  },
  {
    "path": "snippets/sum-by.md",
    "content": "---\ntitle: Sum list based on function\ntype: snippet\ntags: [math,list]\ncover: horse-sunset\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nCalculates the sum of a list, after mapping each element to a value using the provided function.\n\n- Use `map()` with `fn` to map each element to a value using the provided function.\n- Use `sum()` to return the sum of the values.\n\n```py\ndef sum_by(lst, fn):\n  return sum(map(fn, lst))\n```\n\n```py\nsum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 20\n```\n"
  },
  {
    "path": "snippets/sum-of-powers.md",
    "content": "---\ntitle: Sum of powers\ntype: snippet\ntags: [math]\ncover: river-flow\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nReturns the sum of the powers of all the numbers from `start` to `end` (both inclusive).\n\n- Use `range()` in combination with a list comprehension to create a list of elements in the desired range raised to the given `power`.\n- Use `sum()` to add the values together.\n- Omit the second argument, `power`, to use a default power of `2`.\n- Omit the third argument, `start`, to use a default starting value of `1`.\n\n```py\ndef sum_of_powers(end, power = 2, start = 1):\n  return sum([(i) ** power for i in range(start, end + 1)])\n```\n\n```py\nsum_of_powers(10) # 385\nsum_of_powers(10, 3) # 3025\nsum_of_powers(10, 3, 5) # 2925\n```\n"
  },
  {
    "path": "snippets/symmetric-difference-by.md",
    "content": "---\ntitle: List symmetric difference based on function\ntype: snippet\ntags: [list]\ncover: succulent-1\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nReturns the symmetric difference between two lists, after applying the provided function to each list element of both.\n\n- Create a `set` by applying `fn` to each element in every list.\n- Use a list comprehension in combination with `fn` on each of them to only keep values not contained in the previously created set of the other.\n\n```py\ndef symmetric_difference_by(a, b, fn):\n  (_a, _b) = (set(map(fn, a)), set(map(fn, b)))\n  return [item for item in a if fn(item) not in _b] + [item\n          for item in b if fn(item) not in _a]\n```\n\n```py\nfrom math import floor\n\nsymmetric_difference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2, 3.4]\n```\n"
  },
  {
    "path": "snippets/symmetric-difference.md",
    "content": "---\ntitle: List symmetric difference\ntype: snippet\ntags: [list]\ncover: ice\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nReturns the symmetric difference between two iterables, without filtering out duplicate values.\n\n- Create a `set` from each list.\n- Use a list comprehension on each of them to only keep values not contained in the previously created set of the other.\n\n```py\ndef symmetric_difference(a, b):\n  (_a, _b) = (set(a), set(b))\n  return [item for item in a if item not in _b] + [item for item in b\n          if item not in _a]\n```\n\n```py\nsymmetric_difference([1, 2, 3], [1, 2, 4]) # [3, 4]\n```\n"
  },
  {
    "path": "snippets/tail.md",
    "content": "---\ntitle: List tail\ntype: snippet\ntags: [list]\ncover: meteora\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nReturns all elements in a list except for the first one.\n\n- Use slice notation to return the last element if the list's length is more than `1`.\n- Otherwise, return the whole list.\n\n```py\ndef tail(lst):\n  return lst[1:] if len(lst) > 1 else lst\n```\n\n```py\ntail([1, 2, 3]) # [2, 3]\ntail([1]) # [1]\n```\n"
  },
  {
    "path": "snippets/take-right.md",
    "content": "---\ntitle: Remove list elements from the end\ntype: snippet\ntags: [list]\nauthor: chalarangelo\ncover: three-vases\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nReturns a list with `n` elements removed from the end.\n\n- Use slice notation to create a slice of the list with `n` elements taken from the end.\n\n```py\ndef take_right(itr, n = 1):\n  return itr[-n:]\n```\n\n```py\ntake_right([1, 2, 3], 2) # [2, 3]\ntake_right([1, 2, 3]) # [3]\n```\n"
  },
  {
    "path": "snippets/take.md",
    "content": "---\ntitle: Remove list elements\ntype: snippet\ntags: [list]\nauthor: chalarangelo\ncover: sea-view-2\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nReturns a list with `n` elements removed from the beginning.\n\n- Use slice notation to create a slice of the list with `n` elements taken from the beginning.\n\n```py\ndef take(itr, n = 1):\n  return itr[:n]\n```\n\n```py\ntake([1, 2, 3], 5) # [1, 2, 3]\ntake([1, 2, 3], 0) # []\n```\n"
  },
  {
    "path": "snippets/to-binary.md",
    "content": "---\ntitle: Number to binary\ntype: snippet\ntags: [math]\ncover: digital-nomad-13\ndateModified: 2020-10-07T19:46:01+03:00\n---\n\nReturns the binary representation of the given number.\n\n- Use `bin()` to convert a given decimal number into its binary equivalent.\n\n```py\ndef to_binary(n):\n  return bin(n)\n```\n\n```py\nto_binary(100) # 0b1100100\n```\n"
  },
  {
    "path": "snippets/to-dictionary.md",
    "content": "---\ntitle: Lists to dictionary\ntype: snippet\ntags: [list,dictionary]\nexcerpt: Combines two lists into a dictionary, using the first one as the keys and the second one as the values.\ncover: purple-sunset\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nCombines two lists into a dictionary, where the elements of the first one serve as the keys and the elements of the second one serve as the values.\nThe values of the first list need to be unique and hashable.\n\n- Use `zip()` in combination with `dict()` to combine the values of the two lists into a dictionary.\n\n```py\ndef to_dictionary(keys, values):\n  return dict(zip(keys, values))\n```\n\n```py\nto_dictionary(['a', 'b'], [1, 2]) # { a: 1, b: 2 }\n```\n"
  },
  {
    "path": "snippets/to-hex.md",
    "content": "---\ntitle: Number to hex\ntype: snippet\ntags: [math]\ncover: green-plant\ndateModified: 2020-10-09T09:45:47+03:00\n---\n\nReturns the hexadecimal representation of the given number.\n\n- Use `hex()` to convert a given decimal number into its hexadecimal equivalent.\n\n```py\ndef to_hex(dec):\n  return hex(dec)\n```\n\n```py\nto_hex(41) # 0x29\nto_hex(332) # 0x14c\n```\n"
  },
  {
    "path": "snippets/to-iso-date.md",
    "content": "---\ntitle: Date to ISO format\ntype: snippet\ntags: [date]\ncover: succulent-red-light\ndateModified: 2021-01-07T23:30:28+02:00\n---\n\nConverts a date to its ISO-8601 representation.\n\n- Use `datetime.datetime.isoformat()` to convert the given `datetime.datetime` object to an ISO-8601 date.\n\n```py\nfrom datetime import datetime\n\ndef to_iso_date(d):\n  return d.isoformat()\n```\n\n```py\nfrom datetime import datetime\n\nto_iso_date(datetime(2020, 10, 25)) # 2020-10-25T00:00:00\n```\n"
  },
  {
    "path": "snippets/to-roman-numeral.md",
    "content": "---\ntitle: Integer to roman numeral\ntype: snippet\ntags: [math,string]\ncover: tram-car\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nConverts an integer to its roman numeral representation.\nAccepts value between `1` and `3999` (both inclusive).\n\n- Create a lookup list containing tuples in the form of (roman value, integer).\n- Use a `for` loop to iterate over the values in `lookup`.\n- Use `divmod()` to update `num` with the remainder, adding the roman numeral representation to the result.\n\n```py\ndef to_roman_numeral(num):\n  lookup = [\n    (1000, 'M'),\n    (900, 'CM'),\n    (500, 'D'),\n    (400, 'CD'),\n    (100, 'C'),\n    (90, 'XC'),\n    (50, 'L'),\n    (40, 'XL'),\n    (10, 'X'),\n    (9, 'IX'),\n    (5, 'V'),\n    (4, 'IV'),\n    (1, 'I'),\n  ]\n  res = ''\n  for (n, roman) in lookup:\n    (d, num) = divmod(num, n)\n    res += roman * d\n  return res\n```\n\n```py\nto_roman_numeral(3) # 'III'\nto_roman_numeral(11) # 'XI'\nto_roman_numeral(1998) # 'MCMXCVIII'\n```\n"
  },
  {
    "path": "snippets/transpose.md",
    "content": "---\ntitle: Transpose matrix\ntype: snippet\ntags: [list]\ncover: lake-bench\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nTransposes a two-dimensional list.\n\n- Use `*lst` to get the provided list as tuples.\n- Use `zip()` in combination with `list()` to create the transpose of the given two-dimensional list.\n\n```py\ndef transpose(lst):\n  return list(zip(*lst))\n```\n\n```py\ntranspose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])\n# [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]\n```\n"
  },
  {
    "path": "snippets/unfold.md",
    "content": "---\ntitle: Unfold list\ntype: snippet\ntags: [function,list]\ncover: painters-desk\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nBuilds a list, using an iterator function and an initial seed value.\n\n- The iterator function accepts one argument (`seed`) and must always return a list with two elements ([`value`, `nextSeed`]) or `False` to terminate.\n- Use a generator function, `fn_generator`, that uses a `while` loop to call the iterator function and `yield` the `value` until it returns `False`.\n- Use a list comprehension to return the list that is produced by the generator, using the iterator function.\n\n```py\ndef unfold(fn, seed):\n  def fn_generator(val):\n    while True:\n      val = fn(val[1])\n      if val == False: break\n      yield val[0]\n  return [i for i in fn_generator([None, seed])]\n```\n\n```py\nf = lambda n: False if n > 50 else [-n, n + 10]\nunfold(f, 10) # [-10, -20, -30, -40, -50]\n```\n"
  },
  {
    "path": "snippets/union-by.md",
    "content": "---\ntitle: List union based on function\ntype: snippet\ntags: [list]\ncover: sunrise-over-city\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nReturns every element that exists in any of the two lists once, after applying the provided function to each element of both.\n\n- Create a `set` by applying `fn` to each element in `a`.\n- Use a list comprehension in combination with `fn` on `b` to only keep values not contained in the previously created set, `_a`.\n- Finally, create a `set` from the previous result and `a` and transform it into a `list`\n\n```py\ndef union_by(a, b, fn):\n  _a = set(map(fn, a))\n  return list(set(a + [item for item in b if fn(item) not in _a]))\n```\n\n```py\nfrom math import floor\n\nunion_by([2.1], [1.2, 2.3], floor) # [2.1, 1.2]\n```\n"
  },
  {
    "path": "snippets/union.md",
    "content": "---\ntitle: List union\ntype: snippet\ntags: [list]\ncover: river-houses\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nReturns every element that exists in any of the two lists once.\n\n- Create a `set` with all values of `a` and `b` and convert to a `list`.\n\n```py\ndef union(a, b):\n  return list(set(a + b))\n```\n\n```py\nunion([1, 2, 3], [4, 3, 2]) # [1, 2, 3, 4]\n```\n"
  },
  {
    "path": "snippets/unique-elements.md",
    "content": "---\ntitle: Unique elements in list\ntype: snippet\ntags: [list]\ncover: cold-mountains\ndateModified: 2020-09-15T16:13:06+03:00\n---\n\nReturns the unique elements in a given list.\n\n- Create a `set` from the list to discard duplicated values, then return a `list` from it.\n\n```py\ndef unique_elements(li):\n  return list(set(li))\n```\n\n```py\nunique_elements([1, 2, 2, 3, 4, 3]) # [1, 2, 3, 4]\n```\n"
  },
  {
    "path": "snippets/values-only.md",
    "content": "---\ntitle: Dictionary values\ntype: snippet\ntags: [dictionary,list]\ncover: colorful-lounge\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nReturns a flat list of all the values in a flat dictionary.\n\n- Use `dict.values()` to return the values in the given dictionary.\n- Return a `list()` of the previous result.\n\n```py\ndef values_only(flat_dict):\n  return list(flat_dict.values())\n```\n\n```py\nages = {\n  'Peter': 10,\n  'Isabel': 11,\n  'Anna': 9,\n}\nvalues_only(ages) # [10, 11, 9]\n```\n"
  },
  {
    "path": "snippets/weighted-average.md",
    "content": "---\ntitle: Weighted average\ntype: snippet\ntags: [math,list]\ncover: digital-nomad-4\ndateModified: 2020-12-24T15:00:53+02:00\n---\n\nReturns the weighted average of two or more numbers.\n\n- Use `sum()` to sum the products of the numbers by their weight and to sum the weights.\n- Use `zip()` and a list comprehension to iterate over the pairs of values and weights.\n\n```py\ndef weighted_average(nums, weights):\n  return sum(x * y for x, y in zip(nums, weights)) / sum(weights)\n```\n\n```py\nweighted_average([1, 2, 3], [0.6, 0.2, 0.3]) # 1.72727\n```\n"
  },
  {
    "path": "snippets/when.md",
    "content": "---\ntitle: Apply function when true\ntype: snippet\ntags: [function]\ncover: interior-10\ndateModified: 2020-11-09T23:56:11+02:00\n---\n\nTests a value, `x`, against a testing function, conditionally applying a function.\n\n- Check if the value of `predicate()` is `True` for `x` and if so call `when_true()`, otherwise return `x`.\n\n```py\ndef when(predicate, when_true):\n  return lambda x: when_true(x) if predicate(x) else x\n```\n\n```py\ndouble_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)\ndouble_even_numbers(2) # 4\ndouble_even_numbers(1) # 1\n```\n"
  },
  {
    "path": "snippets/words.md",
    "content": "---\ntitle: String to words\ntype: snippet\ntags: [string,regexp]\ncover: rocky-lake\ndateModified: 2020-11-02T19:28:35+02:00\n---\n\nConverts a given string into a list of words.\n\n- Use `re.findall()` with the supplied `pattern` to find all matching substrings.\n- Omit the second argument to use the default regexp, which matches alphanumeric and hyphens.\n\n```py\nimport re\n\ndef words(s, pattern = '[a-zA-Z-]+'):\n  return re.findall(pattern, s)\n```\n\n```py\nwords('I love Python!!') # ['I', 'love', 'Python']\nwords('python, javaScript & coffee') # ['python', 'javaScript', 'coffee']\nwords('build -q --out one-item', r'\\b[a-zA-Z-]+\\b')\n# ['build', 'q', 'out', 'one-item']\n```\n"
  }
]