add cpntributor_database
This commit is contained in:
50
.github/ISSUE_TEMPLATE.md
vendored
50
.github/ISSUE_TEMPLATE.md
vendored
@ -1,25 +1,25 @@
|
||||
<!--- Provide a general summary of the issue in the Title above -->
|
||||
<!--- Add the prefix [BUG] or [FEATURE] to the Title -->
|
||||
|
||||
<!--- In case it's a feature suggestion, otherwise delete this section -->
|
||||
<!--- Make sure there isn't already a snippet accomplishing your goal -->
|
||||
## [FEATURE] _REPLACE THIS WITH A BRIEF SUMMARY OF THE SUGGESTED SNIPPET_
|
||||
**Category:** <!-- One of the existing categories preferably -->
|
||||
### Description <!-- IF NEEDED -->
|
||||
<!-- More detailed description of the snippet you want to be included in 30-seconds-of-code -->
|
||||
|
||||
|
||||
<!--- In case it's a bug, otherwise delete this section-->
|
||||
<!--- Make sure there isn't already an open issue for your problem -->
|
||||
## [BUG] _REPLACE THIS WITH A BRIEF SUMMARY OF YOUR ISSUE_
|
||||
### Expected Snippet Behavior
|
||||
<!--- If you're describing a bug, tell us what should happen -->
|
||||
<!--- If you're suggesting a change/improvement, tell us how it should work -->
|
||||
|
||||
### Current Snippet Behavior
|
||||
<!--- If describing a bug, tell us what happens instead of the expected behavior -->
|
||||
<!--- If suggesting a change/improvement, explain the difference from current behavior -->
|
||||
|
||||
### Possible Solution
|
||||
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
|
||||
<!--- or ideas how to implement the addition or change -->
|
||||
<!--- Provide a general summary of the issue in the Title above -->
|
||||
<!--- Add the prefix [BUG] or [FEATURE] to the Title -->
|
||||
|
||||
<!--- In case it's a feature suggestion, otherwise delete this section -->
|
||||
<!--- Make sure there isn't already a snippet accomplishing your goal -->
|
||||
## [FEATURE] _REPLACE THIS WITH A BRIEF SUMMARY OF THE SUGGESTED SNIPPET_
|
||||
**Category:** <!-- One of the existing categories preferably -->
|
||||
### Description <!-- IF NEEDED -->
|
||||
<!-- More detailed description of the snippet you want to be included in 30-seconds-of-code -->
|
||||
|
||||
|
||||
<!--- In case it's a bug, otherwise delete this section-->
|
||||
<!--- Make sure there isn't already an open issue for your problem -->
|
||||
## [BUG] _REPLACE THIS WITH A BRIEF SUMMARY OF YOUR ISSUE_
|
||||
### Expected Snippet Behavior
|
||||
<!--- If you're describing a bug, tell us what should happen -->
|
||||
<!--- If you're suggesting a change/improvement, tell us how it should work -->
|
||||
|
||||
### Current Snippet Behavior
|
||||
<!--- If describing a bug, tell us what happens instead of the expected behavior -->
|
||||
<!--- If suggesting a change/improvement, explain the difference from current behavior -->
|
||||
|
||||
### Possible Solution
|
||||
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
|
||||
<!--- or ideas how to implement the addition or change -->
|
||||
|
||||
54
.github/PULL_REQUEST_TEMPLATE.md
vendored
54
.github/PULL_REQUEST_TEMPLATE.md
vendored
@ -1,27 +1,27 @@
|
||||
<!--- Provide a general summary of your changes in the Title above -->
|
||||
|
||||
<!--- Add the prefix [FIX: #(issue number)], [FEATURE] or [ENHANCEMENT] to the Title -->
|
||||
|
||||
## Description
|
||||
<!--- Describe your changes in detail -->
|
||||
**Resolves** #(issue number) <!--- Delete if not a issue fix-->
|
||||
|
||||
## What does your PR belong to?
|
||||
- [ ] Website
|
||||
- [ ] Snippets
|
||||
- [ ] General / Things regarding the repository (like CI Integration)
|
||||
|
||||
## Types of changes
|
||||
- [ ] Bug fix (non-breaking change which fixes an issue)
|
||||
- [ ] Enhancement (non-breaking improvement of a snippet)
|
||||
- [ ] New feature (non-breaking change which adds functionality)
|
||||
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
|
||||
|
||||
## Checklist:
|
||||
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
|
||||
- [ ] My code follows the code style of this project.
|
||||
- [ ] My change requires a change to the documentation.
|
||||
- [ ] I have updated the documentation accordingly. <!-- Check this only if you have updated tag_database and ran lint.py and readme.py in the scripts folder -->
|
||||
- [ ] I have checked that the changes are working properly
|
||||
- [ ] I have checked that there isn't any PR doing the same
|
||||
- [ ] I have read the **CONTRIBUTING** document.
|
||||
<!--- Provide a general summary of your changes in the Title above -->
|
||||
|
||||
<!--- Add the prefix [FIX: #(issue number)], [FEATURE] or [ENHANCEMENT] to the Title -->
|
||||
|
||||
## Description
|
||||
<!--- Describe your changes in detail -->
|
||||
**Resolves** #(issue number) <!--- Delete if not a issue fix-->
|
||||
|
||||
## What does your PR belong to?
|
||||
- [ ] Website
|
||||
- [ ] Snippets
|
||||
- [ ] General / Things regarding the repository (like CI Integration)
|
||||
|
||||
## Types of changes
|
||||
- [ ] Bug fix (non-breaking change which fixes an issue)
|
||||
- [ ] Enhancement (non-breaking improvement of a snippet)
|
||||
- [ ] New feature (non-breaking change which adds functionality)
|
||||
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
|
||||
|
||||
## Checklist:
|
||||
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
|
||||
- [ ] My code follows the code style of this project.
|
||||
- [ ] My change requires a change to the documentation.
|
||||
- [ ] I have updated the documentation accordingly. <!-- Check this only if you have updated tag_database and ran lint.py and readme.py in the scripts folder -->
|
||||
- [ ] I have checked that the changes are working properly
|
||||
- [ ] I have checked that there isn't any PR doing the same
|
||||
- [ ] I have read the **CONTRIBUTING** document.
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@ -1 +1 @@
|
||||
__pycache__/
|
||||
__pycache__/
|
||||
|
||||
40
.travis.yml
40
.travis.yml
@ -1,20 +1,20 @@
|
||||
language: python
|
||||
cache:
|
||||
directories:
|
||||
- __pycache__
|
||||
python:
|
||||
- "3.6"
|
||||
before_install:
|
||||
- sudo pip install -r requirements.txt
|
||||
script:
|
||||
- python scripts/lint.py
|
||||
- python scripts/readme.py
|
||||
- python scripts/tdd.py
|
||||
- python3 website/main.py
|
||||
after_success:
|
||||
- chmod +x .travis/push.sh
|
||||
- .travis/push.sh
|
||||
group: deprecated-2017Q4
|
||||
env:
|
||||
global:
|
||||
- secure: RucoyHikFKD7yQq7FBHxOpwYSHSFYUO7QS/5VEXvU55AMnHwB97aI0DcQSMa+XHaSFVsqd4fR7nAP+5H6GMW/lUhIdeXIGzehgBTfuNeQmng2djGgS1lWY9fEOsn2XEL7JlXMi2P5YdZDpOAfiiLqT3W8EaCWDdV60tkizbSQhig2R3exI/649AjmGkIws+NqoYqrEfNpnTvgxJkp2jNuKfBkr0aaVdYuxdI6Kf2KnipEeuKsKJFds+tTjduEUKTg7I8lNSB+tQ9wIHNTDZffZrzODzE2esAZtnflxhkGQ6q7fW8DEj0rheuer+yD4WBWfph1CIxTL6B3VZgT6XQXCu09XzqgRUack0KIS6SBRKjRYJymH3eKNlxZGPpk4s90bX0Qo0a0vvcT4g/iejyVb917pcn2LjRZmmsFQUfJOcCJgU6EUvqNpfM9SWV8fJhaPOacvUnzDxFav3eRdDHaZYgXf0tzJfLAjsTv7rFbLZEnpqtvyKbHrXYLf9sICyPlHbCy4L5KAfguu735v0YPXko5Aabl6PvGcfafyLxVUb/0Y5ot3pLtGVJflfHeqYz8qbkoqp5RovSvTXntx/vVlx20TSE/rQP2l6JUNt98sGFJ+yOZ3SkMnyMdjE1YqeEngxZdzukec2SM3PtnaWxSbxV8Ue1XnM8D5nzhTf4UI8=
|
||||
language: python
|
||||
cache:
|
||||
directories:
|
||||
- __pycache__
|
||||
python:
|
||||
- "3.6"
|
||||
before_install:
|
||||
- sudo pip install -r requirements.txt
|
||||
script:
|
||||
- python scripts/lint.py
|
||||
- python scripts/readme.py
|
||||
- python scripts/tdd.py
|
||||
- python3 website/main.py
|
||||
after_success:
|
||||
- chmod +x .travis/push.sh
|
||||
- .travis/push.sh
|
||||
group: deprecated-2017Q4
|
||||
env:
|
||||
global:
|
||||
- secure: RucoyHikFKD7yQq7FBHxOpwYSHSFYUO7QS/5VEXvU55AMnHwB97aI0DcQSMa+XHaSFVsqd4fR7nAP+5H6GMW/lUhIdeXIGzehgBTfuNeQmng2djGgS1lWY9fEOsn2XEL7JlXMi2P5YdZDpOAfiiLqT3W8EaCWDdV60tkizbSQhig2R3exI/649AjmGkIws+NqoYqrEfNpnTvgxJkp2jNuKfBkr0aaVdYuxdI6Kf2KnipEeuKsKJFds+tTjduEUKTg7I8lNSB+tQ9wIHNTDZffZrzODzE2esAZtnflxhkGQ6q7fW8DEj0rheuer+yD4WBWfph1CIxTL6B3VZgT6XQXCu09XzqgRUack0KIS6SBRKjRYJymH3eKNlxZGPpk4s90bX0Qo0a0vvcT4g/iejyVb917pcn2LjRZmmsFQUfJOcCJgU6EUvqNpfM9SWV8fJhaPOacvUnzDxFav3eRdDHaZYgXf0tzJfLAjsTv7rFbLZEnpqtvyKbHrXYLf9sICyPlHbCy4L5KAfguu735v0YPXko5Aabl6PvGcfafyLxVUb/0Y5ot3pLtGVJflfHeqYz8qbkoqp5RovSvTXntx/vVlx20TSE/rQP2l6JUNt98sGFJ+yOZ3SkMnyMdjE1YqeEngxZdzukec2SM3PtnaWxSbxV8Ue1XnM8D5nzhTf4UI8=
|
||||
|
||||
@ -1,44 +1,44 @@
|
||||
#!/bin/bash
|
||||
setup_git() {
|
||||
git config --global user.email "mst10041967@gmail.com"
|
||||
git config --global user.name "Rohit Tanwar"
|
||||
}
|
||||
|
||||
commit_website_files() {
|
||||
if [ $TRAVIS_EVENT_TYPE != "pull_request" ]; then
|
||||
if [ $TRAVIS_BRANCH == "master" ]; then
|
||||
git checkout master
|
||||
echo "Committing to master branch..."
|
||||
git add -A
|
||||
echo "All files added"
|
||||
git status
|
||||
if [ $TRAVIS_EVENT_TYPE == "cron" ]; then
|
||||
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [cron]"
|
||||
elif [ $TRAVIS_EVENT_TYPE == "api" ]; then
|
||||
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [custom]"
|
||||
else
|
||||
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER"
|
||||
fi
|
||||
echo "Files commited"
|
||||
git status
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
upload_files() {
|
||||
if [ $TRAVIS_EVENT_TYPE != "pull_request" ]; then
|
||||
if [ $TRAVIS_BRANCH == "master" ]; then
|
||||
echo "Pushing to master branch..."
|
||||
git push --force "https://${GH_TOKEN}@github.com/kriadmin/30-seconds-of-python-code.git" master > /dev/null 2>&1
|
||||
echo "Pushing done"
|
||||
echo "Pushing to website"
|
||||
git subtree push --prefix website "https://${GH_TOKEN}@github.com/kriadmin/30-seconds-of-python-code.git" website
|
||||
echo "Pushed to master branch"
|
||||
git status
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
setup_git
|
||||
commit_website_files
|
||||
upload_files
|
||||
#!/bin/bash
|
||||
setup_git() {
|
||||
git config --global user.email "mst10041967@gmail.com"
|
||||
git config --global user.name "Rohit Tanwar"
|
||||
}
|
||||
|
||||
commit_website_files() {
|
||||
if [ $TRAVIS_EVENT_TYPE != "pull_request" ]; then
|
||||
if [ $TRAVIS_BRANCH == "master" ]; then
|
||||
git checkout master
|
||||
echo "Committing to master branch..."
|
||||
git add -A
|
||||
echo "All files added"
|
||||
git status
|
||||
if [ $TRAVIS_EVENT_TYPE == "cron" ]; then
|
||||
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [cron]"
|
||||
elif [ $TRAVIS_EVENT_TYPE == "api" ]; then
|
||||
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [custom]"
|
||||
else
|
||||
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER"
|
||||
fi
|
||||
echo "Files commited"
|
||||
git status
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
upload_files() {
|
||||
if [ $TRAVIS_EVENT_TYPE != "pull_request" ]; then
|
||||
if [ $TRAVIS_BRANCH == "master" ]; then
|
||||
echo "Pushing to master branch..."
|
||||
git push --force "https://${GH_TOKEN}@github.com/kriadmin/30-seconds-of-python-code.git" master > /dev/null 2>&1
|
||||
echo "Pushing done"
|
||||
echo "Pushing to website"
|
||||
git subtree push --prefix website "https://${GH_TOKEN}@github.com/kriadmin/30-seconds-of-python-code.git" website
|
||||
echo "Pushed to master branch"
|
||||
git status
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
setup_git
|
||||
commit_website_files
|
||||
upload_files
|
||||
|
||||
@ -1,73 +1,73 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, gender identity and expression, level of experience,
|
||||
education, socio-economic status, nationality, personal appearance, race,
|
||||
religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at [mst10041967@gmail.com]. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, gender identity and expression, level of experience,
|
||||
education, socio-economic status, nationality, personal appearance, race,
|
||||
religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at [mst10041967@gmail.com]. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
140
CONTRIBUTING.md
140
CONTRIBUTING.md
@ -1,70 +1,70 @@
|
||||
## Contributing
|
||||
|
||||
**30 seconds of python code** is a community effort, so feel free to contribute in any way you can. Every contribution helps!
|
||||
|
||||
Here's what you can do to help:
|
||||
|
||||
- [Open issues](https://github.com/kriadmin/30-seconds-of-python-code/issues/new) for things you want to see added or modified.
|
||||
- Be part of the discussion by helping out with [existing issues](https://github.com/kriadmin/30-seconds-of-python-code/issues) or talking on our [gitter channel](https://gitter.im/30-seconds-of-python-code/Lobby).
|
||||
- Submit [pull requests](https://github.com/kriadmin/30-seconds-of-python-code/pulls) with snippets you have created (see below for guidelines).
|
||||
- Fix typos in existing snippets, improve snippet descriptions and explanations or provide better examples.
|
||||
- Before submitting a PR for any new snippets go through [this](https://github.com/kriadmin/30-seconds-of-python-code/projects/1) project. If your snippet is not there, then go ahead and submit a PR. Else if it is in the done column, sorry it has been already implemented.If it is in any other column submit a PR and give the card's link in the description section of PR.
|
||||
- **Working on your first Pull Request?** You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)
|
||||
|
||||
### Snippet submission and Pull request guidelines
|
||||
|
||||
- **DO NOT MODIFY THE README.md FILE!** Make changes to individual snippet files. The `travis_ci` automatically builds the `README.md` file when your pull request is merged.
|
||||
- **Snippet filenames** must correspond to the title of the snippet and to the function name. For example, if your snippet is titled `### awesome_snippet` the filename should be `awesome_snippet.md` and the function name should be `awesome_snippet`.
|
||||
- Use `snake_case`, not `kebab-case` or `camelCase`.
|
||||
- Avoid capitalization of words.
|
||||
- Please follow the (PEP8)[https://www.python.org/dev/peps/pep-0008/] guidelines.
|
||||
- **Snippet titles** should have be the same as the name of the function that is present in the snippet.
|
||||
- All snippet titles must be prefixed with `###` and be at the very first line of your snippet.
|
||||
- Snippet titles must be unique (although if you cannot find a better title, just add some placeholder at the end of the filename and title and we will figure it out).
|
||||
- Follow snippet titles with an empty line.
|
||||
- **Snippet descriptions** must be short and to the point. Try to explain *what* the snippet does and *how* the snippet works and what **inbuilt** features/modules are used. Remember to include what functions you are using and why.
|
||||
- Follow snippet descriptions with an empty line.
|
||||
- **Snippets _CAN NOT_ use any external modules**. Only the modules and function inbuilt in `python 3.6` shall be used.
|
||||
- **Snippet code** must be enclosed inside ` ```python ` and ` ``` `.
|
||||
- Remember to start your snippet's code on a new line below the opening backticks.
|
||||
- You can write the code in any style you like but eventually it will be formated by our prettifier so the formatting will change. Just make sure to have consistent spacing.
|
||||
- Try to keep your snippets' code short and to the point. Use modern techniques and features. Make sure to test your code before submitting.
|
||||
- All snippets must be followed by one (more if necessary) test case after the code, in a new block enclosed inside ` ```python ` and ` ``` `. The syntax for this is `my_function('test_input') # 'test_output'`. Use multiline examples only if necessary.
|
||||
- Try to make your function name unique, so that it does not conflict with existing snippets.
|
||||
- Snippet functions do not have to handle errors in input, unless it's necessary (e.g. a mathematical function that cannot be extended to negative numbers should handle negative input appropriately).
|
||||
- Snippets should be short (usually below 20 - 30 lines). If your snippet is longer than that, you can still submit it, and we can help you shorten it or figure out ways to improve it.
|
||||
- Snippets *should* solve real-world problems, no matter how simple.
|
||||
- Snippets *should* be abstract enough to be applied to different scenarios.
|
||||
- It is not mandatory but highly appreciated if you provide **test cases** and/or performance tests.
|
||||
- You can start creating a new snippet, by using the [snippet template](snippet_template.md) to format your snippets.
|
||||
- Updating the README.md file should only be done by altering the scripts in the **scripts** folder or altering their relative static parts in the **static-parts** folder.
|
||||
- You may tag your snippet in tag_databse although it is _not_ necessary.
|
||||
- You may also run `scripts\lint.py` & `scripts\readme.py`.
|
||||
|
||||
<!--
|
||||
### Additional guidelines and conventions regarding snippets
|
||||
|
||||
- If your snippet contains argument with default parameters, explain what happens if they are omitted when calling the function and what the default case is.
|
||||
- If your snippet uses recursion, explain the base cases.
|
||||
- If your variable is not changed anywhere in the code name it in uppercase.
|
||||
- Use `camelCase` for function and variable names if they consist of more than one word.
|
||||
- Try to give meaningful names to variables. For example use `letter`, instead of `lt`. Some exceptions to convention are:
|
||||
- `arr` for lists (usually as the snippet function's argument).
|
||||
- `str` for strings.
|
||||
- `n` for a numeric value (usually as the snippet function's argument).
|
||||
- `val` or `v` for value (usually when iterating a list, mapping, sorting etc.).
|
||||
- `i` for indexes.
|
||||
- `func` for function arguments.
|
||||
- `nums` for lists of numbers.
|
||||
- Use `()` if your function takes no arguments.
|
||||
- Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to.
|
||||
- If your snippet's function takes variadic arguments, use `...args` (although in certain cases, it might be needed to use a different name).
|
||||
- Always use single quotes for string literals.
|
||||
- Prefer using the ternary operator (`trueResult if condition else falseResult`) instead of `if else` statements whenever possible.
|
||||
- Avoid nesting ternary operators (but you can do it if you feel like you should).
|
||||
- You should define multiple variables on the same line (e.g. `x,y = 0,1`) on the same line whenever possible.
|
||||
- Do not use trailing or leading underscores in variable names(unless it is a helper function).
|
||||
- Use lambda functions as much as possible, except when you can't.
|
||||
- Leave a single space after a comma (`,`) character.
|
||||
- Try to strike a balance between readability, brevity, and performance.
|
||||
- Never use `eval()`. Your snippet will be disqualified immediately.-->
|
||||
## Contributing
|
||||
|
||||
**30 seconds of python code** is a community effort, so feel free to contribute in any way you can. Every contribution helps!
|
||||
|
||||
Here's what you can do to help:
|
||||
|
||||
- [Open issues](https://github.com/kriadmin/30-seconds-of-python-code/issues/new) for things you want to see added or modified.
|
||||
- Be part of the discussion by helping out with [existing issues](https://github.com/kriadmin/30-seconds-of-python-code/issues) or talking on our [gitter channel](https://gitter.im/30-seconds-of-python-code/Lobby).
|
||||
- Submit [pull requests](https://github.com/kriadmin/30-seconds-of-python-code/pulls) with snippets you have created (see below for guidelines).
|
||||
- Fix typos in existing snippets, improve snippet descriptions and explanations or provide better examples.
|
||||
- Before submitting a PR for any new snippets go through [this](https://github.com/kriadmin/30-seconds-of-python-code/projects/1) project. If your snippet is not there, then go ahead and submit a PR. Else if it is in the done column, sorry it has been already implemented.If it is in any other column submit a PR and give the card's link in the description section of PR.
|
||||
- **Working on your first Pull Request?** You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)
|
||||
|
||||
### Snippet submission and Pull request guidelines
|
||||
|
||||
- **DO NOT MODIFY THE README.md FILE!** Make changes to individual snippet files. The `travis_ci` automatically builds the `README.md` file when your pull request is merged.
|
||||
- **Snippet filenames** must correspond to the title of the snippet and to the function name. For example, if your snippet is titled `### awesome_snippet` the filename should be `awesome_snippet.md` and the function name should be `awesome_snippet`.
|
||||
- Use `snake_case`, not `kebab-case` or `camelCase`.
|
||||
- Avoid capitalization of words.
|
||||
- Please follow the (PEP8)[https://www.python.org/dev/peps/pep-0008/] guidelines.
|
||||
- **Snippet titles** should have be the same as the name of the function that is present in the snippet.
|
||||
- All snippet titles must be prefixed with `###` and be at the very first line of your snippet.
|
||||
- Snippet titles must be unique (although if you cannot find a better title, just add some placeholder at the end of the filename and title and we will figure it out).
|
||||
- Follow snippet titles with an empty line.
|
||||
- **Snippet descriptions** must be short and to the point. Try to explain *what* the snippet does and *how* the snippet works and what **inbuilt** features/modules are used. Remember to include what functions you are using and why.
|
||||
- Follow snippet descriptions with an empty line.
|
||||
- **Snippets _CAN NOT_ use any external modules**. Only the modules and function inbuilt in `python 3.6` shall be used.
|
||||
- **Snippet code** must be enclosed inside ` ```python ` and ` ``` `.
|
||||
- Remember to start your snippet's code on a new line below the opening backticks.
|
||||
- You can write the code in any style you like but eventually it will be formated by our prettifier so the formatting will change. Just make sure to have consistent spacing.
|
||||
- Try to keep your snippets' code short and to the point. Use modern techniques and features. Make sure to test your code before submitting.
|
||||
- All snippets must be followed by one (more if necessary) test case after the code, in a new block enclosed inside ` ```python ` and ` ``` `. The syntax for this is `my_function('test_input') # 'test_output'`. Use multiline examples only if necessary.
|
||||
- Try to make your function name unique, so that it does not conflict with existing snippets.
|
||||
- Snippet functions do not have to handle errors in input, unless it's necessary (e.g. a mathematical function that cannot be extended to negative numbers should handle negative input appropriately).
|
||||
- Snippets should be short (usually below 20 - 30 lines). If your snippet is longer than that, you can still submit it, and we can help you shorten it or figure out ways to improve it.
|
||||
- Snippets *should* solve real-world problems, no matter how simple.
|
||||
- Snippets *should* be abstract enough to be applied to different scenarios.
|
||||
- It is not mandatory but highly appreciated if you provide **test cases** and/or performance tests.
|
||||
- You can start creating a new snippet, by using the [snippet template](snippet_template.md) to format your snippets.
|
||||
- Updating the README.md file should only be done by altering the scripts in the **scripts** folder or altering their relative static parts in the **static-parts** folder.
|
||||
- You may tag your snippet in tag_databse although it is _not_ necessary.
|
||||
- You may also run `scripts\lint.py` & `scripts\readme.py`.
|
||||
|
||||
<!--
|
||||
### Additional guidelines and conventions regarding snippets
|
||||
|
||||
- If your snippet contains argument with default parameters, explain what happens if they are omitted when calling the function and what the default case is.
|
||||
- If your snippet uses recursion, explain the base cases.
|
||||
- If your variable is not changed anywhere in the code name it in uppercase.
|
||||
- Use `camelCase` for function and variable names if they consist of more than one word.
|
||||
- Try to give meaningful names to variables. For example use `letter`, instead of `lt`. Some exceptions to convention are:
|
||||
- `arr` for lists (usually as the snippet function's argument).
|
||||
- `str` for strings.
|
||||
- `n` for a numeric value (usually as the snippet function's argument).
|
||||
- `val` or `v` for value (usually when iterating a list, mapping, sorting etc.).
|
||||
- `i` for indexes.
|
||||
- `func` for function arguments.
|
||||
- `nums` for lists of numbers.
|
||||
- Use `()` if your function takes no arguments.
|
||||
- Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to.
|
||||
- If your snippet's function takes variadic arguments, use `...args` (although in certain cases, it might be needed to use a different name).
|
||||
- Always use single quotes for string literals.
|
||||
- Prefer using the ternary operator (`trueResult if condition else falseResult`) instead of `if else` statements whenever possible.
|
||||
- Avoid nesting ternary operators (but you can do it if you feel like you should).
|
||||
- You should define multiple variables on the same line (e.g. `x,y = 0,1`) on the same line whenever possible.
|
||||
- Do not use trailing or leading underscores in variable names(unless it is a helper function).
|
||||
- Use lambda functions as much as possible, except when you can't.
|
||||
- Leave a single space after a comma (`,`) character.
|
||||
- Try to strike a balance between readability, brevity, and performance.
|
||||
- Never use `eval()`. Your snippet will be disqualified immediately.-->
|
||||
|
||||
@ -1,2 +1,2 @@
|
||||
[tape]
|
||||
[tape]
|
||||
python_files=*.test.py
|
||||
24
contributor_database
Normal file
24
contributor_database
Normal file
@ -0,0 +1,24 @@
|
||||
average:[Rohit Tanwar](@kriadmin)
|
||||
chunk:[Rohit Tanwar](@kriadmin)
|
||||
compact:[Rohit Tanwar](@kriadmin)
|
||||
count_occurences:[Rohit Tanwar](@kriadmin)
|
||||
count_vowels:[Rohit Tanwar](@kriadmin)
|
||||
deep_flatten:[Rohit Tanwar](@kriadmin)
|
||||
difference:[Rohit Tanwar](@kriadmin)
|
||||
factorial:[Rohit Tanwar](@kriadmin)
|
||||
gcd:[Rohit Tanwar](@kriadmin)
|
||||
lcm:[Rohit Tanwar](@kriadmin)
|
||||
max_n:[Rohit Tanwar](@kriadmin)
|
||||
min_n:[Rohit Tanwar](@kriadmin)
|
||||
shuffle:[Rohit Tanwar](@kriadmin)
|
||||
spread:[Rohit Tanwar](@kriadmin)
|
||||
zip:[Rohit Tanwar](@kriadmin)
|
||||
byte_size:[Rohit Tanwar](@kriadmin)
|
||||
capitalize:[Rohit Tanwar](@kriadmin)
|
||||
capitalize_every_word:[Rohit Tanwar](@kriadmin)
|
||||
decapitalize:[Rohit Tanwar](@kriadmin)
|
||||
palindrome:[Rohit Tanwar](@kriadmin)
|
||||
is_upper_case:[Rohit Tanwar](@kriadmin)
|
||||
is_lower_case:[Rohit Tanwar](@kriadmin)
|
||||
count_by:[Rohit Tanwar](@kriadmin)
|
||||
difference_by:[Rohit Tanwar](@kriadmin)
|
||||
@ -1,16 +1,16 @@
|
||||
autopep8==1.3.3
|
||||
cffi==1.11.4
|
||||
click==6.7
|
||||
emoji==0.4.5
|
||||
Flask==0.12.2
|
||||
Flask-OAuth==0.12
|
||||
gunicorn==19.7.1
|
||||
httplib2==0.10.3
|
||||
itsdangerous==0.24
|
||||
Jinja2==2.10
|
||||
MarkupSafe==1.0
|
||||
misaka==2.1.0
|
||||
mistune==0.8.3
|
||||
oauth2==1.9.0.post1
|
||||
pycparser==2.18
|
||||
autopep8==1.3.3
|
||||
cffi==1.11.4
|
||||
click==6.7
|
||||
emoji==0.4.5
|
||||
Flask==0.12.2
|
||||
Flask-OAuth==0.12
|
||||
gunicorn==19.7.1
|
||||
httplib2==0.10.3
|
||||
itsdangerous==0.24
|
||||
Jinja2==2.10
|
||||
MarkupSafe==1.0
|
||||
misaka==2.1.0
|
||||
mistune==0.8.3
|
||||
oauth2==1.9.0.post1
|
||||
pycparser==2.18
|
||||
Werkzeug==0.14.1
|
||||
@ -1,18 +1,18 @@
|
||||
import autopep8
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
print(sys.version)
|
||||
files = os.listdir('snippets')
|
||||
codeRe = "```\s*python([\s\S]*?)```"
|
||||
for file in files:
|
||||
someFile = open("snippets/" + file)
|
||||
fileData = someFile.read()
|
||||
someFile.close()
|
||||
originalCode = re.search(codeRe,fileData).group(0)
|
||||
#print(re.split(codeRe,fileData)[0])
|
||||
formatedCode = '\n'+autopep8.fix_code(re.split(codeRe,fileData)[1]).strip()+'\n'
|
||||
fileToSave = fileData.replace(originalCode,('```python'+formatedCode+'```'))
|
||||
someFile = open("snippets/"+file,'w')
|
||||
someFile.write(fileToSave)
|
||||
import autopep8
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
print(sys.version)
|
||||
files = os.listdir('snippets')
|
||||
codeRe = "```\s*python([\s\S]*?)```"
|
||||
for file in files:
|
||||
someFile = open("snippets/" + file)
|
||||
fileData = someFile.read()
|
||||
someFile.close()
|
||||
originalCode = re.search(codeRe,fileData).group(0)
|
||||
#print(re.split(codeRe,fileData)[0])
|
||||
formatedCode = '\n'+autopep8.fix_code(re.split(codeRe,fileData)[1]).strip()+'\n'
|
||||
fileToSave = fileData.replace(originalCode,('```python'+formatedCode+'```'))
|
||||
someFile = open("snippets/"+file,'w')
|
||||
someFile.write(fileToSave)
|
||||
someFile.close()
|
||||
@ -1,51 +1,51 @@
|
||||
import re
|
||||
codeRe = "```\s*python([\s\S]*?)```"
|
||||
def title_case(str):
|
||||
return str[:1].upper() + str[1:].lower()
|
||||
EMOJIS = {
|
||||
'adapter': ':electric_plug:',
|
||||
'list': ':books:',
|
||||
'browser': ':globe_with_meridians:',
|
||||
'date': ':stopwatch:',
|
||||
'function': ':control_knobs:',
|
||||
'logic': ':crystal_ball:',
|
||||
'math': ':heavy_division_sign:',
|
||||
'media': ':tv:',
|
||||
'node': ':package:',
|
||||
'object': 'card_file_box',
|
||||
'string': ':scroll:',
|
||||
'type': ':page_with_curl:',
|
||||
'utility': ':wrench:'
|
||||
}
|
||||
def tagger():
|
||||
tag_data = open('tag_database').read()
|
||||
tag_dict = {}
|
||||
tag_list = tag_data.split('\n')
|
||||
for tag in tag_list:
|
||||
category = tag.split(':')[1]
|
||||
snippet = tag.split(':')[0]
|
||||
if category in tag_dict:
|
||||
tag_dict[category].append(snippet)
|
||||
else:
|
||||
tag_dict[category] = [snippet]
|
||||
return tag_dict
|
||||
|
||||
start = open("static-parts/readme-start.md").read() + '\n\n'
|
||||
end = open("static-parts/readme-end.md").read()
|
||||
toAppend = ''
|
||||
tag_dict = tagger()
|
||||
toAppend += '## Table of Contents \n'
|
||||
for category in tag_dict:
|
||||
toAppend = toAppend + '### ' + EMOJIS[category] + ' ' + title_case(category) +'\n\n<details><summary>View contents</summary> <ul>'
|
||||
for snippet in sorted(tag_dict[category]):
|
||||
toAppend += f'<li><a href = "#{snippet}"><code>{snippet}</code></a></li>\n'
|
||||
toAppend += '</ul></details>\n\n'
|
||||
toAppend += '<hr></hr> \n\n'
|
||||
for category in tag_dict:
|
||||
toAppend = toAppend + '## ' + EMOJIS[category] + ' ' + title_case(category) +'\n\n'
|
||||
for snippet in sorted(tag_dict[category]):
|
||||
someFile = open("snippets/" + snippet + '.md')
|
||||
fileData = someFile.read()
|
||||
codeParts = re.split(codeRe,fileData)
|
||||
toAppend += codeParts[0] + '```py{codeParts[1]} \n ```'.format(codeParts= codeParts) +codeParts[2] + '<details><summary>View Examples</summary>\n\n```py\n{codeParts[3]}\n```\n</details>\n\n<br><a href = "#table-of-contents">:arrow_up: Back to top</a>\n '.format(codeParts=codeParts) + '\n'
|
||||
import re
|
||||
codeRe = "```\s*python([\s\S]*?)```"
|
||||
def title_case(str):
|
||||
return str[:1].upper() + str[1:].lower()
|
||||
EMOJIS = {
|
||||
'adapter': ':electric_plug:',
|
||||
'list': ':books:',
|
||||
'browser': ':globe_with_meridians:',
|
||||
'date': ':stopwatch:',
|
||||
'function': ':control_knobs:',
|
||||
'logic': ':crystal_ball:',
|
||||
'math': ':heavy_division_sign:',
|
||||
'media': ':tv:',
|
||||
'node': ':package:',
|
||||
'object': 'card_file_box',
|
||||
'string': ':scroll:',
|
||||
'type': ':page_with_curl:',
|
||||
'utility': ':wrench:'
|
||||
}
|
||||
def tagger():
|
||||
tag_data = open('tag_database').read()
|
||||
tag_dict = {}
|
||||
tag_list = tag_data.split('\n')
|
||||
for tag in tag_list:
|
||||
category = tag.split(':')[1]
|
||||
snippet = tag.split(':')[0]
|
||||
if category in tag_dict:
|
||||
tag_dict[category].append(snippet)
|
||||
else:
|
||||
tag_dict[category] = [snippet]
|
||||
return tag_dict
|
||||
|
||||
start = open("static-parts/readme-start.md").read() + '\n\n'
|
||||
end = open("static-parts/readme-end.md").read()
|
||||
toAppend = ''
|
||||
tag_dict = tagger()
|
||||
toAppend += '## Table of Contents \n'
|
||||
for category in tag_dict:
|
||||
toAppend = toAppend + '### ' + EMOJIS[category] + ' ' + title_case(category) +'\n\n<details><summary>View contents</summary> <ul>'
|
||||
for snippet in sorted(tag_dict[category]):
|
||||
toAppend += f'<li><a href = "#{snippet}"><code>{snippet}</code></a></li>\n'
|
||||
toAppend += '</ul></details>\n\n'
|
||||
toAppend += '<hr></hr> \n\n'
|
||||
for category in tag_dict:
|
||||
toAppend = toAppend + '## ' + EMOJIS[category] + ' ' + title_case(category) +'\n\n'
|
||||
for snippet in sorted(tag_dict[category]):
|
||||
someFile = open("snippets/" + snippet + '.md')
|
||||
fileData = someFile.read()
|
||||
codeParts = re.split(codeRe,fileData)
|
||||
toAppend += codeParts[0] + '```py{codeParts[1]} \n ```'.format(codeParts= codeParts) +codeParts[2] + '<details><summary>View Examples</summary>\n\n```py\n{codeParts[3]}\n```\n</details>\n\n<br><a href = "#table-of-contents">:arrow_up: Back to top</a>\n '.format(codeParts=codeParts) + '\n'
|
||||
open("README.md",'w').write(start+toAppend+'\n'+end)
|
||||
@ -1,27 +1,27 @@
|
||||
import os,re
|
||||
|
||||
codeRe = "```\s*python([\s\S]*?)```"
|
||||
|
||||
snippets = [string.replace('.md','') for string in os.listdir('snippets')]
|
||||
|
||||
for snippet in snippets:
|
||||
os.makedirs('test/' + snippet,exist_ok=True)
|
||||
with open(f'snippets/{snippet}.md','r') as f:
|
||||
content = f.read()
|
||||
code = re.search(codeRe,content).group(1).strip()
|
||||
file_to_write_to = open(f'test/{snippet}/{snippet}.py','w')
|
||||
file_to_write_to.write(code)
|
||||
file_to_write_to.close()
|
||||
if not os.path.isfile(f'test/{snippet}/{snippet}.test.py'):
|
||||
test_file = open(f'test/{snippet}/{snippet}.test.py','w')
|
||||
test_file.write(f'''
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from {snippet} import {snippet}
|
||||
def {snippet}_test(t):
|
||||
t.true(isinstance({snippet}, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'{snippet} is a function')
|
||||
test('Testing {snippet}',{snippet}_test)
|
||||
'''.strip())
|
||||
test_file.close()
|
||||
else:
|
||||
import os,re
|
||||
|
||||
codeRe = "```\s*python([\s\S]*?)```"
|
||||
|
||||
snippets = [string.replace('.md','') for string in os.listdir('snippets')]
|
||||
|
||||
for snippet in snippets:
|
||||
os.makedirs('test/' + snippet,exist_ok=True)
|
||||
with open(f'snippets/{snippet}.md','r') as f:
|
||||
content = f.read()
|
||||
code = re.search(codeRe,content).group(1).strip()
|
||||
file_to_write_to = open(f'test/{snippet}/{snippet}.py','w')
|
||||
file_to_write_to.write(code)
|
||||
file_to_write_to.close()
|
||||
if not os.path.isfile(f'test/{snippet}/{snippet}.test.py'):
|
||||
test_file = open(f'test/{snippet}/{snippet}.test.py','w')
|
||||
test_file.write(f'''
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from {snippet} import {snippet}
|
||||
def {snippet}_test(t):
|
||||
t.true(isinstance({snippet}, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'{snippet} is a function')
|
||||
test('Testing {snippet}',{snippet}_test)
|
||||
'''.strip())
|
||||
test_file.close()
|
||||
else:
|
||||
pass
|
||||
@ -1,15 +1,15 @@
|
||||
### function_name
|
||||
|
||||
Describe briefly what the function does
|
||||
|
||||
Explain your method and the functions used.
|
||||
|
||||
``` python
|
||||
def function_name(args):
|
||||
# code
|
||||
return 0
|
||||
```
|
||||
|
||||
``` python
|
||||
function_name(val) # result
|
||||
```
|
||||
### function_name
|
||||
|
||||
Describe briefly what the function does
|
||||
|
||||
Explain your method and the functions used.
|
||||
|
||||
``` python
|
||||
def function_name(args):
|
||||
# code
|
||||
return 0
|
||||
```
|
||||
|
||||
``` python
|
||||
function_name(val) # result
|
||||
```
|
||||
|
||||
@ -1,17 +1,17 @@
|
||||
### average
|
||||
|
||||
:information_source: Already implemented via `statistics.mean`. `statistics.mean` takes an array as an argument whereas this function takes variadic arguments.
|
||||
|
||||
Returns the average of two or more numbers.
|
||||
|
||||
Takes the sum of all the `args` and divides it by `len(args)`. The secind argument `0.0` in sum is to handle floating point division in `python2`.
|
||||
|
||||
```python
|
||||
def average(*args):
|
||||
return sum(args, 0.0) / len(args)
|
||||
```
|
||||
|
||||
``` python
|
||||
average(*[1, 2, 3]) # 2.0
|
||||
average(1, 2, 3) # 2.0
|
||||
### average
|
||||
|
||||
:information_source: Already implemented via `statistics.mean`. `statistics.mean` takes an array as an argument whereas this function takes variadic arguments.
|
||||
|
||||
Returns the average of two or more numbers.
|
||||
|
||||
Takes the sum of all the `args` and divides it by `len(args)`. The secind argument `0.0` in sum is to handle floating point division in `python2`.
|
||||
|
||||
```python
|
||||
def average(*args):
|
||||
return sum(args, 0.0) / len(args)
|
||||
```
|
||||
|
||||
``` python
|
||||
average(*[1, 2, 3]) # 2.0
|
||||
average(1, 2, 3) # 2.0
|
||||
```
|
||||
@ -1,15 +1,15 @@
|
||||
### byte_size
|
||||
|
||||
Returns the length of a string in bytes.
|
||||
|
||||
`utf-8` encodes a given string and find its length.
|
||||
|
||||
```python
|
||||
def byte_size(string):
|
||||
return(len(string.encode('utf-8')))
|
||||
```
|
||||
|
||||
```python
|
||||
byte_size('😀') # 4
|
||||
byte_size('Hello World') # 11
|
||||
### byte_size
|
||||
|
||||
Returns the length of a string in bytes.
|
||||
|
||||
`utf-8` encodes a given string and find its length.
|
||||
|
||||
```python
|
||||
def byte_size(string):
|
||||
return(len(string.encode('utf-8')))
|
||||
```
|
||||
|
||||
```python
|
||||
byte_size('😀') # 4
|
||||
byte_size('Hello World') # 11
|
||||
```
|
||||
@ -1,15 +1,15 @@
|
||||
### capitalize
|
||||
|
||||
Capitalizes the first letter of a string.
|
||||
|
||||
Capitalizes the fist letter of the sring and then adds it with rest of the string. Omit the `lower_rest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
|
||||
|
||||
```python
|
||||
def capitalize(string, lower_rest=False):
|
||||
return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])
|
||||
```
|
||||
|
||||
```python
|
||||
capitalize('fooBar') # 'FooBar'
|
||||
capitalize('fooBar', True) # 'Foobar'
|
||||
### capitalize
|
||||
|
||||
Capitalizes the first letter of a string.
|
||||
|
||||
Capitalizes the fist letter of the sring and then adds it with rest of the string. Omit the `lower_rest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
|
||||
|
||||
```python
|
||||
def capitalize(string, lower_rest=False):
|
||||
return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])
|
||||
```
|
||||
|
||||
```python
|
||||
capitalize('fooBar') # 'FooBar'
|
||||
capitalize('fooBar', True) # 'Foobar'
|
||||
```
|
||||
@ -1,14 +1,14 @@
|
||||
### capitalize_every_word
|
||||
|
||||
Capitalizes the first letter of every word in a string.
|
||||
|
||||
Uses `str.title` to capitalize first letter of evry word in the string.
|
||||
|
||||
```python
|
||||
def capitalize_every_word(string):
|
||||
return string.title()
|
||||
```
|
||||
|
||||
```python
|
||||
capitalize_every_word('hello world!') # 'Hello World!'
|
||||
### capitalize_every_word
|
||||
|
||||
Capitalizes the first letter of every word in a string.
|
||||
|
||||
Uses `str.title` to capitalize first letter of evry word in the string.
|
||||
|
||||
```python
|
||||
def capitalize_every_word(string):
|
||||
return string.title()
|
||||
```
|
||||
|
||||
```python
|
||||
capitalize_every_word('hello world!') # 'Hello World!'
|
||||
```
|
||||
@ -1,19 +1,19 @@
|
||||
### chunk
|
||||
|
||||
Chunks an array into smaller lists of a specified size.
|
||||
|
||||
Uses `range` to create a list of desired size. Then use `map` on this list and fill it with splices of `arr`.
|
||||
|
||||
```python
|
||||
from math import ceil
|
||||
|
||||
|
||||
def chunk(arr, size):
|
||||
return list(
|
||||
map(lambda x: arr[x * size:x * size + size],
|
||||
list(range(0, ceil(len(arr) / size)))))
|
||||
```
|
||||
|
||||
``` python
|
||||
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
|
||||
```
|
||||
### chunk
|
||||
|
||||
Chunks an array into smaller lists of a specified size.
|
||||
|
||||
Uses `range` to create a list of desired size. Then use `map` on this list and fill it with splices of `arr`.
|
||||
|
||||
```python
|
||||
from math import ceil
|
||||
|
||||
|
||||
def chunk(arr, size):
|
||||
return list(
|
||||
map(lambda x: arr[x * size:x * size + size],
|
||||
list(range(0, ceil(len(arr) / size)))))
|
||||
```
|
||||
|
||||
``` python
|
||||
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
|
||||
```
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
### compact
|
||||
|
||||
Removes falsey values from a list.
|
||||
|
||||
Use `filter()` to filter out falsey values (False, None, 0, and "").
|
||||
|
||||
```python
|
||||
def compact(arr):
|
||||
return list(filter(lambda x: bool(x), arr))
|
||||
```
|
||||
|
||||
``` python
|
||||
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
|
||||
### compact
|
||||
|
||||
Removes falsey values from a list.
|
||||
|
||||
Use `filter()` to filter out falsey values (False, None, 0, and "").
|
||||
|
||||
```python
|
||||
def compact(arr):
|
||||
return list(filter(lambda x: bool(x), arr))
|
||||
```
|
||||
|
||||
``` python
|
||||
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
|
||||
```
|
||||
@ -1,22 +1,22 @@
|
||||
### count_by
|
||||
|
||||
:information_source: Already implemented via `collections.Counter`
|
||||
|
||||
Groups the elements of a list based on the given function and returns the count of elements in each group.
|
||||
|
||||
Use `map()` to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs.
|
||||
|
||||
```python
|
||||
def count_by(arr, fn=lambda x: x):
|
||||
key = {}
|
||||
for el in map(fn, arr):
|
||||
key[el] = 0 if not el in key else key[el]
|
||||
key[el] += 1
|
||||
return key
|
||||
```
|
||||
|
||||
``` python
|
||||
from math import floor
|
||||
count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2}
|
||||
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}
|
||||
### count_by
|
||||
|
||||
:information_source: Already implemented via `collections.Counter`
|
||||
|
||||
Groups the elements of a list based on the given function and returns the count of elements in each group.
|
||||
|
||||
Use `map()` to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs.
|
||||
|
||||
```python
|
||||
def count_by(arr, fn=lambda x: x):
|
||||
key = {}
|
||||
for el in map(fn, arr):
|
||||
key[el] = 0 if not el in key else key[el]
|
||||
key[el] += 1
|
||||
return key
|
||||
```
|
||||
|
||||
``` python
|
||||
from math import floor
|
||||
count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2}
|
||||
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}
|
||||
```
|
||||
@ -1,18 +1,18 @@
|
||||
### count_occurences
|
||||
|
||||
:information_source: Already implemented via `list.count()`.
|
||||
|
||||
Counts the occurrences of a value in an list.
|
||||
|
||||
Uses the `reduce` functin from built-in module `functools` to increment a counter each time you encounter the specific value inside the list.
|
||||
|
||||
```python
|
||||
def count_occurences(arr, val):
|
||||
return reduce(
|
||||
(lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
|
||||
arr)
|
||||
```
|
||||
|
||||
```python
|
||||
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
|
||||
### count_occurences
|
||||
|
||||
:information_source: Already implemented via `list.count()`.
|
||||
|
||||
Counts the occurrences of a value in an list.
|
||||
|
||||
Uses the `reduce` functin from built-in module `functools` to increment a counter each time you encounter the specific value inside the list.
|
||||
|
||||
```python
|
||||
def count_occurences(arr, val):
|
||||
return reduce(
|
||||
(lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
|
||||
arr)
|
||||
```
|
||||
|
||||
```python
|
||||
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
|
||||
```
|
||||
@ -1,18 +1,18 @@
|
||||
### count_vowels
|
||||
|
||||
Retuns `number` of vowels in provided `string`.
|
||||
|
||||
Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a string.
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
|
||||
def count_vowels(str):
|
||||
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))
|
||||
```
|
||||
|
||||
``` python
|
||||
count_vowels('foobar') # 3
|
||||
count_vowels('gym') # 0
|
||||
```
|
||||
### count_vowels
|
||||
|
||||
Retuns `number` of vowels in provided `string`.
|
||||
|
||||
Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a string.
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
|
||||
def count_vowels(str):
|
||||
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))
|
||||
```
|
||||
|
||||
``` python
|
||||
count_vowels('foobar') # 3
|
||||
count_vowels('gym') # 0
|
||||
```
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
### decapitalize
|
||||
|
||||
Decapitalizes the first letter of a string.
|
||||
|
||||
Decapitalizes the fist letter of the sring and then adds it with rest of the string. Omit the `upper_rest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase.
|
||||
|
||||
```python
|
||||
def decapitalize(string, upper_rest=False):
|
||||
return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])
|
||||
```
|
||||
|
||||
```python
|
||||
decapitalize('FooBar') # 'fooBar'
|
||||
decapitalize('FooBar', True) # 'fOOBAR'
|
||||
### decapitalize
|
||||
|
||||
Decapitalizes the first letter of a string.
|
||||
|
||||
Decapitalizes the fist letter of the sring and then adds it with rest of the string. Omit the `upper_rest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase.
|
||||
|
||||
```python
|
||||
def decapitalize(string, upper_rest=False):
|
||||
return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])
|
||||
```
|
||||
|
||||
```python
|
||||
decapitalize('FooBar') # 'fooBar'
|
||||
decapitalize('FooBar', True) # 'fOOBAR'
|
||||
```
|
||||
@ -1,27 +1,27 @@
|
||||
### deep_flatten
|
||||
|
||||
Deep flattens a list.
|
||||
|
||||
Use recursion. Use `list.extend()` with an empty array (`result`) and the spread function to flatten a list. Recursively flatten each element that is a list.
|
||||
|
||||
```python
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def deep_flatten(arr):
|
||||
result = []
|
||||
result.extend(
|
||||
spread(list(map(lambda x: deep(x) if type(x) == list else x, arr))))
|
||||
return result
|
||||
```
|
||||
|
||||
```python
|
||||
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
|
||||
```
|
||||
### deep_flatten
|
||||
|
||||
Deep flattens a list.
|
||||
|
||||
Use recursion. Use `list.extend()` with an empty array (`result`) and the spread function to flatten a list. Recursively flatten each element that is a list.
|
||||
|
||||
```python
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def deep_flatten(arr):
|
||||
result = []
|
||||
result.extend(
|
||||
spread(list(map(lambda x: deep(x) if type(x) == list else x, arr))))
|
||||
return result
|
||||
```
|
||||
|
||||
```python
|
||||
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
|
||||
```
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
### difference
|
||||
|
||||
Returns the difference between two arrays.
|
||||
|
||||
Create a `set` from `b`, then use list comprehension to only keep values not contained in `b`
|
||||
|
||||
```python
|
||||
def difference(a, b):
|
||||
b = set(b)
|
||||
return [item for item in a if item not in b]
|
||||
```
|
||||
``` python
|
||||
difference([1, 2, 3], [1, 2, 4]) # [3]
|
||||
### difference
|
||||
|
||||
Returns the difference between two arrays.
|
||||
|
||||
Create a `set` from `b`, then use list comprehension to only keep values not contained in `b`
|
||||
|
||||
```python
|
||||
def difference(a, b):
|
||||
b = set(b)
|
||||
return [item for item in a if item not in b]
|
||||
```
|
||||
``` python
|
||||
difference([1, 2, 3], [1, 2, 4]) # [3]
|
||||
```
|
||||
@ -1,17 +1,17 @@
|
||||
### difference_by
|
||||
|
||||
Returns the difference between two list, after applying the provided function to each list element of both.
|
||||
|
||||
Create a `set` by applying `fn` to each element in `b`, then use list comprehension in combination with fn on a to only keep values not contained in the previously created `set`.
|
||||
|
||||
```python
|
||||
def difference_by(a, b, fn):
|
||||
b = set(map(fn, b))
|
||||
return [item for item in a if fn(item) not in b]
|
||||
```
|
||||
|
||||
```python
|
||||
from math import floor
|
||||
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
|
||||
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]
|
||||
### difference_by
|
||||
|
||||
Returns the difference between two list, after applying the provided function to each list element of both.
|
||||
|
||||
Create a `set` by applying `fn` to each element in `b`, then use list comprehension in combination with fn on a to only keep values not contained in the previously created `set`.
|
||||
|
||||
```python
|
||||
def difference_by(a, b, fn):
|
||||
b = set(map(fn, b))
|
||||
return [item for item in a if fn(item) not in b]
|
||||
```
|
||||
|
||||
```python
|
||||
from math import floor
|
||||
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
|
||||
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]
|
||||
```
|
||||
@ -1,16 +1,16 @@
|
||||
### factorial
|
||||
|
||||
Calculates the factorial of a number.
|
||||
|
||||
Use recursion. If `num` is less than or equal to `1`, return `1`. Otherwise, return the product of `num` and the factorial of `num - 1`. Throws an exception if `num` is a negative or a floating point number.
|
||||
|
||||
```python
|
||||
def factorial(num):
|
||||
if not ((num >= 0) & (num % 1 == 0)):
|
||||
raise Exception(
|
||||
f"Number( {num} ) can't be floating point or negative ")
|
||||
return 1 if num == 0 else num * factorial(num - 1)
|
||||
```
|
||||
``` python
|
||||
factorial(6) # 720
|
||||
```
|
||||
### factorial
|
||||
|
||||
Calculates the factorial of a number.
|
||||
|
||||
Use recursion. If `num` is less than or equal to `1`, return `1`. Otherwise, return the product of `num` and the factorial of `num - 1`. Throws an exception if `num` is a negative or a floating point number.
|
||||
|
||||
```python
|
||||
def factorial(num):
|
||||
if not ((num >= 0) & (num % 1 == 0)):
|
||||
raise Exception(
|
||||
f"Number( {num} ) can't be floating point or negative ")
|
||||
return 1 if num == 0 else num * factorial(num - 1)
|
||||
```
|
||||
``` python
|
||||
factorial(6) # 720
|
||||
```
|
||||
|
||||
@ -1,38 +1,38 @@
|
||||
### gcd
|
||||
|
||||
:information_source: `math.gcd` works with only two numbers
|
||||
|
||||
Calculates the greatest common divisor between two or more numbers/lists.
|
||||
|
||||
The `helperGcdfunction` uses recursion. Base case is when `y` equals `0`. In this case, return `x`. Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
|
||||
|
||||
Uses the reduce function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists.
|
||||
|
||||
```python
|
||||
from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def gcd(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
return reduce((lambda x, y: _gcd(x, y)), numbers)
|
||||
```
|
||||
|
||||
|
||||
``` python
|
||||
gcd(8,36) # 4
|
||||
### gcd
|
||||
|
||||
:information_source: `math.gcd` works with only two numbers
|
||||
|
||||
Calculates the greatest common divisor between two or more numbers/lists.
|
||||
|
||||
The `helperGcdfunction` uses recursion. Base case is when `y` equals `0`. In this case, return `x`. Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
|
||||
|
||||
Uses the reduce function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists.
|
||||
|
||||
```python
|
||||
from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def gcd(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
return reduce((lambda x, y: _gcd(x, y)), numbers)
|
||||
```
|
||||
|
||||
|
||||
``` python
|
||||
gcd(8,36) # 4
|
||||
```
|
||||
@ -1,16 +1,16 @@
|
||||
### is_lower_case
|
||||
|
||||
Checks if a string is lower case.
|
||||
|
||||
Convert the given string to lower case, using `str.lower()` method and compare it to the original.
|
||||
|
||||
```python
|
||||
def is_lower_case(str):
|
||||
return str == str.lower()
|
||||
```
|
||||
|
||||
```python
|
||||
is_lower_case('abc') # True
|
||||
is_lower_case('a3@$') # True
|
||||
is_lower_case('Ab4') # False
|
||||
### is_lower_case
|
||||
|
||||
Checks if a string is lower case.
|
||||
|
||||
Convert the given string to lower case, using `str.lower()` method and compare it to the original.
|
||||
|
||||
```python
|
||||
def is_lower_case(str):
|
||||
return str == str.lower()
|
||||
```
|
||||
|
||||
```python
|
||||
is_lower_case('abc') # True
|
||||
is_lower_case('a3@$') # True
|
||||
is_lower_case('Ab4') # False
|
||||
```
|
||||
@ -1,16 +1,16 @@
|
||||
### is_upper_case
|
||||
|
||||
Checks if a string is upper case.
|
||||
|
||||
Convert the given string to upper case, using `str.upper()` method and compare it to the original.
|
||||
|
||||
```python
|
||||
def is_upper_case(str):
|
||||
return str == str.upper()
|
||||
```
|
||||
|
||||
```python
|
||||
is_upper_case('ABC') # True
|
||||
is_upper_case('a3@$') # True
|
||||
is_upper_case('aB4') # False
|
||||
### is_upper_case
|
||||
|
||||
Checks if a string is upper case.
|
||||
|
||||
Convert the given string to upper case, using `str.upper()` method and compare it to the original.
|
||||
|
||||
```python
|
||||
def is_upper_case(str):
|
||||
return str == str.upper()
|
||||
```
|
||||
|
||||
```python
|
||||
is_upper_case('ABC') # True
|
||||
is_upper_case('a3@$') # True
|
||||
is_upper_case('aB4') # False
|
||||
```
|
||||
@ -1,40 +1,40 @@
|
||||
### lcm
|
||||
|
||||
Returns the least common multiple of two or more numbers.
|
||||
|
||||
Use the `greatest common divisor (GCD)` formula and the fact that `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple. The GCD formula uses recursion.
|
||||
|
||||
Uses `reduce` function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists.
|
||||
|
||||
```python
|
||||
from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def lcm(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
def _lcm(x, y):
|
||||
return x * y / _gcd(x, y)
|
||||
|
||||
return reduce((lambda x, y: _lcm(x, y)), numbers)
|
||||
```
|
||||
|
||||
|
||||
``` python
|
||||
lcm(12, 7) # 84
|
||||
lcm([1, 3, 4], 5) # 60
|
||||
### lcm
|
||||
|
||||
Returns the least common multiple of two or more numbers.
|
||||
|
||||
Use the `greatest common divisor (GCD)` formula and the fact that `lcm(x,y) = x * y / gcd(x,y)` to determine the least common multiple. The GCD formula uses recursion.
|
||||
|
||||
Uses `reduce` function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists.
|
||||
|
||||
```python
|
||||
from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def lcm(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
def _lcm(x, y):
|
||||
return x * y / _gcd(x, y)
|
||||
|
||||
return reduce((lambda x, y: _lcm(x, y)), numbers)
|
||||
```
|
||||
|
||||
|
||||
``` python
|
||||
lcm(12, 7) # 84
|
||||
lcm([1, 3, 4], 5) # 60
|
||||
```
|
||||
@ -1,21 +1,21 @@
|
||||
### max_n
|
||||
|
||||
Returns the `n` maximum elements from the provided list. If `n` is greater than or equal to the provided list's length, then return the original list(sorted in descending order).
|
||||
|
||||
Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order and then use `list.reverse()` reverse it to make it descending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element array
|
||||
|
||||
```python
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
def max_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
numbers.reverse()
|
||||
return numbers[:n]
|
||||
```
|
||||
|
||||
```python
|
||||
max_n([1, 2, 3]) # [3]
|
||||
max_n([1, 2, 3], 2) # [3,2]
|
||||
### max_n
|
||||
|
||||
Returns the `n` maximum elements from the provided list. If `n` is greater than or equal to the provided list's length, then return the original list(sorted in descending order).
|
||||
|
||||
Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order and then use `list.reverse()` reverse it to make it descending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element array
|
||||
|
||||
```python
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
def max_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
numbers.reverse()
|
||||
return numbers[:n]
|
||||
```
|
||||
|
||||
```python
|
||||
max_n([1, 2, 3]) # [3]
|
||||
max_n([1, 2, 3], 2) # [3,2]
|
||||
```
|
||||
@ -1,20 +1,20 @@
|
||||
### min_n
|
||||
|
||||
Returns the `n` minimum elements from the provided list. If `n` is greater than or equal to the provided list's length, then return the original list(sorted in ascending order).
|
||||
|
||||
Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element array
|
||||
|
||||
```python
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
def min_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
return numbers[:n]
|
||||
```
|
||||
|
||||
```python
|
||||
min_n([1, 2, 3]) # [1]
|
||||
min_n([1, 2, 3], 2) # [1,2]
|
||||
### min_n
|
||||
|
||||
Returns the `n` minimum elements from the provided list. If `n` is greater than or equal to the provided list's length, then return the original list(sorted in ascending order).
|
||||
|
||||
Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element array
|
||||
|
||||
```python
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
def min_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
return numbers[:n]
|
||||
```
|
||||
|
||||
```python
|
||||
min_n([1, 2, 3]) # [1]
|
||||
min_n([1, 2, 3], 2) # [1,2]
|
||||
```
|
||||
@ -1,15 +1,15 @@
|
||||
### palindrome
|
||||
|
||||
Returns `True` if the given string is a palindrome, `False` otherwise.
|
||||
|
||||
Convert string `str.lower()` and use `re.sub` to remove non-alphanumeric characters from it. Then compare the new string to the reversed.
|
||||
|
||||
```python
|
||||
def palindrome(string):
|
||||
from re import sub
|
||||
s = sub('[\W_]', '', string.lower())
|
||||
return s == s[::-1]
|
||||
```
|
||||
```python
|
||||
palindrome('taco cat') # True
|
||||
### palindrome
|
||||
|
||||
Returns `True` if the given string is a palindrome, `False` otherwise.
|
||||
|
||||
Convert string `str.lower()` and use `re.sub` to remove non-alphanumeric characters from it. Then compare the new string to the reversed.
|
||||
|
||||
```python
|
||||
def palindrome(string):
|
||||
from re import sub
|
||||
s = sub('[\W_]', '', string.lower())
|
||||
return s == s[::-1]
|
||||
```
|
||||
```python
|
||||
palindrome('taco cat') # True
|
||||
```
|
||||
@ -1,27 +1,27 @@
|
||||
### shuffle
|
||||
|
||||
:information_source: The same algorithm is already implemented via `random.shuffle`.
|
||||
|
||||
Randomizes the order of the values of an list, returning a new list.
|
||||
|
||||
Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list.
|
||||
|
||||
```python
|
||||
from copy import deepcopy
|
||||
from random import randint
|
||||
|
||||
|
||||
def shuffle(arr):
|
||||
temp_arr = deepcopy(arr)
|
||||
m = len(temp_arr)
|
||||
while (m):
|
||||
m -= 1
|
||||
i = randint(0, m)
|
||||
temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m]
|
||||
return temp_arr
|
||||
```
|
||||
|
||||
``` python
|
||||
foo = [1,2,3]
|
||||
shuffle(foo) # [2,3,1] , foo = [1,2,3]
|
||||
### shuffle
|
||||
|
||||
:information_source: The same algorithm is already implemented via `random.shuffle`.
|
||||
|
||||
Randomizes the order of the values of an list, returning a new list.
|
||||
|
||||
Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list.
|
||||
|
||||
```python
|
||||
from copy import deepcopy
|
||||
from random import randint
|
||||
|
||||
|
||||
def shuffle(arr):
|
||||
temp_arr = deepcopy(arr)
|
||||
m = len(temp_arr)
|
||||
while (m):
|
||||
m -= 1
|
||||
i = randint(0, m)
|
||||
temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m]
|
||||
return temp_arr
|
||||
```
|
||||
|
||||
``` python
|
||||
foo = [1,2,3]
|
||||
shuffle(foo) # [2,3,1] , foo = [1,2,3]
|
||||
```
|
||||
@ -1,19 +1,19 @@
|
||||
### spread
|
||||
|
||||
Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list.
|
||||
|
||||
```python
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
|
||||
### spread
|
||||
|
||||
Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list.
|
||||
|
||||
```python
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
|
||||
```
|
||||
@ -1,24 +1,24 @@
|
||||
### zip
|
||||
|
||||
:information_source: Already implemented via `itertools.zip_longest()`
|
||||
|
||||
Creates a list of elements, grouped based on the position in the original lists.
|
||||
|
||||
Use `max` combined with `list comprehension` to get the length of the longest list in the arguments. Loops for `max_length` times grouping elements. If lengths of `lists` vary `fill_value` is used. By default `fill_value` is `None`.
|
||||
|
||||
```python
|
||||
def zip(*args, fillvalue=None):
|
||||
max_length = max([len(arr) for arr in args])
|
||||
result = []
|
||||
for i in range(max_length):
|
||||
result.append([
|
||||
args[k][i] if i < len(args[k]) else None for k in range(len(args))
|
||||
])
|
||||
return result
|
||||
```
|
||||
|
||||
``` python
|
||||
zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]
|
||||
zip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]
|
||||
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]
|
||||
### zip
|
||||
|
||||
:information_source: Already implemented via `itertools.zip_longest()`
|
||||
|
||||
Creates a list of elements, grouped based on the position in the original lists.
|
||||
|
||||
Use `max` combined with `list comprehension` to get the length of the longest list in the arguments. Loops for `max_length` times grouping elements. If lengths of `lists` vary `fill_value` is used. By default `fill_value` is `None`.
|
||||
|
||||
```python
|
||||
def zip(*args, fillvalue=None):
|
||||
max_length = max([len(arr) for arr in args])
|
||||
result = []
|
||||
for i in range(max_length):
|
||||
result.append([
|
||||
args[k][i] if i < len(args[k]) else None for k in range(len(args))
|
||||
])
|
||||
return result
|
||||
```
|
||||
|
||||
``` python
|
||||
zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]
|
||||
zip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]
|
||||
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]
|
||||
```
|
||||
@ -1,8 +1,8 @@
|
||||
## Credits
|
||||
|
||||
*Icons made by [Smashicons](https://www.flaticon.com/authors/smashicons) from [www.flaticon.com](https://www.flaticon.com/) is licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).*
|
||||
|
||||
|
||||
|
||||
## License
|
||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code?ref=badge_large)
|
||||
## Credits
|
||||
|
||||
*Icons made by [Smashicons](https://www.flaticon.com/authors/smashicons) from [www.flaticon.com](https://www.flaticon.com/) is licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).*
|
||||
|
||||
|
||||
|
||||
## License
|
||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code?ref=badge_large)
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||

|
||||
|
||||
# 30-seconds-of-python-code
|
||||
[](https://github.com/kriadmin/30-seconds-of-python-code/blob/master/LICENSE) [](https://gitter.im/30-seconds-of-python-code/Lobby) [](http://makeapullrequest.com) [](https://travis-ci.org/kriadmin/30-seconds-of-python-code) [](https://insight.io/github.com/kriadmin/30-seconds-of-python-code/tree/master/?source=0) [](https://github.com/Flet/semistandard)
|
||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code?ref=badge_shield)
|
||||
|
||||
>Python implementation of 30-seconds-of-code.
|
||||
|
||||
**Note**:- This is in no way affiliated with the original [30-seconds-of-code](https://github.com/Chalarangelo/30-seconds-of-code/).
|
||||

|
||||
|
||||
# 30-seconds-of-python-code
|
||||
[](https://github.com/kriadmin/30-seconds-of-python-code/blob/master/LICENSE) [](https://gitter.im/30-seconds-of-python-code/Lobby) [](http://makeapullrequest.com) [](https://travis-ci.org/kriadmin/30-seconds-of-python-code) [](https://insight.io/github.com/kriadmin/30-seconds-of-python-code/tree/master/?source=0) [](https://github.com/Flet/semistandard)
|
||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fkriadmin%2F30-seconds-of-python-code?ref=badge_shield)
|
||||
|
||||
>Python implementation of 30-seconds-of-code.
|
||||
|
||||
**Note**:- This is in no way affiliated with the original [30-seconds-of-code](https://github.com/Chalarangelo/30-seconds-of-code/).
|
||||
|
||||
46
tag_database
46
tag_database
@ -1,24 +1,24 @@
|
||||
average:math
|
||||
chunk:list
|
||||
compact:list
|
||||
count_occurences:list
|
||||
count_vowels:string
|
||||
deep_flatten:list
|
||||
difference:list
|
||||
factorial:math
|
||||
gcd:math
|
||||
lcm:math
|
||||
max_n:math
|
||||
min_n:math
|
||||
shuffle:list
|
||||
spread:list
|
||||
zip:list
|
||||
byte_size:string
|
||||
capitalize:string
|
||||
capitalize_every_word:string
|
||||
decapitalize:string
|
||||
palindrome:string
|
||||
is_upper_case:string
|
||||
is_lower_case:string
|
||||
count_by:list
|
||||
average:math
|
||||
chunk:list
|
||||
compact:list
|
||||
count_occurences:list
|
||||
count_vowels:string
|
||||
deep_flatten:list
|
||||
difference:list
|
||||
factorial:math
|
||||
gcd:math
|
||||
lcm:math
|
||||
max_n:math
|
||||
min_n:math
|
||||
shuffle:list
|
||||
spread:list
|
||||
zip:list
|
||||
byte_size:string
|
||||
capitalize:string
|
||||
capitalize_every_word:string
|
||||
decapitalize:string
|
||||
palindrome:string
|
||||
is_upper_case:string
|
||||
is_lower_case:string
|
||||
count_by:list
|
||||
difference_by:list
|
||||
@ -1,2 +1,2 @@
|
||||
def average(*args):
|
||||
def average(*args):
|
||||
return sum(args, 0.0) / len(args)
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from average import average
|
||||
def average_test(t):
|
||||
t.true(isinstance(average, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'average is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from average import average
|
||||
def average_test(t):
|
||||
t.true(isinstance(average, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'average is a function')
|
||||
test('Testing average',average_test)
|
||||
@ -1,2 +1,2 @@
|
||||
def byte_size(string):
|
||||
def byte_size(string):
|
||||
return(len(string.encode('utf-8')))
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from byte_size import byte_size
|
||||
def byte_size_test(t):
|
||||
t.true(isinstance(byte_size, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'byte_size is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from byte_size import byte_size
|
||||
def byte_size_test(t):
|
||||
t.true(isinstance(byte_size, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'byte_size is a function')
|
||||
test('Testing byte_size',byte_size_test)
|
||||
@ -1,2 +1,2 @@
|
||||
def capitalize(string, lower_rest=False):
|
||||
def capitalize(string, lower_rest=False):
|
||||
return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from capitalize import capitalize
|
||||
def capitalize_test(t):
|
||||
t.true(isinstance(capitalize, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'capitalize is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from capitalize import capitalize
|
||||
def capitalize_test(t):
|
||||
t.true(isinstance(capitalize, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'capitalize is a function')
|
||||
test('Testing capitalize',capitalize_test)
|
||||
@ -1,2 +1,2 @@
|
||||
def capitalize_every_word(string):
|
||||
def capitalize_every_word(string):
|
||||
return string.title()
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from capitalize_every_word import capitalize_every_word
|
||||
def capitalize_every_word_test(t):
|
||||
t.true(isinstance(capitalize_every_word, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'capitalize_every_word is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from capitalize_every_word import capitalize_every_word
|
||||
def capitalize_every_word_test(t):
|
||||
t.true(isinstance(capitalize_every_word, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'capitalize_every_word is a function')
|
||||
test('Testing capitalize_every_word',capitalize_every_word_test)
|
||||
@ -1,7 +1,7 @@
|
||||
from math import ceil
|
||||
|
||||
|
||||
def chunk(arr, size):
|
||||
return list(
|
||||
map(lambda x: arr[x * size:x * size + size],
|
||||
from math import ceil
|
||||
|
||||
|
||||
def chunk(arr, size):
|
||||
return list(
|
||||
map(lambda x: arr[x * size:x * size + size],
|
||||
list(range(0, ceil(len(arr) / size)))))
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from chunk import chunk
|
||||
def chunk_test(t):
|
||||
t.true(isinstance(chunk, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'chunk is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from chunk import chunk
|
||||
def chunk_test(t):
|
||||
t.true(isinstance(chunk, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'chunk is a function')
|
||||
test('Testing chunk',chunk_test)
|
||||
@ -1,2 +1,2 @@
|
||||
def compact(arr):
|
||||
def compact(arr):
|
||||
return list(filter(lambda x: bool(x), arr))
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from compact import compact
|
||||
def compact_test(t):
|
||||
t.true(isinstance(compact, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'compact is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from compact import compact
|
||||
def compact_test(t):
|
||||
t.true(isinstance(compact, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'compact is a function')
|
||||
test('Testing compact',compact_test)
|
||||
@ -1,6 +1,6 @@
|
||||
def count_by(arr, fn=lambda x: x):
|
||||
key = {}
|
||||
for el in map(fn, arr):
|
||||
key[el] = 0 if not el in key else key[el]
|
||||
key[el] += 1
|
||||
def count_by(arr, fn=lambda x: x):
|
||||
key = {}
|
||||
for el in map(fn, arr):
|
||||
key[el] = 0 if not el in key else key[el]
|
||||
key[el] += 1
|
||||
return key
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from count_by import count_by
|
||||
def count_by_test(t):
|
||||
t.true(isinstance(count_by, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'count_by is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from count_by import count_by
|
||||
def count_by_test(t):
|
||||
t.true(isinstance(count_by, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'count_by is a function')
|
||||
test('Testing count_by',count_by_test)
|
||||
@ -1,4 +1,4 @@
|
||||
def count_occurences(arr, val):
|
||||
return reduce(
|
||||
(lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
|
||||
def count_occurences(arr, val):
|
||||
return reduce(
|
||||
(lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
|
||||
arr)
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from count_occurences import count_occurences
|
||||
def count_occurences_test(t):
|
||||
t.true(isinstance(count_occurences, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'count_occurences is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from count_occurences import count_occurences
|
||||
def count_occurences_test(t):
|
||||
t.true(isinstance(count_occurences, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'count_occurences is a function')
|
||||
test('Testing count_occurences',count_occurences_test)
|
||||
@ -1,5 +1,5 @@
|
||||
import re
|
||||
|
||||
|
||||
def count_vowels(str):
|
||||
import re
|
||||
|
||||
|
||||
def count_vowels(str):
|
||||
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from count_vowels import count_vowels
|
||||
def count_vowels_test(t):
|
||||
t.true(isinstance(count_vowels, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'count_vowels is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from count_vowels import count_vowels
|
||||
def count_vowels_test(t):
|
||||
t.true(isinstance(count_vowels, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'count_vowels is a function')
|
||||
test('Testing count_vowels',count_vowels_test)
|
||||
@ -1,2 +1,2 @@
|
||||
def decapitalize(string, upper_rest=False):
|
||||
def decapitalize(string, upper_rest=False):
|
||||
return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from decapitalize import decapitalize
|
||||
def decapitalize_test(t):
|
||||
t.true(isinstance(decapitalize, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'decapitalize is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from decapitalize import decapitalize
|
||||
def decapitalize_test(t):
|
||||
t.true(isinstance(decapitalize, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'decapitalize is a function')
|
||||
test('Testing decapitalize',decapitalize_test)
|
||||
@ -1,15 +1,15 @@
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def deep_flatten(arr):
|
||||
result = []
|
||||
result.extend(
|
||||
spread(list(map(lambda x: deep(x) if type(x) == list else x, arr))))
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def deep_flatten(arr):
|
||||
result = []
|
||||
result.extend(
|
||||
spread(list(map(lambda x: deep(x) if type(x) == list else x, arr))))
|
||||
return result
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from deep_flatten import deep_flatten
|
||||
def deep_flatten_test(t):
|
||||
t.true(isinstance(deep_flatten, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'deep_flatten is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from deep_flatten import deep_flatten
|
||||
def deep_flatten_test(t):
|
||||
t.true(isinstance(deep_flatten, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'deep_flatten is a function')
|
||||
test('Testing deep_flatten',deep_flatten_test)
|
||||
@ -1,3 +1,3 @@
|
||||
def difference(a, b):
|
||||
b = set(b)
|
||||
def difference(a, b):
|
||||
b = set(b)
|
||||
return [item for item in a if item not in b]
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from difference import difference
|
||||
def difference_test(t):
|
||||
t.true(isinstance(difference, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'difference is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from difference import difference
|
||||
def difference_test(t):
|
||||
t.true(isinstance(difference, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'difference is a function')
|
||||
test('Testing difference',difference_test)
|
||||
@ -1,3 +1,3 @@
|
||||
def difference_by(a, b, fn):
|
||||
b = set(map(fn, b))
|
||||
def difference_by(a, b, fn):
|
||||
b = set(map(fn, b))
|
||||
return [item for item in a if fn(item) not in b]
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from difference_by import difference_by
|
||||
def difference_by_test(t):
|
||||
t.true(isinstance(difference_by, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'difference_by is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from difference_by import difference_by
|
||||
def difference_by_test(t):
|
||||
t.true(isinstance(difference_by, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'difference_by is a function')
|
||||
test('Testing difference_by',difference_by_test)
|
||||
@ -1,5 +1,5 @@
|
||||
def factorial(num):
|
||||
if not ((num >= 0) & (num % 1 == 0)):
|
||||
raise Exception(
|
||||
f"Number( {num} ) can't be floating point or negative ")
|
||||
def factorial(num):
|
||||
if not ((num >= 0) & (num % 1 == 0)):
|
||||
raise Exception(
|
||||
f"Number( {num} ) can't be floating point or negative ")
|
||||
return 1 if num == 0 else num * factorial(num - 1)
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from factorial import factorial
|
||||
def factorial_test(t):
|
||||
t.true(isinstance(factorial, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'factorial is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from factorial import factorial
|
||||
def factorial_test(t):
|
||||
t.true(isinstance(factorial, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'factorial is a function')
|
||||
test('Testing factorial',factorial_test)
|
||||
@ -1,21 +1,21 @@
|
||||
from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def gcd(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def gcd(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
return reduce((lambda x, y: _gcd(x, y)), numbers)
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from gcd import gcd
|
||||
def gcd_test(t):
|
||||
t.true(isinstance(gcd, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'gcd is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from gcd import gcd
|
||||
def gcd_test(t):
|
||||
t.true(isinstance(gcd, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'gcd is a function')
|
||||
test('Testing gcd',gcd_test)
|
||||
@ -1,2 +1,2 @@
|
||||
def is_lower_case(str):
|
||||
def is_lower_case(str):
|
||||
return str == str.lower()
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from is_lower_case import is_lower_case
|
||||
def is_lower_case_test(t):
|
||||
t.true(isinstance(is_lower_case, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'is_lower_case is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from is_lower_case import is_lower_case
|
||||
def is_lower_case_test(t):
|
||||
t.true(isinstance(is_lower_case, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'is_lower_case is a function')
|
||||
test('Testing is_lower_case',is_lower_case_test)
|
||||
@ -1,2 +1,2 @@
|
||||
def is_upper_case(str):
|
||||
def is_upper_case(str):
|
||||
return str == str.upper()
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from is_upper_case import is_upper_case
|
||||
def is_upper_case_test(t):
|
||||
t.true(isinstance(is_upper_case, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'is_upper_case is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from is_upper_case import is_upper_case
|
||||
def is_upper_case_test(t):
|
||||
t.true(isinstance(is_upper_case, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'is_upper_case is a function')
|
||||
test('Testing is_upper_case',is_upper_case_test)
|
||||
@ -1,24 +1,24 @@
|
||||
from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def lcm(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
def _lcm(x, y):
|
||||
return x * y / _gcd(x, y)
|
||||
|
||||
from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def lcm(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
def _lcm(x, y):
|
||||
return x * y / _gcd(x, y)
|
||||
|
||||
return reduce((lambda x, y: _lcm(x, y)), numbers)
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from lcm import lcm
|
||||
def lcm_test(t):
|
||||
t.true(isinstance(lcm, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'lcm is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from lcm import lcm
|
||||
def lcm_test(t):
|
||||
t.true(isinstance(lcm, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'lcm is a function')
|
||||
test('Testing lcm',lcm_test)
|
||||
@ -1,8 +1,8 @@
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
def max_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
numbers.reverse()
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
def max_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
numbers.reverse()
|
||||
return numbers[:n]
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from max_n import max_n
|
||||
def max_n_test(t):
|
||||
t.true(isinstance(max_n, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'max_n is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from max_n import max_n
|
||||
def max_n_test(t):
|
||||
t.true(isinstance(max_n, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'max_n is a function')
|
||||
test('Testing max_n',max_n_test)
|
||||
@ -1,7 +1,7 @@
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
def min_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
def min_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
return numbers[:n]
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from min_n import min_n
|
||||
def min_n_test(t):
|
||||
t.true(isinstance(min_n, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'min_n is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from min_n import min_n
|
||||
def min_n_test(t):
|
||||
t.true(isinstance(min_n, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'min_n is a function')
|
||||
test('Testing min_n',min_n_test)
|
||||
@ -1,4 +1,4 @@
|
||||
def palindrome(string):
|
||||
from re import sub
|
||||
s = sub('[\W_]', '', string.lower())
|
||||
def palindrome(string):
|
||||
from re import sub
|
||||
s = sub('[\W_]', '', string.lower())
|
||||
return s == s[::-1]
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from palindrome import palindrome
|
||||
def palindrome_test(t):
|
||||
t.true(isinstance(palindrome, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'palindrome is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from palindrome import palindrome
|
||||
def palindrome_test(t):
|
||||
t.true(isinstance(palindrome, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'palindrome is a function')
|
||||
test('Testing palindrome',palindrome_test)
|
||||
@ -1,12 +1,12 @@
|
||||
from copy import deepcopy
|
||||
from random import randint
|
||||
|
||||
|
||||
def shuffle(arr):
|
||||
temp_arr = deepcopy(arr)
|
||||
m = len(temp_arr)
|
||||
while (m):
|
||||
m -= 1
|
||||
i = randint(0, m)
|
||||
temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m]
|
||||
from copy import deepcopy
|
||||
from random import randint
|
||||
|
||||
|
||||
def shuffle(arr):
|
||||
temp_arr = deepcopy(arr)
|
||||
m = len(temp_arr)
|
||||
while (m):
|
||||
m -= 1
|
||||
i = randint(0, m)
|
||||
temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m]
|
||||
return temp_arr
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from shuffle import shuffle
|
||||
def shuffle_test(t):
|
||||
t.true(isinstance(shuffle, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'shuffle is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from shuffle import shuffle
|
||||
def shuffle_test(t):
|
||||
t.true(isinstance(shuffle, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'shuffle is a function')
|
||||
test('Testing shuffle',shuffle_test)
|
||||
@ -1,8 +1,8 @@
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from spread import spread
|
||||
def spread_test(t):
|
||||
t.true(isinstance(spread, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'spread is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from spread import spread
|
||||
def spread_test(t):
|
||||
t.true(isinstance(spread, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'spread is a function')
|
||||
test('Testing spread',spread_test)
|
||||
@ -1,8 +1,8 @@
|
||||
def zip(*args, fillvalue=None):
|
||||
max_length = max([len(arr) for arr in args])
|
||||
result = []
|
||||
for i in range(max_length):
|
||||
result.append([
|
||||
args[k][i] if i < len(args[k]) else None for k in range(len(args))
|
||||
])
|
||||
def zip(*args, fillvalue=None):
|
||||
max_length = max([len(arr) for arr in args])
|
||||
result = []
|
||||
for i in range(max_length):
|
||||
result.append([
|
||||
args[k][i] if i < len(args[k]) else None for k in range(len(args))
|
||||
])
|
||||
return result
|
||||
@ -1,6 +1,6 @@
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from zip import zip
|
||||
def zip_test(t):
|
||||
t.true(isinstance(zip, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'zip is a function')
|
||||
import types,functools
|
||||
from pytape import test
|
||||
from zip import zip
|
||||
def zip_test(t):
|
||||
t.true(isinstance(zip, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'zip is a function')
|
||||
test('Testing zip',zip_test)
|
||||
@ -1,8 +1,8 @@
|
||||
from flask import Flask
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
|
||||
app.secret_key = 'thedarklordisgreat'
|
||||
|
||||
from flask import Flask
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
|
||||
app.secret_key = 'thedarklordisgreat'
|
||||
|
||||
from app import routes,vote
|
||||
@ -1,2 +1,2 @@
|
||||
127.0.0.1 localwebsite
|
||||
127.0.0.1 localwebsite
|
||||
127.0.0.1 blog.localwebsite
|
||||
@ -1,23 +1,23 @@
|
||||
from flask import render_template, redirect ,request, url_for
|
||||
from app import app, vote, vote_data
|
||||
|
||||
@app.route('/')
|
||||
@app.route('/index')
|
||||
@app.route('/index/')
|
||||
def index():
|
||||
return render_template('index.html',vote={})
|
||||
'''
|
||||
For future when we have logins
|
||||
@app.route('/',methods=['POST'])
|
||||
@app.route('/index',methods=['POST'])
|
||||
@app.route('/index/',methods=['POST'])
|
||||
def post():
|
||||
try:
|
||||
vote.vote(request.form['submit'])
|
||||
except Exception as e:
|
||||
return render_template('index.html', vote=vote_data.vote_data(),err_400=True,message=e)
|
||||
return redirect(f"/#{request.form['submit']}",code=302)
|
||||
'''
|
||||
|
||||
|
||||
|
||||
from flask import render_template, redirect ,request, url_for
|
||||
from app import app, vote, vote_data
|
||||
|
||||
@app.route('/')
|
||||
@app.route('/index')
|
||||
@app.route('/index/')
|
||||
def index():
|
||||
return render_template('index.html',vote={})
|
||||
'''
|
||||
For future when we have logins
|
||||
@app.route('/',methods=['POST'])
|
||||
@app.route('/index',methods=['POST'])
|
||||
@app.route('/index/',methods=['POST'])
|
||||
def post():
|
||||
try:
|
||||
vote.vote(request.form['submit'])
|
||||
except Exception as e:
|
||||
return render_template('index.html', vote=vote_data.vote_data(),err_400=True,message=e)
|
||||
return redirect(f"/#{request.form['submit']}",code=302)
|
||||
'''
|
||||
|
||||
|
||||
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
count_vowels
|
||||
byte_size
|
||||
capitalize
|
||||
capitalize_every_word
|
||||
decapitalize
|
||||
palindrome
|
||||
is_upper_case
|
||||
count_vowels
|
||||
byte_size
|
||||
capitalize
|
||||
capitalize_every_word
|
||||
decapitalize
|
||||
palindrome
|
||||
is_upper_case
|
||||
is_lower_case
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,74 +1,74 @@
|
||||
<html>
|
||||
<head>
|
||||
<link href="/static/css/prism.css" rel = "stylesheet"></link>
|
||||
<script src="/static/js/prism.js"></script>
|
||||
<meta charset="utf-8"><meta name="description" content=" Python implementation of 30-seconds-of-code "><meta name="keywords" content="python, javascript, snippets, code, programming"><meta name="author" content="Rohit Kumar Tanwar (mst10041967@gmail.com)"><meta name="viewport" content="width=device-width,initial-scale=1"><meta property="og:title" content="30 seconds of python code"><meta property="og:description" content="Python implementation of 30 seconds of code"><meta property="og:type" content="website"><meta property="og:image" content="static/favicon.png"><link rel="icon" type="image/ico" href="static/favicon.png">
|
||||
<title>30 seconds of python code</title>
|
||||
</head>
|
||||
<body onload="loader()">
|
||||
<a href="https://github.com/kriadmin/30-seconds-of-python-code" class="github-corner" aria-label="View source on Github"><svg width="90" height="90" viewBox="0 0 250 250" style="fill:#151513;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>
|
||||
{% if err_400 %}
|
||||
<div class="error">{{ message }}</div>
|
||||
{% endif %}
|
||||
<header style="height:5.5rem"><h1 class="logo"><img src="static/favicon.png" style="height:4rem" alt="logo"><span id="title"> 30 seconds of python code</span> <small>Python Implementation of 30 seconds of code</small></h1><label for="doc-drawer-checkbox" class="button drawer-toggle" id="menu-toggle"></label></header>
|
||||
{% block content %}{% endblock %}
|
||||
<script>
|
||||
const search = (node) => {
|
||||
let matchingTags = [];
|
||||
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => {
|
||||
let data = [x.innerText.toLowerCase(), ...x.getAttribute('tags').split(',')].map(v => !!(v.indexOf(node.value.toLowerCase()) + 1));
|
||||
if(data.includes(true)){
|
||||
x.style.display = '';
|
||||
matchingTags.push(x.getAttribute('tags').split(',')[0]);
|
||||
}
|
||||
else x.style.display = 'none';
|
||||
});
|
||||
Array.from(node.parentElement.parentElement.getElementsByTagName('h3')).forEach(x => {
|
||||
x.style.display = matchingTags.includes(x.innerText.toLowerCase()) ? '' : 'none';
|
||||
})
|
||||
}
|
||||
function scrollToTop(){
|
||||
const c = document.querySelector('main').scrollTop;
|
||||
if (c > 0) {
|
||||
window.requestAnimationFrame(scrollToTop);
|
||||
document.querySelector('main').scrollTo(0, c - c / 4);
|
||||
}
|
||||
};
|
||||
function loader() {
|
||||
registerClickListener();
|
||||
}
|
||||
function registerClickListener() {
|
||||
document.addEventListener('click', function (event) {
|
||||
if ( event.target.classList.contains('collapse') ) {
|
||||
event.target.classList = event.target.classList.contains('toggled') ? 'collapse' : 'collapse toggled';
|
||||
}
|
||||
else if (event.target.classList.contains('clipboard-copy')) {
|
||||
const text = event.target.parentElement.parentElement.querySelector(':not(pre) + pre').textContent;
|
||||
const textArea = document.createElement("textarea");
|
||||
textArea.value = text.trim();
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
document.execCommand("Copy");
|
||||
document.body.removeChild(textArea);
|
||||
let tst = document.createElement('div');
|
||||
tst.classList = 'toast';
|
||||
tst.innerHTML = 'Snippet copied to clipboard!';
|
||||
document.body.appendChild(tst);
|
||||
setTimeout(function() {
|
||||
tst.style.opacity = 0;
|
||||
setTimeout(function() {
|
||||
document.body.removeChild(tst);
|
||||
},300);
|
||||
},1700);
|
||||
}
|
||||
else if (event.target.classList.contains('scroll-to-top')){
|
||||
scrollToTop();
|
||||
}
|
||||
}, false);
|
||||
}
|
||||
</script>
|
||||
<script>
|
||||
[...document.getElementsByClassName("language-python")].forEach(el => Prism.highlightElement(el))
|
||||
</script>
|
||||
</body>
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<link href="/static/css/prism.css" rel = "stylesheet"></link>
|
||||
<script src="/static/js/prism.js"></script>
|
||||
<meta charset="utf-8"><meta name="description" content=" Python implementation of 30-seconds-of-code "><meta name="keywords" content="python, javascript, snippets, code, programming"><meta name="author" content="Rohit Kumar Tanwar (mst10041967@gmail.com)"><meta name="viewport" content="width=device-width,initial-scale=1"><meta property="og:title" content="30 seconds of python code"><meta property="og:description" content="Python implementation of 30 seconds of code"><meta property="og:type" content="website"><meta property="og:image" content="static/favicon.png"><link rel="icon" type="image/ico" href="static/favicon.png">
|
||||
<title>30 seconds of python code</title>
|
||||
</head>
|
||||
<body onload="loader()">
|
||||
<a href="https://github.com/kriadmin/30-seconds-of-python-code" class="github-corner" aria-label="View source on Github"><svg width="90" height="90" viewBox="0 0 250 250" style="fill:#151513;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>
|
||||
{% if err_400 %}
|
||||
<div class="error">{{ message }}</div>
|
||||
{% endif %}
|
||||
<header style="height:5.5rem"><h1 class="logo"><img src="static/favicon.png" style="height:4rem" alt="logo"><span id="title"> 30 seconds of python code</span> <small>Python Implementation of 30 seconds of code</small></h1><label for="doc-drawer-checkbox" class="button drawer-toggle" id="menu-toggle"></label></header>
|
||||
{% block content %}{% endblock %}
|
||||
<script>
|
||||
const search = (node) => {
|
||||
let matchingTags = [];
|
||||
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => {
|
||||
let data = [x.innerText.toLowerCase(), ...x.getAttribute('tags').split(',')].map(v => !!(v.indexOf(node.value.toLowerCase()) + 1));
|
||||
if(data.includes(true)){
|
||||
x.style.display = '';
|
||||
matchingTags.push(x.getAttribute('tags').split(',')[0]);
|
||||
}
|
||||
else x.style.display = 'none';
|
||||
});
|
||||
Array.from(node.parentElement.parentElement.getElementsByTagName('h3')).forEach(x => {
|
||||
x.style.display = matchingTags.includes(x.innerText.toLowerCase()) ? '' : 'none';
|
||||
})
|
||||
}
|
||||
function scrollToTop(){
|
||||
const c = document.querySelector('main').scrollTop;
|
||||
if (c > 0) {
|
||||
window.requestAnimationFrame(scrollToTop);
|
||||
document.querySelector('main').scrollTo(0, c - c / 4);
|
||||
}
|
||||
};
|
||||
function loader() {
|
||||
registerClickListener();
|
||||
}
|
||||
function registerClickListener() {
|
||||
document.addEventListener('click', function (event) {
|
||||
if ( event.target.classList.contains('collapse') ) {
|
||||
event.target.classList = event.target.classList.contains('toggled') ? 'collapse' : 'collapse toggled';
|
||||
}
|
||||
else if (event.target.classList.contains('clipboard-copy')) {
|
||||
const text = event.target.parentElement.parentElement.querySelector(':not(pre) + pre').textContent;
|
||||
const textArea = document.createElement("textarea");
|
||||
textArea.value = text.trim();
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
document.execCommand("Copy");
|
||||
document.body.removeChild(textArea);
|
||||
let tst = document.createElement('div');
|
||||
tst.classList = 'toast';
|
||||
tst.innerHTML = 'Snippet copied to clipboard!';
|
||||
document.body.appendChild(tst);
|
||||
setTimeout(function() {
|
||||
tst.style.opacity = 0;
|
||||
setTimeout(function() {
|
||||
document.body.removeChild(tst);
|
||||
},300);
|
||||
},1700);
|
||||
}
|
||||
else if (event.target.classList.contains('scroll-to-top')){
|
||||
scrollToTop();
|
||||
}
|
||||
}, false);
|
||||
}
|
||||
</script>
|
||||
<script>
|
||||
[...document.getElementsByClassName("language-python")].forEach(el => Prism.highlightElement(el))
|
||||
</script>
|
||||
</body>
|
||||
|
||||
|
||||
@ -1,379 +1,379 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block content %}<div class="row" style="height:calc(100vh - 5.875rem);overflow:hidden"><input id="doc-drawer-checkbox" class="drawer" value="on" type="checkbox"><nav class="col-md-4 col-lg-3" style="border-top:0"><div class="group"><input class="search" id="searchInput" onkeyup="search(this)" type="text"><label id="search-label">Search for snippet...</label></div><label for="doc-drawer-checkbox" class="button drawer-close"></label><h3 style = "">Math</h3><a class="sublink-1" tags="math" href="#average" style="">average</a><a class="sublink-1" tags="math" href="#factorial" style="">factorial</a><a class="sublink-1" tags="math" href="#gcd" style="">gcd</a><a class="sublink-1" tags="math" href="#lcm" style="">lcm</a><a class="sublink-1" tags="math" href="#max_n" style="">max_n</a><a class="sublink-1" tags="math" href="#min_n" style="">min_n</a><h3 style = "">List</h3><a class="sublink-1" tags="list" href="#chunk" style="">chunk</a><a class="sublink-1" tags="list" href="#compact" style="">compact</a><a class="sublink-1" tags="list" href="#count_occurences" style="">count_occurences</a><a class="sublink-1" tags="list" href="#deep_flatten" style="">deep_flatten</a><a class="sublink-1" tags="list" href="#difference" style="">difference</a><a class="sublink-1" tags="list" href="#shuffle" style="">shuffle</a><a class="sublink-1" tags="list" href="#spread" style="">spread</a><a class="sublink-1" tags="list" href="#zip" style="">zip</a><a class="sublink-1" tags="list" href="#count_by" style="">count_by</a><a class="sublink-1" tags="list" href="#difference_by" style="">difference_by</a><h3 style = "">String</h3><a class="sublink-1" tags="string" href="#count_vowels" style="">count_vowels</a><a class="sublink-1" tags="string" href="#byte_size" style="">byte_size</a><a class="sublink-1" tags="string" href="#capitalize" style="">capitalize</a><a class="sublink-1" tags="string" href="#capitalize_every_word" style="">capitalize_every_word</a><a class="sublink-1" tags="string" href="#decapitalize" style="">decapitalize</a><a class="sublink-1" tags="string" href="#palindrome" style="">palindrome</a><a class="sublink-1" tags="string" href="#is_upper_case" style="">is_upper_case</a><a class="sublink-1" tags="string" href="#is_lower_case" style="">is_lower_case</a></nav><main class="col-sm-12 col-md-8 col-lg-9" style="height:100%;overflow-y:auto;background:#eceef2;padding:0"><a id="top"></a><h2 style="text-align:center">Math</h2><div class="card fluid"><h3 id="average" class="section double-padded">average</h3><!--<form action="" method="post"><button type="submit" value="average" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> Already implemented via <code>statistics.mean</code>. <code>statistics.mean</code> takes an array as an argument whereas this function takes variadic arguments.</p>
|
||||
<p>Returns the average of two or more numbers.</p>
|
||||
<p>Takes the sum of all the <code>args</code> and divides it by <code>len(args)</code>. The secind argument <code>0.0</code> in sum is to handle floating point division in <code>python2</code>.</p>
|
||||
|
||||
<pre class="language-python">def average(*args):
|
||||
return sum(args, 0.0) / len(args)</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">average(*[1, 2, 3]) # 2.0
|
||||
average(1, 2, 3) # 2.0</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="factorial" class="section double-padded">factorial</h3><!--<form action="" method="post"><button type="submit" value="factorial" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Calculates the factorial of a number.</p>
|
||||
<p>Use recursion. If <code>num</code> is less than or equal to <code>1</code>, return <code>1</code>. Otherwise, return the product of <code>num</code> and the factorial of <code>num - 1</code>. Throws an exception if <code>num</code> is a negative or a floating point number.</p>
|
||||
|
||||
<pre class="language-python">def factorial(num):
|
||||
if not ((num >= 0) & (num % 1 == 0)):
|
||||
raise Exception(
|
||||
f"Number( {num} ) can't be floating point or negative ")
|
||||
return 1 if num == 0 else num * factorial(num - 1)</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">factorial(6) # 720</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="gcd" class="section double-padded">gcd</h3><!--<form action="" method="post"><button type="submit" value="gcd" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> <code>math.gcd</code> works with only two numbers</p>
|
||||
<p>Calculates the greatest common divisor between two or more numbers/lists.</p>
|
||||
<p>The <code>helperGcdfunction</code> uses recursion. Base case is when <code>y</code> equals <code>0</code>. In this case, return <code>x</code>. Otherwise, return the GCD of <code>y</code> and the remainder of the division <code>x/y</code>.</p>
|
||||
<p>Uses the reduce function from the inbuilt module <code>functools</code>. Also defines a method <code>spread</code> for javascript like spreading of lists.</p>
|
||||
|
||||
<pre class="language-python">from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def gcd(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
return reduce((lambda x, y: _gcd(x, y)), numbers)</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">gcd(8,36) # 4</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="lcm" class="section double-padded">lcm</h3><!--<form action="" method="post"><button type="submit" value="lcm" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the least common multiple of two or more numbers.</p>
|
||||
<p>Use the <code>greatest common divisor (GCD)</code> formula and the fact that <code>lcm(x,y) = x * y / gcd(x,y)</code> to determine the least common multiple. The GCD formula uses recursion.</p>
|
||||
<p>Uses <code>reduce</code> function from the inbuilt module <code>functools</code>. Also defines a method <code>spread</code> for javascript like spreading of lists.</p>
|
||||
|
||||
<pre class="language-python">from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def lcm(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
def _lcm(x, y):
|
||||
return x * y / _gcd(x, y)
|
||||
|
||||
return reduce((lambda x, y: _lcm(x, y)), numbers)</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">lcm(12, 7) # 84
|
||||
lcm([1, 3, 4], 5) # 60</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="max_n" class="section double-padded">max_n</h3><!--<form action="" method="post"><button type="submit" value="max_n" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the <code>n</code> maximum elements from the provided list. If <code>n</code> is greater than or equal to the provided list's length, then return the original list(sorted in descending order).</p>
|
||||
<p>Use <code>list.sort()</code> combined with the <code>deepcopy</code> function from the inbuilt <code>copy</code> module to create a shallow clone of the list and sort it in ascending order and then use <code>list.reverse()</code> reverse it to make it descending order. Use <code>[:n]</code> to get the specified number of elements. Omit the second argument, <code>n</code>, to get a one-element array</p>
|
||||
|
||||
<pre class="language-python">from copy import deepcopy
|
||||
|
||||
|
||||
def max_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
numbers.reverse()
|
||||
return numbers[:n]</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">max_n([1, 2, 3]) # [3]
|
||||
max_n([1, 2, 3], 2) # [3,2]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="min_n" class="section double-padded">min_n</h3><!--<form action="" method="post"><button type="submit" value="min_n" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the <code>n</code> minimum elements from the provided list. If <code>n</code> is greater than or equal to the provided list's length, then return the original list(sorted in ascending order).</p>
|
||||
<p>Use <code>list.sort()</code> combined with the <code>deepcopy</code> function from the inbuilt <code>copy</code> module to create a shallow clone of the list and sort it in ascending order. Use <code>[:n]</code> to get the specified number of elements. Omit the second argument, <code>n</code>, to get a one-element array</p>
|
||||
|
||||
<pre class="language-python">from copy import deepcopy
|
||||
|
||||
|
||||
def min_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
return numbers[:n]</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">min_n([1, 2, 3]) # [1]
|
||||
min_n([1, 2, 3], 2) # [1,2]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><h2 style="text-align:center">List</h2><div class="card fluid"><h3 id="chunk" class="section double-padded">chunk</h3><!--<form action="" method="post"><button type="submit" value="chunk" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Chunks an array into smaller lists of a specified size.</p>
|
||||
<p>Uses <code>range</code> to create a list of desired size. Then use <code>map</code> on this list and fill it with splices of <code>arr</code>.</p>
|
||||
|
||||
<pre class="language-python">from math import ceil
|
||||
|
||||
|
||||
def chunk(arr, size):
|
||||
return list(
|
||||
map(lambda x: arr[x * size:x * size + size],
|
||||
list(range(0, ceil(len(arr) / size)))))</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="compact" class="section double-padded">compact</h3><!--<form action="" method="post"><button type="submit" value="compact" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Removes falsey values from a list.</p>
|
||||
<p>Use <code>filter()</code> to filter out falsey values (False, None, 0, and "").</p>
|
||||
|
||||
<pre class="language-python">def compact(arr):
|
||||
return list(filter(lambda x: bool(x), arr))</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="count_occurences" class="section double-padded">count_occurences</h3><!--<form action="" method="post"><button type="submit" value="count_occurences" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> Already implemented via <code>list.count()</code>.</p>
|
||||
<p>Counts the occurrences of a value in an list.</p>
|
||||
<p>Uses the <code>reduce</code> functin from built-in module <code>functools</code> to increment a counter each time you encounter the specific value inside the list.</p>
|
||||
|
||||
<pre class="language-python">def count_occurences(arr, val):
|
||||
return reduce(
|
||||
(lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
|
||||
arr)</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="deep_flatten" class="section double-padded">deep_flatten</h3><!--<form action="" method="post"><button type="submit" value="deep_flatten" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Deep flattens a list.</p>
|
||||
<p>Use recursion. Use <code>list.extend()</code> with an empty array (<code>result</code>) and the spread function to flatten a list. Recursively flatten each element that is a list.</p>
|
||||
|
||||
<pre class="language-python">def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def deep_flatten(arr):
|
||||
result = []
|
||||
result.extend(
|
||||
spread(list(map(lambda x: deep(x) if type(x) == list else x, arr))))
|
||||
return result</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="difference" class="section double-padded">difference</h3><!--<form action="" method="post"><button type="submit" value="difference" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the difference between two arrays.</p>
|
||||
<p>Create a <code>set</code> from <code>b</code>, then use list comprehension to only keep values not contained in <code>b</code></p>
|
||||
|
||||
<pre class="language-python">def difference(a, b):
|
||||
b = set(b)
|
||||
return [item for item in a if item not in b]</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">difference([1, 2, 3], [1, 2, 4]) # [3]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="shuffle" class="section double-padded">shuffle</h3><!--<form action="" method="post"><button type="submit" value="shuffle" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> The same algorithm is already implemented via <code>random.shuffle</code>.</p>
|
||||
<p>Randomizes the order of the values of an list, returning a new list.</p>
|
||||
<p>Uses the <a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle">Fisher-Yates algorithm</a> to reorder the elements of the list.</p>
|
||||
|
||||
<pre class="language-python">from copy import deepcopy
|
||||
from random import randint
|
||||
|
||||
|
||||
def shuffle(arr):
|
||||
temp_arr = deepcopy(arr)
|
||||
m = len(temp_arr)
|
||||
while (m):
|
||||
m -= 1
|
||||
i = randint(0, m)
|
||||
temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m]
|
||||
return temp_arr</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">foo = [1,2,3]
|
||||
shuffle(foo) # [2,3,1] , foo = [1,2,3]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="spread" class="section double-padded">spread</h3><!--<form action="" method="post"><button type="submit" value="spread" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Implements javascript's <code>[].concat(...arr)</code>. Flattens the list(non-deep) and returns an list.</p>
|
||||
|
||||
<pre class="language-python">def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="zip" class="section double-padded">zip</h3><!--<form action="" method="post"><button type="submit" value="zip" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> Already implemented via <code>itertools.zip_longest()</code></p>
|
||||
<p>Creates a list of elements, grouped based on the position in the original lists.</p>
|
||||
<p>Use <code>max</code> combined with <code>list comprehension</code> to get the length of the longest list in the arguments. Loops for <code>max_length</code> times grouping elements. If lengths of <code>lists</code> vary <code>fill_value</code> is used. By default <code>fill_value</code> is <code>None</code>.</p>
|
||||
|
||||
<pre class="language-python">def zip(*args, fillvalue=None):
|
||||
max_length = max([len(arr) for arr in args])
|
||||
result = []
|
||||
for i in range(max_length):
|
||||
result.append([
|
||||
args[k][i] if i < len(args[k]) else None for k in range(len(args))
|
||||
])
|
||||
return result</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]
|
||||
zip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]
|
||||
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="count_by" class="section double-padded">count_by</h3><!--<form action="" method="post"><button type="submit" value="count_by" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> Already implemented via <code>collections.Counter</code></p>
|
||||
<p>Groups the elements of a list based on the given function and returns the count of elements in each group.</p>
|
||||
<p>Use <code>map()</code> to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs.</p>
|
||||
|
||||
<pre class="language-python">def count_by(arr, fn=lambda x: x):
|
||||
key = {}
|
||||
for el in map(fn, arr):
|
||||
key[el] = 0 if not el in key else key[el]
|
||||
key[el] += 1
|
||||
return key</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">from math import floor
|
||||
count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2}
|
||||
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="difference_by" class="section double-padded">difference_by</h3><!--<form action="" method="post"><button type="submit" value="difference_by" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the difference between two list, after applying the provided function to each list element of both.</p>
|
||||
<p>Create a <code>set</code> by applying <code>fn</code> to each element in <code>b</code>, then use list comprehension in combination with fn on a to only keep values not contained in the previously created <code>set</code>.</p>
|
||||
|
||||
<pre class="language-python">def difference_by(a, b, fn):
|
||||
b = set(map(fn, b))
|
||||
return [item for item in a if fn(item) not in b]</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">from math import floor
|
||||
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
|
||||
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><h2 style="text-align:center">String</h2><div class="card fluid"><h3 id="count_vowels" class="section double-padded">count_vowels</h3><!--<form action="" method="post"><button type="submit" value="count_vowels" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Retuns <code>number</code> of vowels in provided <code>string</code>.</p>
|
||||
<p>Use a regular expression to count the number of vowels <code>(A, E, I, O, U)</code> in a string.</p>
|
||||
|
||||
<pre class="language-python">import re
|
||||
|
||||
|
||||
def count_vowels(str):
|
||||
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">count_vowels('foobar') # 3
|
||||
count_vowels('gym') # 0</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="byte_size" class="section double-padded">byte_size</h3><!--<form action="" method="post"><button type="submit" value="byte_size" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the length of a string in bytes.</p>
|
||||
<p><code>utf-8</code> encodes a given string and find its length.</p>
|
||||
|
||||
<pre class="language-python">def byte_size(string):
|
||||
return(len(string.encode('utf-8')))</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">byte_size('😀') # 4
|
||||
byte_size('Hello World') # 11</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="capitalize" class="section double-padded">capitalize</h3><!--<form action="" method="post"><button type="submit" value="capitalize" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Capitalizes the first letter of a string.</p>
|
||||
<p>Capitalizes the fist letter of the sring and then adds it with rest of the string. Omit the <code>lower_rest</code> parameter to keep the rest of the string intact, or set it to <code>true</code> to convert to lowercase.</p>
|
||||
|
||||
<pre class="language-python">def capitalize(string, lower_rest=False):
|
||||
return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">capitalize('fooBar') # 'FooBar'
|
||||
capitalize('fooBar', True) # 'Foobar'</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="capitalize_every_word" class="section double-padded">capitalize_every_word</h3><!--<form action="" method="post"><button type="submit" value="capitalize_every_word" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Capitalizes the first letter of every word in a string.</p>
|
||||
<p>Uses <code>str.title</code> to capitalize first letter of evry word in the string.</p>
|
||||
|
||||
<pre class="language-python">def capitalize_every_word(string):
|
||||
return string.title()</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">capitalize_every_word('hello world!') # 'Hello World!'</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="decapitalize" class="section double-padded">decapitalize</h3><!--<form action="" method="post"><button type="submit" value="decapitalize" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Decapitalizes the first letter of a string.</p>
|
||||
<p>Decapitalizes the fist letter of the sring and then adds it with rest of the string. Omit the <code>upper_rest</code> parameter to keep the rest of the string intact, or set it to <code>true</code> to convert to uppercase.</p>
|
||||
|
||||
<pre class="language-python">def decapitalize(string, upper_rest=False):
|
||||
return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">decapitalize('FooBar') # 'fooBar'
|
||||
decapitalize('FooBar', True) # 'fOOBAR'</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="palindrome" class="section double-padded">palindrome</h3><!--<form action="" method="post"><button type="submit" value="palindrome" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns <code>True</code> if the given string is a palindrome, <code>False</code> otherwise.</p>
|
||||
<p>Convert string <code>str.lower()</code> and use <code>re.sub</code> to remove non-alphanumeric characters from it. Then compare the new string to the reversed.</p>
|
||||
|
||||
<pre class="language-python">def palindrome(string):
|
||||
from re import sub
|
||||
s = sub('[\W_]', '', string.lower())
|
||||
return s == s[::-1]</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">palindrome('taco cat') # True</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="is_upper_case" class="section double-padded">is_upper_case</h3><!--<form action="" method="post"><button type="submit" value="is_upper_case" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Checks if a string is upper case.</p>
|
||||
<p>Convert the given string to upper case, using <code>str.upper()</code> method and compare it to the original.</p>
|
||||
|
||||
<pre class="language-python">def is_upper_case(str):
|
||||
return str == str.upper()</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">is_upper_case('ABC') # True
|
||||
is_upper_case('a3@$') # True
|
||||
is_upper_case('aB4') # False</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="is_lower_case" class="section double-padded">is_lower_case</h3><!--<form action="" method="post"><button type="submit" value="is_lower_case" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Checks if a string is lower case.</p>
|
||||
<p>Convert the given string to lower case, using <code>str.lower()</code> method and compare it to the original.</p>
|
||||
|
||||
<pre class="language-python">def is_lower_case(str):
|
||||
return str == str.lower()</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">is_lower_case('abc') # True
|
||||
is_lower_case('a3@$') # True
|
||||
is_lower_case('Ab4') # False</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><button class="scroll-to-top">↑</button>
|
||||
<footer><p style="display:inline-block"><strong>30 seconds of python code</strong> is licensed under the <a href="https://github.com/kriadmin/30-seconds-of-python-code/blob/master/LICENSE">GPL-3.0</a> license.<br>Icons made by <a href="https://www.flaticon.com/authors/smashicons">Smashicons</a> from <a href="https://www.flaticon.com/">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/">CC 3.0 BY</a>.<br>Ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> is licensed by <a href="https://opensource.org/licenses/MIT">The MIT License</a><br>Built with the <a href="https://minicss.org">mini.css framework</a>.</p></footer>
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block content %}<div class="row" style="height:calc(100vh - 5.875rem);overflow:hidden"><input id="doc-drawer-checkbox" class="drawer" value="on" type="checkbox"><nav class="col-md-4 col-lg-3" style="border-top:0"><div class="group"><input class="search" id="searchInput" onkeyup="search(this)" type="text"><label id="search-label">Search for snippet...</label></div><label for="doc-drawer-checkbox" class="button drawer-close"></label><h3 style = "">Math</h3><a class="sublink-1" tags="math" href="#average" style="">average</a><a class="sublink-1" tags="math" href="#factorial" style="">factorial</a><a class="sublink-1" tags="math" href="#gcd" style="">gcd</a><a class="sublink-1" tags="math" href="#lcm" style="">lcm</a><a class="sublink-1" tags="math" href="#max_n" style="">max_n</a><a class="sublink-1" tags="math" href="#min_n" style="">min_n</a><h3 style = "">List</h3><a class="sublink-1" tags="list" href="#chunk" style="">chunk</a><a class="sublink-1" tags="list" href="#compact" style="">compact</a><a class="sublink-1" tags="list" href="#count_occurences" style="">count_occurences</a><a class="sublink-1" tags="list" href="#deep_flatten" style="">deep_flatten</a><a class="sublink-1" tags="list" href="#difference" style="">difference</a><a class="sublink-1" tags="list" href="#shuffle" style="">shuffle</a><a class="sublink-1" tags="list" href="#spread" style="">spread</a><a class="sublink-1" tags="list" href="#zip" style="">zip</a><a class="sublink-1" tags="list" href="#count_by" style="">count_by</a><a class="sublink-1" tags="list" href="#difference_by" style="">difference_by</a><h3 style = "">String</h3><a class="sublink-1" tags="string" href="#count_vowels" style="">count_vowels</a><a class="sublink-1" tags="string" href="#byte_size" style="">byte_size</a><a class="sublink-1" tags="string" href="#capitalize" style="">capitalize</a><a class="sublink-1" tags="string" href="#capitalize_every_word" style="">capitalize_every_word</a><a class="sublink-1" tags="string" href="#decapitalize" style="">decapitalize</a><a class="sublink-1" tags="string" href="#palindrome" style="">palindrome</a><a class="sublink-1" tags="string" href="#is_upper_case" style="">is_upper_case</a><a class="sublink-1" tags="string" href="#is_lower_case" style="">is_lower_case</a></nav><main class="col-sm-12 col-md-8 col-lg-9" style="height:100%;overflow-y:auto;background:#eceef2;padding:0"><a id="top"></a><h2 style="text-align:center">Math</h2><div class="card fluid"><h3 id="average" class="section double-padded">average</h3><!--<form action="" method="post"><button type="submit" value="average" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> Already implemented via <code>statistics.mean</code>. <code>statistics.mean</code> takes an array as an argument whereas this function takes variadic arguments.</p>
|
||||
<p>Returns the average of two or more numbers.</p>
|
||||
<p>Takes the sum of all the <code>args</code> and divides it by <code>len(args)</code>. The secind argument <code>0.0</code> in sum is to handle floating point division in <code>python2</code>.</p>
|
||||
|
||||
<pre class="language-python">def average(*args):
|
||||
return sum(args, 0.0) / len(args)</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">average(*[1, 2, 3]) # 2.0
|
||||
average(1, 2, 3) # 2.0</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="factorial" class="section double-padded">factorial</h3><!--<form action="" method="post"><button type="submit" value="factorial" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Calculates the factorial of a number.</p>
|
||||
<p>Use recursion. If <code>num</code> is less than or equal to <code>1</code>, return <code>1</code>. Otherwise, return the product of <code>num</code> and the factorial of <code>num - 1</code>. Throws an exception if <code>num</code> is a negative or a floating point number.</p>
|
||||
|
||||
<pre class="language-python">def factorial(num):
|
||||
if not ((num >= 0) & (num % 1 == 0)):
|
||||
raise Exception(
|
||||
f"Number( {num} ) can't be floating point or negative ")
|
||||
return 1 if num == 0 else num * factorial(num - 1)</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">factorial(6) # 720</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="gcd" class="section double-padded">gcd</h3><!--<form action="" method="post"><button type="submit" value="gcd" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> <code>math.gcd</code> works with only two numbers</p>
|
||||
<p>Calculates the greatest common divisor between two or more numbers/lists.</p>
|
||||
<p>The <code>helperGcdfunction</code> uses recursion. Base case is when <code>y</code> equals <code>0</code>. In this case, return <code>x</code>. Otherwise, return the GCD of <code>y</code> and the remainder of the division <code>x/y</code>.</p>
|
||||
<p>Uses the reduce function from the inbuilt module <code>functools</code>. Also defines a method <code>spread</code> for javascript like spreading of lists.</p>
|
||||
|
||||
<pre class="language-python">from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def gcd(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
return reduce((lambda x, y: _gcd(x, y)), numbers)</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">gcd(8,36) # 4</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="lcm" class="section double-padded">lcm</h3><!--<form action="" method="post"><button type="submit" value="lcm" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the least common multiple of two or more numbers.</p>
|
||||
<p>Use the <code>greatest common divisor (GCD)</code> formula and the fact that <code>lcm(x,y) = x * y / gcd(x,y)</code> to determine the least common multiple. The GCD formula uses recursion.</p>
|
||||
<p>Uses <code>reduce</code> function from the inbuilt module <code>functools</code>. Also defines a method <code>spread</code> for javascript like spreading of lists.</p>
|
||||
|
||||
<pre class="language-python">from functools import reduce
|
||||
|
||||
|
||||
def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def lcm(*args):
|
||||
numbers = []
|
||||
numbers.extend(spread(list(args)))
|
||||
|
||||
def _gcd(x, y):
|
||||
return x if not y else gcd(y, x % y)
|
||||
|
||||
def _lcm(x, y):
|
||||
return x * y / _gcd(x, y)
|
||||
|
||||
return reduce((lambda x, y: _lcm(x, y)), numbers)</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">lcm(12, 7) # 84
|
||||
lcm([1, 3, 4], 5) # 60</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="max_n" class="section double-padded">max_n</h3><!--<form action="" method="post"><button type="submit" value="max_n" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the <code>n</code> maximum elements from the provided list. If <code>n</code> is greater than or equal to the provided list's length, then return the original list(sorted in descending order).</p>
|
||||
<p>Use <code>list.sort()</code> combined with the <code>deepcopy</code> function from the inbuilt <code>copy</code> module to create a shallow clone of the list and sort it in ascending order and then use <code>list.reverse()</code> reverse it to make it descending order. Use <code>[:n]</code> to get the specified number of elements. Omit the second argument, <code>n</code>, to get a one-element array</p>
|
||||
|
||||
<pre class="language-python">from copy import deepcopy
|
||||
|
||||
|
||||
def max_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
numbers.reverse()
|
||||
return numbers[:n]</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">max_n([1, 2, 3]) # [3]
|
||||
max_n([1, 2, 3], 2) # [3,2]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="min_n" class="section double-padded">min_n</h3><!--<form action="" method="post"><button type="submit" value="min_n" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the <code>n</code> minimum elements from the provided list. If <code>n</code> is greater than or equal to the provided list's length, then return the original list(sorted in ascending order).</p>
|
||||
<p>Use <code>list.sort()</code> combined with the <code>deepcopy</code> function from the inbuilt <code>copy</code> module to create a shallow clone of the list and sort it in ascending order. Use <code>[:n]</code> to get the specified number of elements. Omit the second argument, <code>n</code>, to get a one-element array</p>
|
||||
|
||||
<pre class="language-python">from copy import deepcopy
|
||||
|
||||
|
||||
def min_n(arr, n=1):
|
||||
numbers = deepcopy(arr)
|
||||
numbers.sort()
|
||||
return numbers[:n]</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">min_n([1, 2, 3]) # [1]
|
||||
min_n([1, 2, 3], 2) # [1,2]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><h2 style="text-align:center">List</h2><div class="card fluid"><h3 id="chunk" class="section double-padded">chunk</h3><!--<form action="" method="post"><button type="submit" value="chunk" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Chunks an array into smaller lists of a specified size.</p>
|
||||
<p>Uses <code>range</code> to create a list of desired size. Then use <code>map</code> on this list and fill it with splices of <code>arr</code>.</p>
|
||||
|
||||
<pre class="language-python">from math import ceil
|
||||
|
||||
|
||||
def chunk(arr, size):
|
||||
return list(
|
||||
map(lambda x: arr[x * size:x * size + size],
|
||||
list(range(0, ceil(len(arr) / size)))))</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="compact" class="section double-padded">compact</h3><!--<form action="" method="post"><button type="submit" value="compact" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Removes falsey values from a list.</p>
|
||||
<p>Use <code>filter()</code> to filter out falsey values (False, None, 0, and "").</p>
|
||||
|
||||
<pre class="language-python">def compact(arr):
|
||||
return list(filter(lambda x: bool(x), arr))</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="count_occurences" class="section double-padded">count_occurences</h3><!--<form action="" method="post"><button type="submit" value="count_occurences" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> Already implemented via <code>list.count()</code>.</p>
|
||||
<p>Counts the occurrences of a value in an list.</p>
|
||||
<p>Uses the <code>reduce</code> functin from built-in module <code>functools</code> to increment a counter each time you encounter the specific value inside the list.</p>
|
||||
|
||||
<pre class="language-python">def count_occurences(arr, val):
|
||||
return reduce(
|
||||
(lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
|
||||
arr)</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="deep_flatten" class="section double-padded">deep_flatten</h3><!--<form action="" method="post"><button type="submit" value="deep_flatten" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Deep flattens a list.</p>
|
||||
<p>Use recursion. Use <code>list.extend()</code> with an empty array (<code>result</code>) and the spread function to flatten a list. Recursively flatten each element that is a list.</p>
|
||||
|
||||
<pre class="language-python">def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret
|
||||
|
||||
|
||||
def deep_flatten(arr):
|
||||
result = []
|
||||
result.extend(
|
||||
spread(list(map(lambda x: deep(x) if type(x) == list else x, arr))))
|
||||
return result</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="difference" class="section double-padded">difference</h3><!--<form action="" method="post"><button type="submit" value="difference" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the difference between two arrays.</p>
|
||||
<p>Create a <code>set</code> from <code>b</code>, then use list comprehension to only keep values not contained in <code>b</code></p>
|
||||
|
||||
<pre class="language-python">def difference(a, b):
|
||||
b = set(b)
|
||||
return [item for item in a if item not in b]</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">difference([1, 2, 3], [1, 2, 4]) # [3]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="shuffle" class="section double-padded">shuffle</h3><!--<form action="" method="post"><button type="submit" value="shuffle" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> The same algorithm is already implemented via <code>random.shuffle</code>.</p>
|
||||
<p>Randomizes the order of the values of an list, returning a new list.</p>
|
||||
<p>Uses the <a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle">Fisher-Yates algorithm</a> to reorder the elements of the list.</p>
|
||||
|
||||
<pre class="language-python">from copy import deepcopy
|
||||
from random import randint
|
||||
|
||||
|
||||
def shuffle(arr):
|
||||
temp_arr = deepcopy(arr)
|
||||
m = len(temp_arr)
|
||||
while (m):
|
||||
m -= 1
|
||||
i = randint(0, m)
|
||||
temp_arr[m], temp_arr[i] = temp_arr[i], temp_arr[m]
|
||||
return temp_arr</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">foo = [1,2,3]
|
||||
shuffle(foo) # [2,3,1] , foo = [1,2,3]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="spread" class="section double-padded">spread</h3><!--<form action="" method="post"><button type="submit" value="spread" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Implements javascript's <code>[].concat(...arr)</code>. Flattens the list(non-deep) and returns an list.</p>
|
||||
|
||||
<pre class="language-python">def spread(arg):
|
||||
ret = []
|
||||
for i in arg:
|
||||
if isinstance(i, list):
|
||||
ret.extend(i)
|
||||
else:
|
||||
ret.append(i)
|
||||
return ret</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="zip" class="section double-padded">zip</h3><!--<form action="" method="post"><button type="submit" value="zip" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> Already implemented via <code>itertools.zip_longest()</code></p>
|
||||
<p>Creates a list of elements, grouped based on the position in the original lists.</p>
|
||||
<p>Use <code>max</code> combined with <code>list comprehension</code> to get the length of the longest list in the arguments. Loops for <code>max_length</code> times grouping elements. If lengths of <code>lists</code> vary <code>fill_value</code> is used. By default <code>fill_value</code> is <code>None</code>.</p>
|
||||
|
||||
<pre class="language-python">def zip(*args, fillvalue=None):
|
||||
max_length = max([len(arr) for arr in args])
|
||||
result = []
|
||||
for i in range(max_length):
|
||||
result.append([
|
||||
args[k][i] if i < len(args[k]) else None for k in range(len(args))
|
||||
])
|
||||
return result</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]
|
||||
zip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]
|
||||
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="count_by" class="section double-padded">count_by</h3><!--<form action="" method="post"><button type="submit" value="count_by" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p><emoji>ℹ</emoji> Already implemented via <code>collections.Counter</code></p>
|
||||
<p>Groups the elements of a list based on the given function and returns the count of elements in each group.</p>
|
||||
<p>Use <code>map()</code> to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs.</p>
|
||||
|
||||
<pre class="language-python">def count_by(arr, fn=lambda x: x):
|
||||
key = {}
|
||||
for el in map(fn, arr):
|
||||
key[el] = 0 if not el in key else key[el]
|
||||
key[el] += 1
|
||||
return key</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">from math import floor
|
||||
count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2}
|
||||
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="difference_by" class="section double-padded">difference_by</h3><!--<form action="" method="post"><button type="submit" value="difference_by" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the difference between two list, after applying the provided function to each list element of both.</p>
|
||||
<p>Create a <code>set</code> by applying <code>fn</code> to each element in <code>b</code>, then use list comprehension in combination with fn on a to only keep values not contained in the previously created <code>set</code>.</p>
|
||||
|
||||
<pre class="language-python">def difference_by(a, b, fn):
|
||||
b = set(map(fn, b))
|
||||
return [item for item in a if fn(item) not in b]</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">from math import floor
|
||||
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
|
||||
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><h2 style="text-align:center">String</h2><div class="card fluid"><h3 id="count_vowels" class="section double-padded">count_vowels</h3><!--<form action="" method="post"><button type="submit" value="count_vowels" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Retuns <code>number</code> of vowels in provided <code>string</code>.</p>
|
||||
<p>Use a regular expression to count the number of vowels <code>(A, E, I, O, U)</code> in a string.</p>
|
||||
|
||||
<pre class="language-python">import re
|
||||
|
||||
|
||||
def count_vowels(str):
|
||||
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">count_vowels('foobar') # 3
|
||||
count_vowels('gym') # 0</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="byte_size" class="section double-padded">byte_size</h3><!--<form action="" method="post"><button type="submit" value="byte_size" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns the length of a string in bytes.</p>
|
||||
<p><code>utf-8</code> encodes a given string and find its length.</p>
|
||||
|
||||
<pre class="language-python">def byte_size(string):
|
||||
return(len(string.encode('utf-8')))</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">byte_size('😀') # 4
|
||||
byte_size('Hello World') # 11</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="capitalize" class="section double-padded">capitalize</h3><!--<form action="" method="post"><button type="submit" value="capitalize" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Capitalizes the first letter of a string.</p>
|
||||
<p>Capitalizes the fist letter of the sring and then adds it with rest of the string. Omit the <code>lower_rest</code> parameter to keep the rest of the string intact, or set it to <code>true</code> to convert to lowercase.</p>
|
||||
|
||||
<pre class="language-python">def capitalize(string, lower_rest=False):
|
||||
return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">capitalize('fooBar') # 'FooBar'
|
||||
capitalize('fooBar', True) # 'Foobar'</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="capitalize_every_word" class="section double-padded">capitalize_every_word</h3><!--<form action="" method="post"><button type="submit" value="capitalize_every_word" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Capitalizes the first letter of every word in a string.</p>
|
||||
<p>Uses <code>str.title</code> to capitalize first letter of evry word in the string.</p>
|
||||
|
||||
<pre class="language-python">def capitalize_every_word(string):
|
||||
return string.title()</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">capitalize_every_word('hello world!') # 'Hello World!'</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="decapitalize" class="section double-padded">decapitalize</h3><!--<form action="" method="post"><button type="submit" value="decapitalize" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Decapitalizes the first letter of a string.</p>
|
||||
<p>Decapitalizes the fist letter of the sring and then adds it with rest of the string. Omit the <code>upper_rest</code> parameter to keep the rest of the string intact, or set it to <code>true</code> to convert to uppercase.</p>
|
||||
|
||||
<pre class="language-python">def decapitalize(string, upper_rest=False):
|
||||
return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">decapitalize('FooBar') # 'fooBar'
|
||||
decapitalize('FooBar', True) # 'fOOBAR'</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="palindrome" class="section double-padded">palindrome</h3><!--<form action="" method="post"><button type="submit" value="palindrome" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Returns <code>True</code> if the given string is a palindrome, <code>False</code> otherwise.</p>
|
||||
<p>Convert string <code>str.lower()</code> and use <code>re.sub</code> to remove non-alphanumeric characters from it. Then compare the new string to the reversed.</p>
|
||||
|
||||
<pre class="language-python">def palindrome(string):
|
||||
from re import sub
|
||||
s = sub('[\W_]', '', string.lower())
|
||||
return s == s[::-1]</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">palindrome('taco cat') # True</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="is_upper_case" class="section double-padded">is_upper_case</h3><!--<form action="" method="post"><button type="submit" value="is_upper_case" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Checks if a string is upper case.</p>
|
||||
<p>Convert the given string to upper case, using <code>str.upper()</code> method and compare it to the original.</p>
|
||||
|
||||
<pre class="language-python">def is_upper_case(str):
|
||||
return str == str.upper()</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">is_upper_case('ABC') # True
|
||||
is_upper_case('a3@$') # True
|
||||
is_upper_case('aB4') # False</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><div class="card fluid"><h3 id="is_lower_case" class="section double-padded">is_lower_case</h3><!--<form action="" method="post"><button type="submit" value="is_lower_case" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
|
||||
<p>Checks if a string is lower case.</p>
|
||||
<p>Convert the given string to lower case, using <code>str.lower()</code> method and compare it to the original.</p>
|
||||
|
||||
<pre class="language-python">def is_lower_case(str):
|
||||
return str == str.lower()</pre>
|
||||
<label class="collapse">Show examples</label>
|
||||
<pre class="language-python">is_lower_case('abc') # True
|
||||
is_lower_case('a3@$') # True
|
||||
is_lower_case('Ab4') # False</pre>
|
||||
<button class="primary clipboard-copy">📋 Copy to clipboard</button></div>
|
||||
|
||||
</div><button class="scroll-to-top">↑</button>
|
||||
<footer><p style="display:inline-block"><strong>30 seconds of python code</strong> is licensed under the <a href="https://github.com/kriadmin/30-seconds-of-python-code/blob/master/LICENSE">GPL-3.0</a> license.<br>Icons made by <a href="https://www.flaticon.com/authors/smashicons">Smashicons</a> from <a href="https://www.flaticon.com/">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/">CC 3.0 BY</a>.<br>Ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> is licensed by <a href="https://opensource.org/licenses/MIT">The MIT License</a><br>Built with the <a href="https://minicss.org">mini.css framework</a>.</p></footer>
|
||||
</main></div>{% endblock %}
|
||||
@ -1,16 +1,16 @@
|
||||
import json
|
||||
|
||||
|
||||
def vote(snippet):
|
||||
snippets = open('website/app/snippets').read().split('\n')
|
||||
with open('website/app/votes.json', 'r') as f:
|
||||
if snippet in snippets:
|
||||
data = json.load(f)
|
||||
try:
|
||||
data[snippet]
|
||||
except KeyError:
|
||||
data[snippet] = 0
|
||||
data[snippet] += 1
|
||||
open('website/app/votes.json','w').write(str(data).replace("'",'"'))
|
||||
else:
|
||||
raise Exception(f'{snippet} does not exists ')
|
||||
import json
|
||||
|
||||
|
||||
def vote(snippet):
|
||||
snippets = open('website/app/snippets').read().split('\n')
|
||||
with open('website/app/votes.json', 'r') as f:
|
||||
if snippet in snippets:
|
||||
data = json.load(f)
|
||||
try:
|
||||
data[snippet]
|
||||
except KeyError:
|
||||
data[snippet] = 0
|
||||
data[snippet] += 1
|
||||
open('website/app/votes.json','w').write(str(data).replace("'",'"'))
|
||||
else:
|
||||
raise Exception(f'{snippet} does not exists ')
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
import json
|
||||
|
||||
def vote_data():
|
||||
f = open('website/app/snippets')
|
||||
snippets = f.read().split('\n')
|
||||
f.close()
|
||||
|
||||
f = open('website/app/votes.json')
|
||||
votes_data = json.load(f)
|
||||
votes = {}
|
||||
for snippet in snippets:
|
||||
try:
|
||||
votes[snippet] = votes_data[snippet]
|
||||
except KeyError:
|
||||
votes[snippet] = 0
|
||||
return votes
|
||||
import json
|
||||
|
||||
def vote_data():
|
||||
f = open('website/app/snippets')
|
||||
snippets = f.read().split('\n')
|
||||
f.close()
|
||||
|
||||
f = open('website/app/votes.json')
|
||||
votes_data = json.load(f)
|
||||
votes = {}
|
||||
for snippet in snippets:
|
||||
try:
|
||||
votes[snippet] = votes_data[snippet]
|
||||
except KeyError:
|
||||
votes[snippet] = 0
|
||||
return votes
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user