def checksum(code, awards={'A': 15, 'B': 20, 'C': 30, '': 40}, joker='D'):
return sum(
awards.get(''.join(set(triplet)-{joker}), 0) for triplet in zip(*[iter(code)]*3)
)
checksum('ABCAABDCA') # 0
checksum('ADAAABDCA') # 15
def checksum2(code, awards={'A': 15, 'B': 20, 'C': 30, '': 40}, joker='D'):
return reduce(
lambda xsum, triplet: xsum + awards.get(
''.join(set(triplet).difference(joker)), 0
),
(code[0:3], code[3:6], code[6:9]), 0
)
html = urllib.request.urlopen(url).read().decode('utf-8').encode('cp1251')
audio = (
{'lyrics_id': 3586866, 'title': 'Fruhling in Paris', 'id': 358450897, 'artist': 'Rammstein', 'owner_id': 358450897},
{'lyrics_id': 3655472, 'title': 'Zwitter', 'id': 358450894, 'artist': 'Rammstein', 'owner_id': 358450897},
)
keys_to_delete = {'owner_id', 'duration', 'url', 'lyrics_id', 'album_id', 'genre_id'}
for track in audio:
for attribute in keys_to_delete:
try:
del track[attribute]
except KeyError:
pass
>>> def foo(**kwargs):
kwargs['id'] = 1
print 'Internal: %s' % kwargs['id']
>>> d = {'id': 0}
>>> foo(**d)
Internal: 1
>>> d
{'id': 0}
>>> def foo(**kwargs):
kwargs['id'][:] = [4, 5, 6]
print 'Internal: %s' % kwargs['id']
>>> d = {'id': [1, 2, 3]}
>>> foo(**d)
Internal: [4, 5, 6]
>>> d
{'id': [4, 5, 6]}
from random import random
while True:
try:
total = int(raw_input('\nВведите количество бросков: '))
except ValueError:
print 'Введено некорректное значение: ожидается целое число.'
else:
# side1 = sum(random() < 0.5 for n in xrange(total))
side1 = int(round(sum(random() for n in xrange(total)))) # эквивалент random() >= 0.5
side2 = max(0, total) - side1
print 'Результат: орёл - {0}, решка - {1}'.format(side1, side2)
finally:
if raw_input('\nПопробовать ещё раз (Y)? ').upper() != 'Y':
break
import collections, random
options = ('орёл', 'решка')
while True:
stats = collections.Counter(dict.fromkeys(options, 0))
try:
stats.update(
random.choice(options) for test in xrange(
input('\nВведите количество бросков: ')
)
)
except:
print 'Введено некорректное значение: ожидается целое число.'
else:
print 'Результат: {0} - {{{0}}}, {1} - {{{1}}}'.format(*options).format(**stats)
finally:
if raw_input('\nПопробовать ещё раз (Y)? ').upper() != 'Y':
break
>>> timeit('choice((0,1))', setup='from random import random, choice', number=10**6)
1.4363103769230747
>>> timeit('random() < 0.5', setup='from random import random, choice', number=10**6)
0.18878976080804932
>>> exec('xyz="xyz"')
>>> xyz
'xyz'
>>> exec('{s}="{s}"'.format(s='xyz'))
>>> xyz
'xyz'
>>> 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