import os
def to_unicode(unicode_or_str):
if isinstance(unicode_or_str, str):
value = unicode_or_str.decode("utf-8")
else:
value = unicode_or_str
return value
def to_str(unicode_or_str):
if isinstance(unicode_or_str, unicode):
value = unicode_or_str.encode("utf-8")
else:
value = unicode_or_str
return value
with open("random.bin", "w") as f:
f.write(os.urandom(10))
def get_first_int(values, key, default=0):
found = values.get(key, [""])
if found[0]:
found = int(found[0])
else:
found = default
return found
a = [1,2,3]
b = a[:]
assert b == a and b is not a
b = a
print "Before {}".format(a)
a[:] = [101, 102, 103]
assert a is b
print "After {}".format(a)
a = ["red", "orange", "yellow", "green", "blue", "purple"]
odds = a[::2]
evens = a[1::2]
print odds
print evens
x = "mongoose"
y = x[::-1]
print y
w = u"谢谢"
x = w.encode("utf-8")
y = x[::-1]
a = ["a", "b", "c", "d", "e", "f", "g", "h"]
b = a[::2]
c = b[1:-1]
print c
a = [1,2,3,4,5,6,7,8,9,10]
squares = [x**2 for x in a]
print squares
squares = map(lambda x: x**2, a)
even_squares = [x**2 for x in a if x % 2 == 0]
print even_squares
alt = map(lambda x: x**2, filter(lambda x: x % 2 == 0, a))
assert even_squares == list(alt)
chile_ranks = {
"ghost": 1, "habanero": 2, "cayenne": 3}
rank_dict = {
rank: name for name, rank in chile_ranks.iteritems()}
print rank_dict
chile_len_set = {
len(name) for name in rank_dict.itervalues()}
print chile_len_set
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [x for row in matrix for x in row]
print flat
squared = [[x**2 for x in row] for row in matrix]
print squared
a = [1,2,3,4,5,6,7,8,9,10]
b = [x for x in a if x > 4 if x % 2 == 0]
c = [x for x in a if x > 4 and x % 2 == 0]
print b
assert b == c
matrix = [[1,2,3],[4,5,6],[7,8,9]]
filtered = [[x for x in row if x % 3 == 0]
for row in matrix if sum(row) >= 10]
print filtered
value = [len(x) for x in open("hello.txt")]
print value
it = (len(x) for x in open("hello.txt"))
print it
print next(it)
print next(it)
roots = ((x, x**0.5) for x in it)
print next(roots)
fruit_list = ["apple", "banana", "orange"]
for i, fruit in enumerate(fruit_list):
print "%d: %s" % (i+1, fruit)
names = ["Lebron", "Bryant", "Wade", "HongfeiXu"]
letters = [len(n) for n in names]
longest_name = None
max_letters = 0
for i in range(len(names)):
count = letters[i]
if count > max_letters:
longest_name = names[i]
max_letters = count
print longest_name
longest_name = None
max_letters = 0
for name, count in zip(names, letters):
if count > max_letters:
longest_name = name
max_letters = count
print longest_name
a = 4
b = 9
for i in range(2, min(a, b) + 1):
print "Testing %d" % i
if a % 2 == 0 and b % i == 0:
print "Not coprime"
break
else:
print "Coprime"
def coprime(a, b):
for i in range(2, min(a, b) + 1):
if a % 2 == 0 and b % i == 0:
return False
return True
handle = open("hello.txt")
try:
data = handle.read()
finally:
handle.close()
import json
def load_json_key(data, key):
try:
result_dict = json.loads(data)
except ValueError as e:
raise KeyError(e)
else:
return result_dict[key]
UNDEFINE = object()
def divide_json(path):
handle = open(path, "r+")
try:
data = handle.read()
op = json.loads(data)
value = (
op["numerator"]/
op["denominator"])
except ZeroDivisionError as e:
return UNDEFINE
else:
op["result"] = value
result = json.dumps(op)
handle.seek(0)
handle.write(result)
return value
finally:
handle.close()