>>> from timeit import timeit
>>> def f1(s1='foo', s2='bar'):
return ' - '.join((s1, s2))
>>> f1()
'foo - bar'
>>> def f2(s1='foo', s2='bar'):
return '{0} - {1}'.format(s1, s2)
>>> f2()
'foo - bar'
>>> def f3(s1='foo', s2='bar'):
return '%s - %s' % (s1, s2)
>>> f3()
'foo - bar'
>>> timeit(f1)
0.7238124336211288
>>> timeit(f2)
1.3038862714413124
>>> timeit(f3)
0.8215918286469828
>>> def namedtuplex(*args, **kwargs):
def getitem(self, key):
if type(key) is str:
value = getattr(self, key)
else:
value = tuple.__getitem__(self, key)
if type(value) is str:
value = value.strip('"')
try:
value = eval(value)
except:
value = intern(value)
return value
ntuple = collections.namedtuple(*args, **kwargs)
ntuple.__getitem__ = getitem
return ntuple
>>> XDR = namedtuplex('XDR', 'a b c d e f g')
>>> xdr = XDR('"abc"', 'def', '5', '"3.14"', 2.71, [1,2], None)
>>> xdr.a
'abc'
>>> xdr.b
'def'
>>> xdr.c
5
>>> xdr.d
3.14
>>> xdr.e
2.71
>>> xdr.f
[1, 2]
>>> xdr.g
>>> xdr['a']
'abc'
>>> xdr['b']
'def'
>>> xdr['c']
5
>>> xdr['d']
3.14
>>> xdr['e']
2.71
>>> xdr['f']
[1, 2]
>>> xdr['g']
>>>
В зависимость от конкретного применения можно сделать что-то такое:eval(value.strip('"'))
xcache = dict()
while cache:
key, val = cache.iteritems().next()
xcache[cache.pop(key)] = key
Такой способ в 3 раза величивает время исполнения скрипта (с 60 до 180 секунд на моём ноутбуке) по сравнению с традиционным методом инвертирования "в лоб". Есть ли способ лучше?xcache = dict()
cpop = cache.pop
while cache:
key = cache.iterkeys().next()
xcache[cpop(key)] = key
del cache
xcache = dict()
cpop = cache.popitem
while cache:
key, val = cpop()
xcache[val] = key
del cache
from collections import Counter
def min_unique(dictionary):
minval, result = float('inf'), None
counter = Counter(dictionary.itervalues())
for key, val in dictionary.iteritems():
if (val < minval) and (counter[val] == 1):
minval = val
result = (key, val)
return result
data = {'a': 23, 'b': 26, 'c': 45, 'd': 23}
print min_unique(data)
from operator import itemgetter
from itertools import ifilter
def min_unique(dictionary):
inverted = dict()
for key, value in dictionary.iteritems():
inverted[value] = None if value in inverted else key
filtered = ifilter(itemgetter(1), inverted.iteritems())
try:
value, key = min(filtered, key=itemgetter(0))
except ValueError:
value, key = None, None
return key, value
from operator import itemgetter
from itertools import groupby
def min_unique(dictionary, ig=itemgetter(1)):
grouped = groupby(sorted(dictionary.viewitems(), key=ig), key=ig)
for key, entries in grouped:
entry = entries.next()
try:
entries.next()
except StopIteration:
return entry
else:
continue
from collections import Counter
from itertools import ifilter
def criteria(dictword):
return (
wlen == len(dictword) and
wset == set(dictword) and
wcnt == Counter(dictword)
)
while True:
word = raw_input('\nEnter word: ')
wlen, wset, wcnt = len(word), set(word), Counter(word)
with open('thesaurus.txt') as f:
thesaurus = (line.rstrip() for line in f)
for dictword in ifilter(criteria, thesaurus):
print dictword
if word in {'exit', 'quit'}:
break
>>> from math import sqrt
>>> def solver():
try:
a, b, c = map(float, raw_input('Введите a, b, c через пробел: ').split())
except:
print 'На колу мочало - начинай сначала!'
else:
d = b*b - 4*a*c
if d >= 0:
sd = sqrt(d)
root = lambda k: '{:.6f}'.format((-b+k*sd)/(2*a))
solution = ' и '.join(set(map(root, (-1,1))))
else:
solution = 'уравнение не имеет решений'
print 'Ответ: %s' % solution
>>> solver()
Введите a, b, c через пробел: 1, 2 3
На колу мочало - начинай сначала!
>>> solver()
Введите a, b, c через пробел: 1 2 3
Ответ: уравнение не имеет решений
>>> solver()
Введите a, b, c через пробел: 4 9 1
Ответ: -0.117218 и -2.132782
>>>
>>> print 'Result: %s' % input('Expression: ')
Expression: 2+3
Result: 5
>>> print 'Result: %s' % input('Expression: ')
Expression: 1/0
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print 'Result: %s' % input('Expression: ')
File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> import os
>>> input()
os.remove('z:\\test.txt')
>>>
>>> import re
>>> url = 'http://www.mail.ru/index.html'
>>> parser = re.compile('^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$')
>>> parser.findall(url)
[('http://', 'www.mail', 'ru', '')]
dlist = [('www.ya.ru', {1,2,3}), ('ya.ru', {4,5}), ('xxx.x', {6,7,8,9})]
from collections import defaultdict
buffer = defaultdict(set)
for domain, stuff in dlist:
buffer[domain.lstrip('www.')].update(stuff)
print buffer.items()
from collections import OrderedDict
buffer = OrderedDict()
for domain, stuff in dlist:
if domain.startswith('www.'):
domain = domain[4:]
buffer.setdefault(domain, set()).update(stuff)
print buffer.items()
buffer = defaultdict(set)
map(lambda (domain, stuff): buffer[domain.lstrip('www.')].update(stuff), dlist)
print buffer.items()
reduce(
lambda buffer, (domain, stuff): buffer[domain.lstrip('www.')].update(stuff) or buffer,
dlist,
defaultdict(set)
).items()
>>> items = [ 'photo_2560', 'photo_1280', 'width', 'album_id', 'post_id', 'date', 'owner_id', 'photo_807', 'photo_604', 'id', 'photo_130', 'text']
>>> max((item for item in items if item.startswith('photo_')), key=lambda x: int(x[6:]))
'photo_2560'
>>> s = 'abc<def*gh?ikl'
>>> s.translate(None, '\/:*?"<>|')
'abcdefghikl'