Last active
May 13, 2017 10:20
-
-
Save sidharthshah/5610e43797fe49b50359208c09e2d6d0 to your computer and use it in GitHub Desktop.
Sample Python Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is Readable | |
>>> nums = [] | |
>>> for i in range(1000): | |
... nums.append(random.randint(1, 1000)) | |
... | |
# This is not readable | |
num_1 = [random.randint(1, 1000) for i in range(1000)] | |
# Traditional way of doing things | |
counts = {} | |
for i in num: | |
if i not in counts: | |
counts[i] = 0 | |
counts[i] += 1 | |
# A little faster ways of doing things | |
counts = defaultdict(int) | |
for i in num: | |
counts[i] += 1 | |
# Interating over dictionary | |
# One Way | |
for key, count in counts.items(): | |
if count > 1: | |
print key, count | |
# Another Way | |
for current in names: | |
print current, "->", names[current] | |
# Code Sample to Count Articles by Source | |
import json | |
from collections import defaultdict | |
data = json.loads(open("data.json")) | |
counts_by_source = defaultdict(int) | |
for doc in data['response']['docs']: | |
counts_by_source[doc['source']] += 1 | |
for store, count in counts_by_source.item(): | |
print store, count | |
# Version with Reverse Sorting | |
import json | |
import operator | |
from collections import defaultdict | |
data = json.loads(open("data.json").read()) | |
counts_by_source = defaultdict(int) | |
for current_article in data['response']['docs']: | |
counts_by_source[current_article['source']] += 1 | |
for source, count in counts_by_source.items(): | |
print source, count | |
print "\n\nSorted\n\n" | |
counts_by_source_sorted = sorted( | |
counts_by_source.items(), | |
key=operator.itemgetter(1), | |
reverse=True) | |
for source, count in counts_by_source_sorted: | |
print source, count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment