Skip to content

Instantly share code, notes, and snippets.

@JimDennis
Forked from anonymous/mystery_code.py
Last active August 10, 2017 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JimDennis/9c2eb2ee9167751d84863bfd0aab8597 to your computer and use it in GitHub Desktop.
Save JimDennis/9c2eb2ee9167751d84863bfd0aab8597 to your computer and use it in GitHub Desktop.
Mystery Python code from G+
#/usr/bin/env python
from __future__ import print_function
import random
list1 = list('abc') # We can expand strings into lists with this:
list2 = list1[:] # Makes a (shallow) copy of the list
letter_counts = dict()
for letter in list1:
# Compact way to initialize counts for each of our possible letters
# Dynamically adjusts if you change your list1 initialization above, too.
letter_counts[letter] = 0
def main(source, target=letter_counts):
'''Randomly choose from source and update count in target (dictionary)
source must be a mutable list-like object supporting the .remove() method
target must be a dictionary-like object with valid keys (letters) initialized
to integer values.
'''
# Defining parameters and calling with arguments eliminates the need for global variables
# ... defining target with a default is possible, perhaps even reasonable.
results = 'No letters' # (Default from the bottom "else" in the original example)
# (Well written functions often bind some value(s) to a variable named "results" and
# end with the statement: return results
# This prevents having multiple exit points scattered throughout a function which
# makes code easier to read and much easier to reason about and maintain.
if not source:
return results
# random.choice() would raise an "IndexError" if we passed an empty value
# to our "source" parameter; we can either opt for early (harmless) return
# ... or raise our own exception.
# Early returns are sometimes a reasonable exception to the
selection = random.choice(source)
if selection not in target:
raise RuntimeError('The impossible has occurred?')
## Previous is just for pedagogical purposes!
if target[selection] == 1:
# An example of dynamically testing the value count associated with your selection
results = 'Only found exactly one %s in %s' % (selection, source)
source.remove(selection)
else:
results = selection
target[selection] += 1
return results
if __name__ == '__main__':
print(main(list2)) # Invoking such that it uses the default for "target"
@JimDennis
Copy link
Author

In response to:

https://plus.google.com/u/0/107541430877608655699/posts/DsJiLgjMZYn

... some very rudimentary suggestions on Python coding.

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