Skip to content

Instantly share code, notes, and snippets.

@kylebgorman
Created November 11, 2022 17:13
Show Gist options
  • Save kylebgorman/4acb1cd4e0c346fb59e00ab431b761f9 to your computer and use it in GitHub Desktop.
Save kylebgorman/4acb1cd4e0c346fb59e00ab431b761f9 to your computer and use it in GitHub Desktop.
Methods I HW6 style notes

HW6 style notes

The following were common style issues seen in HW6:

  • When indexing into a list or tuple x, x[0:10] is redundant; just write x[:10].

  • Similarly, the last ten elements of x are given by x[-10:] and other forms are either redundant or wrong.

  • Avoid "noop" list comprehensions. For instance if lexicon is a list,

    new_lexicon = [item for item in lexicon]

    does nothing other than (slowly and obfuscatorily) making a copy of the lexicon. Or, if lexicon is a set and one desireds to convert it to a list, just use the faster:

    lexicon_list = list(lexicon)
  • If you want to convert a set to a sorted list, just use sorted. Converting it to a list and then sorting it in place with .sort is, once again, slow and obfuscatory.

  • If you want to sort by length, just use the built-in len function as the key:

    lexicon_by_length = sorted(lexicon, key=len)

    In this case there is no need to define a helper function.

  • When you're iterating over the lines of a file, you almost always want to .rstrip() the line before further processing. Make the following a habit:

    for line in source:
        line = line.rstrip()  # Gets rid of trailing newline.
        ...
  • line.split(" ") is redundant. Just write line.split() since it already splits on whitespace by default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment