Coder Social home page Coder Social logo

chalarangelo / 30-seconds-of-python Goto Github PK

View Code? Open in Web Editor NEW
8.8K 251.0 1.3K 66.89 MB

Short Python code snippets for all your development needs

Home Page: https://www.30secondsofcode.org/python/p/1

License: Creative Commons Attribution 4.0 International

Python 100.00%
snippets python3 learning-resources snippets-library snippets-collection learn-to-code programming education

30-seconds-of-python's Introduction

Hi there ๐Ÿ‘‹

I'm Angelos Chalaris, a web developer from Athens, Greece. I love programming both as a job and as a hobby and I spend a lot of time writing code and testing out new ideas. I work mainly with web technologies such as JavaScript, HTML, CSS, Node.js, React and SCSS, and I occasionally dabble in Python, Astro and Svelte.

My work ๐Ÿ”ญ

Contact ๐Ÿ“ซ

You can reach me via email at [email protected]

30-seconds-of-python's People

Contributors

0x00t0x7f avatar 30secondsofcode avatar akshatbhat avatar alex979 avatar animeshry avatar azanbinzahid avatar chalarangelo avatar defterade avatar dependabot[bot] avatar fejes713 avatar gurukiran07 avatar havanagrawal avatar hbaena avatar huybery avatar kshivi99 avatar lazargugleta avatar mattveraldi avatar meetzaveri avatar mx-psi avatar nampnq avatar natgho avatar rfezzani avatar rob-rychs avatar rohitanwar avatar rohitbabugaddeti avatar sachans avatar shriprajwalk avatar tasbihaasim avatar trinityyi avatar zhangfelix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

30-seconds-of-python's Issues

[BUG] deep_flatten not working

Description

The deep_flatten not working. Causing Error when I run it. (IDE - Pycharm)

[BUG] deep_flattern not working

Expected Snippet Behavior

Should perform as expected

Current Snippet Behavior

Error : NameError: global name 'deep' is not defined

Possible Solution

Not at current, but will come up as early as possible

ScreenShot

error1pycharm

Function naming conventions

Category: naming conventions

Summary:

CONTRIBUTING links to PEP8 which suggests:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

countOccurences() and countVowels() are camel-cased.

Possible Solution

Just let me know if you want a PR. 30-seconds-of-python-code sounds like a nice idea and I would contribute to (hopefully with more meaningful contributions) than this.

Refactor snippets to avoid using str as a variable

You use str as variable name and by doing so hiding the underlying function. Here is an example.
split_lines
def split_lines(str):
return str.split('\n')

This is bad coding - so please rename str to something else.

[FEATURE] Change license to CC-0

The license of this repository is GPL.3. The 30-seconds-of-javascript-code repo has CC-0. Since the code are snippets, why not having another license?

Superficially, GPL is equal to CC-BY-SA. CC-BY-SA has been used until March 2016 by stackoverflow. Now, they changed to MIT + additional attribution. See https://meta.stackexchange.com/questions/272956/a-new-code-license-the-mit-this-time-with-attribution-required for a long justification.

In contrast to CC-BY-SA, GPL demands that each user of a code snippet has to disclose all code where this snippet is used. Is this really the intention of choosing GPL as license?

I would recommend to use the same license as the JavaScript sister site. It is very liberal. However, one has to accept that the code is donated to the public. I hope, this is acceptable.

[FEATURE] count_by() could be improved.

[FEATURE] REPLACE THIS WITH A BRIEF SUMMARY OF THE SUGGESTED SNIPPET

Category:

Description

The current code used in count_by() needlessly sets the key value to itself. It could be more efficient and more straight-forward if changed.

Current Snippet Behavior

The current code:

def count_by(arr, fn=lambda x: x):
key = {}
for el in map(fn, arr):
key[el] = 0 if el not in key else key[el]
key[el] += 1
return key

Possible Solution

My suggested replacement:

def count_by(arr, fn=lambda x: x):
key = {}
for el in map(fn, arr):
key[el] = 1 if el not in key else key[el] + 1
return key

average ,there is ambiguity about the functional representation of the second parameter in the function sum

[FEATURE] REPLACE THIS WITH A BRIEF SUMMARY OF THE SUGGESTED SNIPPET

Category:

Description

[BUG] REPLACE THIS WITH A BRIEF SUMMARY OF YOUR ISSUE

Expected Snippet Behavior

There is ambiguity about the functional representation of the second parameter in the function sum, which should be dealing with floating-point number addition, not floating-point division. And this parameter is not necessary in python3.0. For numeric additions, Python 3.0 automatically converts numeric numbers into more complex numeric types, such as sum([1,2.0]) - 3.0, and / in Python 3.0 must get a floating point result.

Current Snippet Behavior

Possible Solution

[BUG] Definition for is_odd is incorrect

[BUG] is_odd snippet is incorrect, has implementation for is_even and invalid syntax

Expected Snippet Behavior

  1. The snippet should be valid Python3 syntax
  2. The snippet should execute is_odd correctly

Current Snippet Behavior

>>> def is_odd(num):
...   return num % 2 == `0`
  File "<stdin>", line 2
    return num % 2 == `0`
                      ^
SyntaxError: invalid syntax

Possible Solution

  1. Remove the backticks around the 0
  2. Use num % 2 != 0

keys_only implementation

Dictionaries already have a built-in functions for retrieving only the keys:

>>> d
{'a': 97, 'c': 99, 'b': {'i': 105, 'h': 104, 'k': 107, 'j': 106}, 'd': 100}
>>> d.keys()
['a', 'c', 'b', 'd']

A loop over the values isn't needed to access them.

[FEATURE] Using dict for to_dictionary

I totally understand their are preferences in the different choices between the different Python offering, so just suggesting one here for to_dictionary. Would love to hear your thoughts on it.

We could direct make use of the dict constructor which would make dictionary.

Current implementation

def to_dictionary(keys, values):
    return {key:value for key, value in zip(keys, values)}

Suggested implementation

def to_dictionary(key, values):
    return dict(zip(key, values))

Change array to lst or iterable

The affected snippets that need to be updated to use either the iterable or lst where appropriate are:

  • bubble_sort
  • chunk
  • compact
  • deep_flatten
  • insertion-sort
  • max_n
  • min_n
  • shuffle
  • zip

First timers are encouraged to contribute to this.

Possible integration into 30-seconds organization

Hello, there! Our GitHub organization would love to have you as part of the team. You will, of course, retain all rights to your code and repository, write access and all the good stuff. The only thing that changes is that the 30-seconds team will be able to help more often with your project's needs and you will get to have access to all our communication channels.

If you are interested, please reply with the following information:

  • Main person(s) responsible for the repository after the transfer (i.e. team leaders, up to 3 people).
  • Any other people who should be part of the organization as members of the Python team.

If you have any questions and/or concerns, please feel free to ask me about them.

[BUG] kebab function is not working for some strings

Current implementation of kebab function is not working for strings like 'camelCase'.

Current implementation

from re import sub

def kebab(s):
  return sub(
    r"(\s|_|-)+","-",
    sub(
      r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
      lambda mo: mo.group(0).lower(), s))

kebab('camelCase') # 'camel-case'
kebab('some text') # 'some-text'
kebab('some-mixed_string With spaces_underscores-and-hyphens') # 'some-mixed-string-with-spaces-underscores-and-hyphens'
kebab('AllThe-small Things') # "allthe-small-things"

Actually, kebab('camelCase') returns 'camelcase', and kebab('AllThe-small Things') returns 'all-the-small-things'

The first re.sub(pattern, repl, string, count=0, flags=0) function can find out all the words. But the repl function(lambda mo: mo.group(0).lower()) add nothing to separate them, just changes those words to lower case.

Inspired by snake function, I think kebab can be modified like follows:

from re import sub

def kebab(s):
  return '-'.join(
    sub(r"(\s|_|-)+"," ",
    sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
    lambda mo: ' ' + mo.group(0).lower(), s)).split())

All the examples works well:

>>> kebab('camelCase') # 'camel-case'
'camel-case'
>>> kebab('some text') # 'some-text'
'some-text'
>>> kebab('some-mixed_string With spaces_underscores-and-hyphens') # 'some-mixed-string-with-spaces-underscores-and-hyphens'
'some-mixed-string-with-spaces-underscores-and-hyphens'
>>> kebab('AllThe-small Things') # "all-the-small-things"
'all-the-small-things'

[BUG] is_anagram does not ignore punctuation or special characters and is inefficient

The is_anagram snippet does not ignore punctuation or special characters.
Furthermore, the running time could be improved using a collections.Counter.

Expected Snippet Behavior

is_anagram("#anagram", "Nag a ram!") should be True and run in linear time

Current Snippet Behavior

is_anagram("#anagram", "Nag a ram!") is False.

In cases where it does not fail it runs in linearithmic time (because of sorting), instead of linear time.

Possible Solution

One may improve the code as follows:

from collections import Counter

def is_anagram(s1, s2):
  return Counter(
    c.lower() for c in s1 if c.isalnum()
  ) == Counter(
    c.lower() for c in s2 if c.isalnum()
  )

The code counts the alphanumeric characters on each string in their lowercase version and checks if the counters match. There is no need for sorting and the intermediate strings need not be created.

I intend to open a PR for fixing this but I am unsure as to what counts as a special character.
In the suggested fix, str.isalnum considers characters like U+2460 'โ‘ ' to be alphanumeric and thus not a special character. Is that the correct interpretation of "special character"?

[FEATURE] map_values() could be improved

Category:

Description

Can be done in a single line.

Current Snippet Behavior

Current code:

def map_values(obj, fn):
	ret = {}
	for key in obj.keys():
		ret[key] = fn(obj[key])
	return ret

Possible Solution

Suggested replacement:

def map_values(obj, fn):
	return {key: fn(obj[key]) for key in obj}

Return value is not true for is_upper_case("a3@$")

[BUG] wrong return value for is_upper_case("a3@$")

Expected Snippet Behavior

in 30-seconds-of-python-code/snippets/is_upper_case.md

is_upper_case('ABC') # True
is_upper_case('a3@$') # False
is_upper_case('aB4') # False

Current Snippet Behavior

in 30-seconds-of-python-code/snippets/is_upper_case.md

is_upper_case('ABC') # True
is_upper_case('a3@$') # True
is_upper_case('aB4') # False

[FEATURE] Improve filter_unique and filter_non_unique running time

The filter_non_unique and filter_unique snippets currently have a quadratic running time; in both cases they count each item in the original list. This can be improved to linear time by using a counter from the collections module (at the expense of linear space).

Improvement of filter_unique

from collections import Counter


def filter_unique(lst):
  counter = Counter(lst)
  return [item for item, count in counter.items() if count > 1]

Improvement of filter_non_unique

from collections import Counter


def filter_non_unique(lst):
  counter = Counter(lst)
  return [item for item, count in counter.items() if count == 1]

Distinguish between lists and arrays

All throughout the snippets, text and variable names refer to arrays. In Python and other languages, arrays contain objects of the same type. The array module in the standard library implements this.

Instead, what is often meant is lists, or really, iterables. Conversely, the variable name should be lst or l instead of arr.

[FEATURE] use any() and all() instead of for loops in every, some and none

Category:

Description

Current Snippet Behavior

def none(lst, fn=lambda x: not not x):
  for el in lst:
    if fn(el):
      return False
  return True

def some(lst, fn=lambda x: not not x):
  for el in lst:
    if fn(el):
      return True
  return False

def every(lst, fn=lambda x: not not x):
  for el in lst:
    if not fn(el):
      return False
  return True

Possible Solution

def none(lst, fn=lambda x: x):
  return not all(map(fn, lst))

def some(lst, fn=lambda x: x):
  return any(map(fn, lst))

def every(lst, fn=lambda x: x):
  return all(map(fn, lst))

Undefined names

Is the flake8 testing working in the Travis CI process?

flake8 testing of https://github.com/kriadmin/30-seconds-of-python-code on Python 3.7.0

$ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics

./website/web/Lib/site-packages/itsdangerous.py:26:17: F821 undefined name 'unicode'
    text_type = unicode
                ^
./website/web/Lib/site-packages/itsdangerous.py:28:26: F821 undefined name 'long'
    number_types = (int, long, float)
                         ^
./website/web/Lib/site-packages/setuptools/site-patch.py:41:26: F821 undefined name 'makepath'
    known_paths = dict([(makepath(item)[1], 1) for item in sys.path])  # 2.2 comp
                         ^
./website/web/Lib/site-packages/setuptools/site-patch.py:47:9: F821 undefined name 'addsitedir'
        addsitedir(item)
        ^
./website/web/Lib/site-packages/setuptools/site-patch.py:51:13: F821 undefined name 'makepath'
    d, nd = makepath(stdpath[0])
            ^
./website/web/Lib/site-packages/setuptools/site-patch.py:56:17: F821 undefined name 'makepath'
        p, np = makepath(item)
                ^
./website/web/Lib/site-packages/setuptools/command/egg_info.py:641:12: F821 undefined name 'StringIO'
    data = StringIO()
           ^
./website/web/Lib/site-packages/pip/_vendor/pyparsing.py:129:13: F821 undefined name 'xrange'
    range = xrange
            ^
./website/web/Lib/site-packages/pip/_vendor/pyparsing.py:136:27: F821 undefined name 'unicode'
        if isinstance(obj,unicode):
                          ^
./website/web/Lib/site-packages/pip/_vendor/pyparsing.py:146:19: F821 undefined name 'unicode'
            ret = unicode(obj).encode(sys.getdefaultencoding(), 'xmlcharrefreplace')
                  ^
./website/web/Lib/site-packages/pip/_vendor/six.py:49:20: F821 undefined name 'basestring'
    string_types = basestring,
                   ^
./website/web/Lib/site-packages/pip/_vendor/six.py:50:27: F821 undefined name 'long'
    integer_types = (int, long)
                          ^
./website/web/Lib/site-packages/pip/_vendor/six.py:52:17: F821 undefined name 'unicode'
    text_type = unicode
                ^
./website/web/Lib/site-packages/pip/_vendor/six.py:647:16: F821 undefined name 'unicode'
        return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
               ^
./website/web/Lib/site-packages/pip/_vendor/six.py:730:37: F821 undefined name 'basestring'
            if not isinstance(data, basestring):
                                    ^
./website/web/Lib/site-packages/pip/_vendor/six.py:733:32: F821 undefined name 'file'
            if (isinstance(fp, file) and
                               ^
./website/web/Lib/site-packages/pip/_vendor/six.py:734:38: F821 undefined name 'unicode'
                    isinstance(data, unicode) and
                                     ^
./website/web/Lib/site-packages/pip/_vendor/six.py:744:32: F821 undefined name 'unicode'
            if isinstance(sep, unicode):
                               ^
./website/web/Lib/site-packages/pip/_vendor/six.py:750:32: F821 undefined name 'unicode'
            if isinstance(end, unicode):
                               ^
./website/web/Lib/site-packages/pip/_vendor/six.py:758:36: F821 undefined name 'unicode'
                if isinstance(arg, unicode):
                                   ^
./website/web/Lib/site-packages/pip/_vendor/six.py:762:23: F821 undefined name 'unicode'
            newline = unicode("\n")
                      ^
./website/web/Lib/site-packages/pip/_vendor/six.py:763:21: F821 undefined name 'unicode'
            space = unicode(" ")
                    ^
./website/web/Lib/site-packages/pip/_vendor/appdirs.py:503:12: F821 undefined name 'kernal'
        if kernal.GetShortPathName(dir, buf, buf_size):
           ^
./website/web/Lib/site-packages/pip/_vendor/requests/models.py:335:19: F821 undefined name 'unicode'
            url = unicode(url) if is_py2 else str(url)
                  ^
./website/web/Lib/site-packages/pip/_vendor/requests/compat.py:52:11: F821 undefined name 'unicode'
    str = unicode
          ^
./website/web/Lib/site-packages/pip/_vendor/requests/compat.py:53:18: F821 undefined name 'basestring'
    basestring = basestring
                 ^
./website/web/Lib/site-packages/pip/_vendor/requests/compat.py:54:27: F821 undefined name 'long'
    numeric_types = (int, long, float)
                          ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:49:20: F821 undefined name 'basestring'
    string_types = basestring,
                   ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:50:27: F821 undefined name 'long'
    integer_types = (int, long)
                          ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:52:17: F821 undefined name 'unicode'
    text_type = unicode
                ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:647:16: F821 undefined name 'unicode'
        return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
               ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:730:37: F821 undefined name 'basestring'
            if not isinstance(data, basestring):
                                    ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:733:32: F821 undefined name 'file'
            if (isinstance(fp, file) and
                               ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:734:38: F821 undefined name 'unicode'
                    isinstance(data, unicode) and
                                     ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:744:32: F821 undefined name 'unicode'
            if isinstance(sep, unicode):
                               ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:750:32: F821 undefined name 'unicode'
            if isinstance(end, unicode):
                               ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:758:36: F821 undefined name 'unicode'
                if isinstance(arg, unicode):
                                   ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:762:23: F821 undefined name 'unicode'
            newline = unicode("\n")
                      ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py:763:21: F821 undefined name 'unicode'
            space = unicode(" ")
                    ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/chardet/__init__.py:23:53: F821 undefined name 'unicode'
    if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or
                                                    ^
./website/web/Lib/site-packages/pip/_vendor/requests/packages/chardet/compat.py:25:22: F821 undefined name 'unicode'
    base_str = (str, unicode)
                     ^
./website/web/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py:1930:5: F821 undefined name '_distribution_finders'
    _distribution_finders[importer_type] = distribution_finder
    ^
./website/web/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py:1936:28: F821 undefined name '_distribution_finders'
    finder = _find_adapter(_distribution_finders, importer)
                           ^
./website/web/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py:2067:5: F821 undefined name '_namespace_handlers'
    _namespace_handlers[importer_type] = namespace_handler
    ^
./website/web/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py:2086:29: F821 undefined name '_namespace_handlers'
    handler = _find_adapter(_namespace_handlers, importer)
                            ^
./website/web/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py:2130:27: F821 undefined name '_namespace_packages'
        if packageName in _namespace_packages:
                          ^
./website/web/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py:2137:30: F821 undefined name '_namespace_packages'
            if parent not in _namespace_packages:
                             ^
./website/web/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py:2146:9: F821 undefined name '_namespace_packages'
        _namespace_packages.setdefault(parent, []).append(packageName)
        ^
./website/web/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py:2147:9: F821 undefined name '_namespace_packages'
        _namespace_packages.setdefault(packageName, [])
        ^
./website/web/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py:2162:24: F821 undefined name '_namespace_packages'
        for package in _namespace_packages.get(parent, ()):
                       ^
./website/web/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py:2726:35: F821 undefined name '_namespace_packages'
                    or modname in _namespace_packages):
                                  ^
./website/web/Lib/site-packages/pip/_vendor/distlib/locators.py:581:57: F821 undefined name 'd'
        'gzip': lambda b: gzip.GzipFile(fileobj=BytesIO(d)).read(),
                                                        ^
./website/web/Lib/site-packages/pip/_vendor/distlib/compat.py:20:20: F821 undefined name 'basestring'
    string_types = basestring,
                   ^
./website/web/Lib/site-packages/pip/_vendor/distlib/compat.py:21:17: F821 undefined name 'unicode'
    text_type = unicode
                ^
./website/web/Lib/site-packages/pip/_vendor/distlib/compat.py:31:26: F821 undefined name 'unicode'
        if isinstance(s, unicode):
                         ^
./website/web/Lib/site-packages/pip/_vendor/distlib/compat.py:47:17: F821 undefined name 'raw_input'
    raw_input = raw_input
                ^
./website/web/Lib/site-packages/pip/_vendor/distlib/compat.py:493:37: F821 undefined name 'get_ident'
                    key = id(self), get_ident()
                                    ^
./website/web/Lib/site-packages/cffi/verifier.py:25:30: F821 undefined name 'unicode'
            if isinstance(s, unicode):
                             ^
./website/web/Lib/site-packages/click/_termui_impl.py:44:39: F821 undefined name 'long'
           not isinstance(hint, (int, long)) or \
                                      ^
./website/web/Lib/site-packages/click/_compat.py:138:17: F821 undefined name 'unicode'
    text_type = unicode
                ^
./website/web/Lib/site-packages/click/_compat.py:140:17: F821 undefined name 'raw_input'
    raw_input = raw_input
                ^
./website/web/Lib/site-packages/click/_compat.py:141:26: F821 undefined name 'unicode'
    string_types = (str, unicode)
                         ^
./website/web/Lib/site-packages/click/_compat.py:143:18: F821 undefined name 'xrange'
    range_type = xrange
                 ^
./website/web/Lib/site-packages/click/_compat.py:146:31: F821 undefined name 'buffer'
        return isinstance(x, (buffer, bytearray))
                              ^
./website/web/Lib/site-packages/werkzeug/websocket.py:18:28: F821 undefined name 'unicode'
    if isinstance(message, unicode):
                           ^
./website/web/Lib/site-packages/werkzeug/websocket.py:102:22: F821 undefined name 'xrange'
            for i in xrange(0, int(f['length']/4)):
                     ^
./website/web/Lib/site-packages/werkzeug/websocket.py:217:16: F821 undefined name 'ALREADY_HANDLED'
        return ALREADY_HANDLED
               ^
./website/web/Lib/site-packages/pkg_resources/__init__.py:1929:5: F821 undefined name '_distribution_finders'
    _distribution_finders[importer_type] = distribution_finder
    ^
./website/web/Lib/site-packages/pkg_resources/__init__.py:1935:28: F821 undefined name '_distribution_finders'
    finder = _find_adapter(_distribution_finders, importer)
                           ^
./website/web/Lib/site-packages/pkg_resources/__init__.py:2066:5: F821 undefined name '_namespace_handlers'
    _namespace_handlers[importer_type] = namespace_handler
    ^
./website/web/Lib/site-packages/pkg_resources/__init__.py:2085:29: F821 undefined name '_namespace_handlers'
    handler = _find_adapter(_namespace_handlers, importer)
                            ^
./website/web/Lib/site-packages/pkg_resources/__init__.py:2129:27: F821 undefined name '_namespace_packages'
        if packageName in _namespace_packages:
                          ^
./website/web/Lib/site-packages/pkg_resources/__init__.py:2136:30: F821 undefined name '_namespace_packages'
            if parent not in _namespace_packages:
                             ^
./website/web/Lib/site-packages/pkg_resources/__init__.py:2145:9: F821 undefined name '_namespace_packages'
        _namespace_packages.setdefault(parent, []).append(packageName)
        ^
./website/web/Lib/site-packages/pkg_resources/__init__.py:2146:9: F821 undefined name '_namespace_packages'
        _namespace_packages.setdefault(packageName, [])
        ^
./website/web/Lib/site-packages/pkg_resources/__init__.py:2161:24: F821 undefined name '_namespace_packages'
        for package in _namespace_packages.get(parent, ()):
                       ^
./website/web/Lib/site-packages/pkg_resources/__init__.py:2725:35: F821 undefined name '_namespace_packages'
                    or modname in _namespace_packages):
                                  ^
./website/web/Lib/site-packages/pkg_resources/_vendor/pyparsing.py:129:13: F821 undefined name 'xrange'
    range = xrange
            ^
./website/web/Lib/site-packages/pkg_resources/_vendor/pyparsing.py:136:27: F821 undefined name 'unicode'
        if isinstance(obj,unicode):
                          ^
./website/web/Lib/site-packages/pkg_resources/_vendor/pyparsing.py:146:19: F821 undefined name 'unicode'
            ret = unicode(obj).encode(sys.getdefaultencoding(), 'xmlcharrefreplace')
                  ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:49:20: F821 undefined name 'basestring'
    string_types = basestring,
                   ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:50:27: F821 undefined name 'long'
    integer_types = (int, long)
                          ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:52:17: F821 undefined name 'unicode'
    text_type = unicode
                ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:647:16: F821 undefined name 'unicode'
        return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
               ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:730:37: F821 undefined name 'basestring'
            if not isinstance(data, basestring):
                                    ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:733:32: F821 undefined name 'file'
            if (isinstance(fp, file) and
                               ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:734:38: F821 undefined name 'unicode'
                    isinstance(data, unicode) and
                                     ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:744:32: F821 undefined name 'unicode'
            if isinstance(sep, unicode):
                               ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:750:32: F821 undefined name 'unicode'
            if isinstance(end, unicode):
                               ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:758:36: F821 undefined name 'unicode'
                if isinstance(arg, unicode):
                                   ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:762:23: F821 undefined name 'unicode'
            newline = unicode("\n")
                      ^
./website/web/Lib/site-packages/pkg_resources/_vendor/six.py:763:21: F821 undefined name 'unicode'
            space = unicode(" ")
                    ^
./website/web/Lib/site-packages/pkg_resources/_vendor/appdirs.py:503:12: F821 undefined name 'kernal'
        if kernal.GetShortPathName(dir, buf, buf_size):
           ^
./website/web/Lib/site-packages/jinja2/bccache.py:37:26: F821 undefined name 'file'
        if isinstance(f, file):
                         ^
./website/web/Lib/site-packages/jinja2/bccache.py:43:26: F821 undefined name 'file'
        if isinstance(f, file):
                         ^
./website/web/Lib/site-packages/jinja2/_compat.py:51:17: F821 undefined name 'unicode'
    text_type = unicode
                ^
./website/web/Lib/site-packages/jinja2/_compat.py:52:18: F821 undefined name 'xrange'
    range_type = xrange
                 ^
./website/web/Lib/site-packages/jinja2/_compat.py:53:26: F821 undefined name 'unicode'
    string_types = (str, unicode)
                         ^
./website/web/Lib/site-packages/jinja2/_compat.py:54:27: F821 undefined name 'long'
    integer_types = (int, long)
                          ^
./website/web/Lib/site-packages/jinja2/_compat.py:80:33: F821 undefined name 'unicode'
        if isinstance(filename, unicode):
                                ^
./website/web/Lib/site-packages/markupsafe/_compat.py:22:17: F821 undefined name 'unicode'
    text_type = unicode
                ^
./website/web/Lib/site-packages/markupsafe/_compat.py:23:26: F821 undefined name 'unicode'
    string_types = (str, unicode)
                         ^
./website/web/Lib/site-packages/markupsafe/_compat.py:25:23: F821 undefined name 'long'
    int_types = (int, long)
                      ^
./website/web/Lib/site-packages/gunicorn/six.py:47:20: F821 undefined name 'basestring'
    string_types = basestring,
                   ^
./website/web/Lib/site-packages/gunicorn/six.py:48:27: F821 undefined name 'long'
    integer_types = (int, long)
                          ^
./website/web/Lib/site-packages/gunicorn/six.py:50:17: F821 undefined name 'unicode'
    text_type = unicode
                ^
./website/web/Lib/site-packages/gunicorn/six.py:601:16: F821 undefined name 'unicode'
        return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
               ^
./website/web/Lib/site-packages/gunicorn/six.py:654:37: F821 undefined name 'basestring'
            if not isinstance(data, basestring):
                                    ^
./website/web/Lib/site-packages/gunicorn/six.py:657:32: F821 undefined name 'file'
            if (isinstance(fp, file) and
                               ^
./website/web/Lib/site-packages/gunicorn/six.py:658:34: F821 undefined name 'unicode'
                isinstance(data, unicode) and
                                 ^
./website/web/Lib/site-packages/gunicorn/six.py:668:32: F821 undefined name 'unicode'
            if isinstance(sep, unicode):
                               ^
./website/web/Lib/site-packages/gunicorn/six.py:674:32: F821 undefined name 'unicode'
            if isinstance(end, unicode):
                               ^
./website/web/Lib/site-packages/gunicorn/six.py:682:36: F821 undefined name 'unicode'
                if isinstance(arg, unicode):
                                   ^
./website/web/Lib/site-packages/gunicorn/six.py:686:23: F821 undefined name 'unicode'
            newline = unicode("\n")
                      ^
./website/web/Lib/site-packages/gunicorn/six.py:687:21: F821 undefined name 'unicode'
            space = unicode(" ")
                    ^
./website/web/Lib/site-packages/gunicorn/_compat.py:91:16: F821 undefined name 'execfile'
        return execfile(fname, *args)
               ^
./website/web/Lib/site-packages/gunicorn/_compat.py:94:26: F821 undefined name 'unicode'
        if isinstance(s, unicode):
                         ^
./website/web/Lib/site-packages/gunicorn/workers/_gaiohttp.py:49:36: E999 SyntaxError: invalid syntax
        self._runner = asyncio.async(self._run(), loop=self.loop)
                                   ^
./website/web/Lib/site-packages/gunicorn/workers/ggevent.py:30:27: E999 SyntaxError: invalid syntax
from gunicorn.workers.async import AsyncWorker
                          ^
./website/web/Lib/site-packages/gunicorn/workers/geventlet.py:27:27: E999 SyntaxError: invalid syntax
from gunicorn.workers.async import AsyncWorker
                          ^
./website/web/Lib/site-packages/flask/_compat.py:38:17: F821 undefined name 'unicode'
    text_type = unicode
                ^
./website/web/Lib/site-packages/flask/_compat.py:39:26: F821 undefined name 'unicode'
    string_types = (str, unicode)
                         ^
./website/web/Lib/site-packages/flask/_compat.py:40:27: F821 undefined name 'long'
    integer_types = (int, long)
                          ^
./website/web/Lib/site-packages/oauth2/_compat.py:11:21: F821 undefined name 'unicode'
    STRING_TYPES = (unicode, bytes)
                    ^
./website/web/Lib/site-packages/oauth2/_compat.py:13:26: F821 undefined name 'unicode'
        if isinstance(x, unicode):
                         ^
./website/web/Lib/site-packages/pycparser/ply/yacc.py:97:20: F821 undefined name 'basestring'
    string_types = basestring
                   ^
./website/web/Lib/site-packages/pycparser/ply/yacc.py:1363:26: F821 undefined name 'Prodnames'
            p.lr_after = Prodnames[p.prod[n+1]]
                         ^
./website/web/Lib/site-packages/pycparser/ply/cpp.py:16:26: F821 undefined name 'unicode'
    STRING_TYPES = (str, unicode)
                         ^
./test/bubble_sort/bubble_sort.test.py:5:1: E999 IndentationError: expected an indented block
t.true(isinstance(bubble_sort, (types.BuiltinFunctionType, types.FunctionType, functools.partial)),'<util.read_snippets.<locals>.snippet object at 0x7fc8ea4c6978> is a function')
^
./test/has_duplicates/has_duplicates.test.py:6:31: F821 undefined name 'has_duplicates_test'
test('Testing has_duplicates',has_duplicates_test)                              ^
./test/all_unique/all_unique.test.py:6:27: F821 undefined name 'all_unique_test'
test('Testing all_unique',all_unique_test)                          ^
4     E999 IndentationError: expected an indented block
127   F821 undefined name 'all_unique_test'
131

difference example

The provided example is unnecessary complicated! sets in Python by themselves define set operations like difference and many others...So it is better to replace this example:

def difference(a, b):
    b = set(b)
    return [item for item in a if item not in b]

with this:

def difference(lst1, lst2):
    return list(set(lst1) - set(lst2))

Also none of these examples take into account if elements of a or b (lst1 or lst2) are hashable. The same critique goes for difference_by example.

[QUESTION]Whether to pay attention to parameter checking and exception handling

Should we pay attention to parameter checking and exception handling, or should we focus more on showing a possible idea for solving the problem?

For example in lcm.md, the current implementation has the potential to cause a divide by zero exception.

Also, by definition, lcm should be a positive integer. However, the current implementation may result in the return of a negative number.

Current implementation

from functools import reduce
from math import gcd

def lcm(numbers):
  return reduce((lambda x, y: int(x * y / gcd(x, y))), numbers)

[FEATURE] replace for loop in group_by with dictionary comprehension

Category:

Description

Also removes unnecessary list cast.

There are also unnecessary semicolons in the examples section of this function.

Current Snippet Behavior

def group_by(lst, fn):
  groups = {}
  for key in list(map(fn,lst)):
    groups[key] = [item for item in lst if fn(item) == key]
  return groups

Possible Solution

def group_by(lst, fn):
    return {key : [el for el in lst if fn(el) == key] for key in map(fn,lst)}

[FEATURE] remove unnecessary list casts in min_by, max_by, sum_by

Category:

Description

min(), max() and sum() take any iterable.

Current Snippet Behavior

def min_by(lst, fn):
  return min(list(map(fn,lst)))

def max_by(lst, fn):
  return max(list(map(fn,lst)))

def sum_by(lst, fn):
  return sum(list(map(fn,lst)))

Possible Solution

def min_by(lst, fn):
  return min(map(fn,lst))

def max_by(lst, fn):
  return max(map(fn,lst))

def sum_by(lst, fn):
  return sum(map(fn,lst))

[IMPROVEMENT] Definition for lcm is unnecessarily complicated

[IMPROVEMENT] Simplify the definition for lcm

Description

Currently, lcm has the following snippet:

from functools import reduce
import math

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 _lcm(x, y):
    return int(x * y / math.gcd(x, y))

  return reduce((lambda x, y: _lcm(x, y)), numbers)

This is hardly a 30-second snippet, especially if you are looking at it in isolation. Most of the code is tangential to calculating the LCM. It is also an unlikely usage pattern (I don't think anyone expects to use lcm as lcm([[5, 10], [4, 6, [2]], 8])). If this were to follow the pattern all other snippets follow, it would probably look like this:

from math import gcd
from functools import reduce

def lcm(*nums):
  def _lcm(x, y):
    return int(x * y / gcd(x, y))

  return reduce(_lcm, nums)

[FEATURE] Topic wise Snippets

Topic-wise snippets like:

  • For web [Flask and Django Snippets]
  • For Machine Learning and Data Science [ Numpy, Pandas,etc.]
  • For OOPs

I am experienced in machine learning and Django, can I PR the Topic Feature in the code with some snippets.

[BUG] count_occurences

[BUG] count_occurences

snippet is :

from functools import reduce


def count_occurences(arr, val):
    return reduce(
        (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
        arr)

count_occurences([1, 1, 2, 1, 2, 3], 1) # 3

but when I want to run that :

count_occurences([2, 1, 2, 1, 2, 3], 1)  # 2

But it returns the count_occurences is 4. A mistake has happened.
I think this code run successfully only when the first element of list is 1 and the val is 1.
And I can't find a more pythonic code to repalce list.count()

[BUG] - [VERY LITTLE :-] - use - for snake, not _

Hi,
First congratulation for this great work !!!

There is a little mistake in the snake case snippet, it mention '_' in examples results but i think it might be a '-', take a look to following lines :

[BUG] use - for snake, not _

Expected Snippet Behavior

'-' in examples results

Current Snippet Behavior

'_' in examples results

Possible Solution

'-' in examples results

Best regards,
Julien

[FEATURE] Suggest using builtin functions when similar options exist

The Python Standard Library has functions with similar behavior to some snippets.
In particular:

  1. The split_lines snippet has similar functionality to the str.splitlines method (the latter being more general and omitting the last line) and
  2. the zip snippet has similar behavior to the itertools.zip_longest function (the latter returning an iterator instead of a list).

The functions don't have the exact same behavior, so it might make sense to keep them, but I believe it would be helpful for visitors to at least have a reference to the standard library version in the snippet documentation; that way they can choose the option that best fits their needs.

[Question] average snippet references python2 in description? Typo?

The snippet average mentions python2 in the snippet description but I thought this project was using 100% python3? If so the snippet description for average should probably be updated to not confuse people. It might also be a good idea to add a python3 badge to the top of the readme file so that it's obvious for new people/contributors.

Category:

Description

Expected Snippet Behavior

Current Snippet Behavior

Possible Solution

[FEATURE] Using defaultdict in *group_by* implementation

The current implementation of group_by loops twice over the lst, which significantly reduces the speed when working with large data. Instead using defaultdict will make it possible to loop over the lst only once.

Current implementation:

def group_by(lst, fn):
    return {key: [el for el in lst if fn(el] == key] for key in map(fn, lst)}

Suggested implementation:

from collections import defaultdict

def group_by(lst, fn):
    d = defaultdict(list)
    for el in lst:
        d[fn(el)].append(el)
    return d

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.