def gcd(a,b): while b != 0: a, b = b, a%b return a tests = [(216,846), (1071,462), (1024,768)] for a, b in tests: print("The gcd of {} and {} is {}.".format(a, b, gcd(a,b)))
The gcd of 216 and 846 is 18. The gcd of 1071 and 462 is 21. The gcd of 1024 and 768 is 256.
if 1 and True: print("1 and True is True") if not(0 or False): print("0 or False is False")
1 and True is True 0 or False is False
def outer(v1, v2): # defining a nested function def inner(iv1, iv2): print("Outer v1={}, Outer v2={}".format(v1, v2)) print("Outer iv1={}, Outer iv2={}".format(iv1, iv2)) inner(3,4) outer(1,2)
Outer v1=1, Outer v2=2 Outer iv1=3, Outer iv2=4
lorem_text = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed iaculis sapien, vitae vestibulum nunc. Vivamus pharetra risus neque, ut iaculis elit porta non. Vivamus ullamcorper dolor sit amet sollicitudin vehicula. Aliquam quis tristique nibh, eget malesuada purus. Proin varius sollicitudin turpis, fermentum mollis elit cursus vel. Suspendisse vehicula enim ac magna consequat ultricies. Pellentesque in leo et nulla porta faucibus. Quisque tincidunt in erat ut commodo. Quisque id augue a nisl mollis pulvinar id at nulla. Morbi a augue erat. Sed pharetra molestie mauris nec ultricies. Pellentesque efficitur blandit mauris, sed vulputate ante bibendum eu. Nulla facilisi. Sed porta massa eu ligula tristique, nec hendrerit elit euismod. Phasellus luctus placerat facilisis. """ for t in lorem_text.split(): print t
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed iaculis sapien, vitae vestibulum nunc. Vivamus pharetra risus neque, ut iaculis elit porta non. Vivamus ullamcorper dolor sit amet sollicitudin vehicula. Aliquam quis tristique nibh, eget malesuada purus. Proin varius sollicitudin turpis, fermentum mollis elit cursus vel. Suspendisse vehicula enim ac magna consequat ultricies. Pellentesque in leo et nulla porta faucibus. Quisque tincidunt in erat ut commodo. Quisque id augue a nisl mollis pulvinar id at nulla. Morbi a augue erat. Sed pharetra molestie mauris nec ultricies. Pellentesque efficitur blandit mauris, sed vulputate ante bibendum eu. Nulla facilisi. Sed porta massa eu ligula tristique, nec hendrerit elit euismod. Phasellus luctus placerat facilisis.
for w in lorem_text.split(): if w[-1] in [',', "."]: print w[:-1] else: print w
Lorem ipsum dolor sit amet consectetur adipiscing elit In sed iaculis sapien vitae vestibulum nunc Vivamus pharetra risus neque ut iaculis elit porta non Vivamus ullamcorper dolor sit amet sollicitudin vehicula Aliquam quis tristique nibh eget malesuada purus Proin varius sollicitudin turpis fermentum mollis elit cursus vel Suspendisse vehicula enim ac magna consequat ultricies Pellentesque in leo et nulla porta faucibus Quisque tincidunt in erat ut commodo Quisque id augue a nisl mollis pulvinar id at nulla Morbi a augue erat Sed pharetra molestie mauris nec ultricies Pellentesque efficitur blandit mauris sed vulputate ante bibendum eu Nulla facilisi Sed porta massa eu ligula tristique nec hendrerit elit euismod Phasellus luctus placerat facilisis
for w in lorem_text.split()[:5]: if w[-1] in [',', "."]: print w[:-1].lower() else: print w.lower()
lorem ipsum dolor sit amet
for w in reversed(lorem_text.split()[:5]): print w
amet, sit dolor ipsum Lorem
e_word_count = 0 for w in lorem_text.split(): if 'e' in w: e_word_count += 1 print e_word_count
55
def lorem_clean_sample(start, end): sample = [] for w in lorem_text.split()[start:end]: if w[-1] in [',', "."]: sample.append(w[:-1].lower()) else: sample.append(w.lower()) return sample
# dictionaries / maps d = {"a": 1} # tuples (immutable "lists") tup = ("b", 2) # lists [1, 2, 3] lis = ["c", 1]
list(tup)
['b', 2]
tuple(lis)
('c', 1)
dict([tuple(lis)])
{'c': 1}
dict([tup])
{'b': 2}
dict.fromkeys(["a", "b", "c"])
{'a': None, 'b': None, 'c': None}
dict.fromkeys(("a", "b", "c"))
{'a': None, 'b': None, 'c': None}
d = dict.fromkeys(["a", "b", "c"]) d
{'a': None, 'b': None, 'c': None}
d.update(dict([tuple(lis)]))
d
{'a': None, 'b': None, 'c': 1}
d.update(dict([('a',1), tuple(lis), tup]))
d
{'a': 1, 'b': 2, 'c': 1}
# list comprehensions [i for i in xrange(1,16)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[i for i in xrange(1,16) if i%2] # say what???
[1, 3, 5, 7, 9, 11, 13, 15]
[i for i in xrange(1,16) if not i%2] # aha!!!
[2, 4, 6, 8, 10, 12, 14]
# dictionary comprehensions lorem_wlen = {key: len(key) for key in lorem_clean_sample(0, 10)} lorem_wlen
{'adipiscing': 10, 'amet': 4, 'consectetur': 11, 'dolor': 5, 'elit': 4, 'in': 2, 'ipsum': 5, 'lorem': 5, 'sed': 3, 'sit': 3}
lorem_cnt_e = {key: key.count("e") for key in lorem_clean_sample(0, 10)} lorem_cnt_e
{'adipiscing': 0, 'amet': 1, 'consectetur': 2, 'dolor': 0, 'elit': 1, 'in': 0, 'ipsum': 0, 'lorem': 1, 'sed': 1, 'sit': 0}
import requests r = requests.get("http://www2.ed.gov/data.json") if r.status_code == 200: payload_dict = r.json() # loading the data into a dict via the json() just works! else: print "Could not load the data at this endpoint."
payload_dict.keys()
[u'conformsTo', u'dataset', u'describedBy', u'@context', u'@id', u'@type']
arra_data = {} for dataset in payload_dict['dataset']: if "ARRA" in dataset['description']: dsid = dataset['identifier'] desc = dataset['description'] title = dataset['title'] arra_data[dsid] = {'description': desc, 'title': title}
arra_data
{u'ED-2485': {'description': u'The Investing in Innovation (i3) Fund website depicts and allows downloading of general information on the i3 applicants received, grantees awarded and project locations. The Investing in Innovation Fund, established under section 14007 of the American Recovery and Reinvestment Act of 2009 (ARRA), provides funding to support (1) local educational agencies (LEAs), and (2) nonprofit organizations in partnership with (a) one or more LEAs or (b) a consortium of schools. The purpose of the i3 program is to provide competitive grants to applicants with a record of improving student achievement and attainment in order to expand the implementation of, and investment in, innovative practices that are demonstrated to have an impact on improving student achievement or student growth, closing achievement gaps, decreasing dropout rates, increasing high school graduation rates, or increasing college enrollment and completion rates. These grants will (1) allow eligible entities to expand and develop innovative practices that can serve as models of best practices, (2) allow eligible entities to work in partnership with the private sector and the philanthropic community, and (3) identify and document best practices that can be shared and taken to scale based on demonstrated success.', 'title': u'ED Grants: Investing in Innovation (i3) Fund 2010'}, u'ED-5562': {'description': u'The Investing in Innovation (i3) Fund website depicts and allows downloading of general information on the i3 applicants received, grantees awarded and project locations. The Investing in Innovation Fund, established under section 14007 of the American Recovery and Reinvestment Act of 2009 (ARRA), provides funding to support (1) local educational agencies (LEAs), and (2) nonprofit organizations in partnership with (a) one or more LEAs or (b) a consortium of schools. The purpose of the i3 program is to provide competitive grants to applicants with a record of improving student achievement and attainment in order to expand the implementation of, and investment in, innovative practices that are demonstrated to have an impact on improving student achievement or student growth, closing achievement gaps, decreasing dropout rates, increasing high school graduation rates, or increasing college enrollment and completion rates. These grants will (1) allow eligible entities to expand and develop innovative practices that can serve as models of best practices, (2) allow eligible entities to work in partnership with the private sector and the philanthropic community, and (3) identify and document best practices that can be shared and taken to scale based on demonstrated success.', 'title': u'ED Grants: Investing in Innovation (i3) Fund 2011'}}
arra_data_dc = { dataset['identifier'] : {'description': dataset['description'], 'title': dataset['title']} for dataset in payload_dict['dataset'] if "ARRA" in dataset['description'] }
arra_data_dc
{u'ED-2485': {'description': u'The Investing in Innovation (i3) Fund website depicts and allows downloading of general information on the i3 applicants received, grantees awarded and project locations. The Investing in Innovation Fund, established under section 14007 of the American Recovery and Reinvestment Act of 2009 (ARRA), provides funding to support (1) local educational agencies (LEAs), and (2) nonprofit organizations in partnership with (a) one or more LEAs or (b) a consortium of schools. The purpose of the i3 program is to provide competitive grants to applicants with a record of improving student achievement and attainment in order to expand the implementation of, and investment in, innovative practices that are demonstrated to have an impact on improving student achievement or student growth, closing achievement gaps, decreasing dropout rates, increasing high school graduation rates, or increasing college enrollment and completion rates. These grants will (1) allow eligible entities to expand and develop innovative practices that can serve as models of best practices, (2) allow eligible entities to work in partnership with the private sector and the philanthropic community, and (3) identify and document best practices that can be shared and taken to scale based on demonstrated success.', 'title': u'ED Grants: Investing in Innovation (i3) Fund 2010'}, u'ED-5562': {'description': u'The Investing in Innovation (i3) Fund website depicts and allows downloading of general information on the i3 applicants received, grantees awarded and project locations. The Investing in Innovation Fund, established under section 14007 of the American Recovery and Reinvestment Act of 2009 (ARRA), provides funding to support (1) local educational agencies (LEAs), and (2) nonprofit organizations in partnership with (a) one or more LEAs or (b) a consortium of schools. The purpose of the i3 program is to provide competitive grants to applicants with a record of improving student achievement and attainment in order to expand the implementation of, and investment in, innovative practices that are demonstrated to have an impact on improving student achievement or student growth, closing achievement gaps, decreasing dropout rates, increasing high school graduation rates, or increasing college enrollment and completion rates. These grants will (1) allow eligible entities to expand and develop innovative practices that can serve as models of best practices, (2) allow eligible entities to work in partnership with the private sector and the philanthropic community, and (3) identify and document best practices that can be shared and taken to scale based on demonstrated success.', 'title': u'ED Grants: Investing in Innovation (i3) Fund 2011'}}
import csv with open("Export.csv") as fi: csv_fi = csv.DictReader(fi) for row in csv_fi: print row['MarketName'], row['x'], row['y'] break
Caledonia Farmers Market Association - Danville -72.140305 44.411013
map_data_objects = {} with open("Export.csv") as fi: csv_fi = csv.DictReader(fi) for row in csv_fi: try: map_data_objects[row['FMID']] = (row['MarketName'], float(row['x'].strip()), float(row['y'].strip())) except ValueError: print("Count not convert row for FMID: {}".format(row['FMID']))
Count not convert row for FMID: 2000001 Count not convert row for FMID: 1011689 Count not convert row for FMID: 2000002 Count not convert row for FMID: 1002854 Count not convert row for FMID: 2000004 Count not convert row for FMID: 2000005 Count not convert row for FMID: 2000006 Count not convert row for FMID: 2000007 Count not convert row for FMID: 2000008 Count not convert row for FMID: 2000009 Count not convert row for FMID: 2000010 Count not convert row for FMID: 2000011 Count not convert row for FMID: 2000012 Count not convert row for FMID: 2000013 Count not convert row for FMID: 2000014 Count not convert row for FMID: 2000016 Count not convert row for FMID: 2000017 Count not convert row for FMID: 2000019 Count not convert row for FMID: 2000020 Count not convert row for FMID: 2000021 Count not convert row for FMID: 2000022 Count not convert row for FMID: 2000026 Count not convert row for FMID: 2000028 Count not convert row for FMID: 2000030 Count not convert row for FMID: 2000032 Count not convert row for FMID: 2000033 Count not convert row for FMID: 2000034 Count not convert row for FMID: 2000035 Count not convert row for FMID: 2000036
import folium us_fm_map = folium.Map(location=[39.232253, -97.910156], zoom_start=4, tiles='Stamen Terrain') for fmid, v in map_data_objects.iteritems(): name, lon, lat = v if (lon < -104 and lon > -106) \ and \ (lat < 43 and lat > 30): folium.Marker([lat, lon], popup=unicode(name.decode('utf-8')) ).add_to(us_fm_map)
us_fm_map