Skip to content

Instantly share code, notes, and snippets.

@billmei
Created June 7, 2017 04:22
Show Gist options
  • Save billmei/37eb3abd893618b250ddf7b39920d19f to your computer and use it in GitHub Desktop.
Save billmei/37eb3abd893618b250ddf7b39920d19f to your computer and use it in GitHub Desktop.
Playing around with Intermediate Python
#!/usr/bin/env python3
"""
Playing around with Intermediate Python
http://book.pythontips.com/en/latest/index.html
"""
def multiple_params(f_arg, *args):
"""Unpacking an *args"""
print('First argument:', f_arg)
for arg in args:
print('Another arg from *args:', arg)
def greet(**kwargs):
"""Unpacking a **kwargs"""
if kwargs is not None:
for key, value in kwargs.iteritems():
print('{key} : {value}'.format(key=key, value=value))
def fibonacci(n):
latest = 1
second = 0
for i in range(n):
yield latest
latest, second = latest + second, latest
def main():
"""Run everything"""
multiple_params('foo', 'bar', 'baz', 'quux')
multiple_params(*[1, 2, 3, 4])
greet(name="John Smith", occupation="Accountant")
greet(**{'name' : 'Bob Smith'})
for i in fibonacci(10):
print(i)
gen = fibonacci(3)
try:
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
except StopIteration:
print("Iteration stopped.")
str_iter = iter('foo')
try:
print(next(str_iter))
print(next(str_iter))
print(next(str_iter))
print(next(str_iter))
except StopIteration:
print("Iteration stopped.")
# Find duplicates in a list
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = set([x for x in some_list if some_list.count(x) > 1])
print(duplicates)
# Output: set(['b', 'n'])
set_a = set(['yellow', 'red', 'blue', 'green', 'black'])
set_b = set(['red', 'brown'])
# Intersect two sets
print(set_b.intersection(set_a))
# Output: set(['red'])
# Difference two sets
print(set_b.difference(set_a))
# Output: set(['brown'])
print(set_a.difference(set_b))
# Output: set(['blue', 'green', 'black', 'yellow'])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment