>>> 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'
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from itertools import product
def process(existing, required):
for opcount in xrange(existing+required):
for combo in product('dcv', repeat=opcount):
buffer = 0
smiles = existing
data_y = [existing]
for char in combo:
if char == 'd':
smiles -= 1
elif char == 'v':
smiles += buffer
else:
buffer = smiles
data_y.append(smiles)
if smiles == required:
data_x = xrange(opcount+1)
plt.plot(data_x, data_y, linewidth=1)
print required, data_y
return ''.join(combo)
return '-'
for required in xrange(2, 101):
plt.clf()
plt.grid(True)
plt.title('Target: %s' % required)
plt.autoscale(enable=True, axis='both', tight=False)
for existing in xrange(1, (required//2)+1):
result = process(existing, required)
plt.savefig('{:02d}.png'.format(required), dpi=96, bbox_inches='tight')
# -*- coding: utf-8 -*-
from itertools import starmap, imap
from math import sqrt
options = {str(index):option for (index, option) in enumerate('Cathetus|Hypotenuse'.split('|'), 1)}
if __name__ == '__main__':
while True:
try:
menu = '\n'.join(
starmap('-'.join(chr(0x20)*2).join(['{}']*2).format, options.items())
)
choice = raw_input('\nCalculate:\n%s\n\nYour choice: ' % menu)
side = options[choice]
sign = -1 if int(choice) == 1 else 1
print
query = lambda index: raw_input('Enter side #%s: = ' % index)
sides = sorted(float(x) for x in imap(query, options))
assert 0 < sides[0] <= sides[1], '\nERROR: Length must be a positive number!'
result = sqrt(pow(sides[-1], 2) + sign*(min(sides)**2))
except KeyError:
print '\nERROR: No such option!'
except ValueError:
print '\nERROR: Length must be a number!'
except AssertionError, error_text:
print error_text
else:
print '\nResult: {:.2f}'.format(result)
exit(0)
>>> a
["['9', '8', '7', '4']", "['9', '8', '7', '5']", "['9', '8', '7', '6']"]
>>> map(int, map(''.join, map(eval, a)))
[9874, 9875, 9876]
>>> reduce(lambda item, func: map(func, item), (eval, ''.join, int), a)
[9874, 9875, 9876]
>>> eval(','.join(a).translate(None,",' ").replace('][',','))
[9874, 9875, 9876]
>>> from itertools import starmap
>>> map(int, starmap(('{}'*4).format, map(eval, a)))
[9874, 9875, 9876]
>>> import re
>>> eval(re.sub("', '|['\[\]]", '', ','.join(a)))
(9874, 9875, 9876)
>>> map(lambda x: int(re.sub('[^\d]', '', x)), a)
[9874, 9875, 9876]
>>> repl = partial(re.sub, '[^\d]', '')
>>> map(lambda x: int(repl(x)), a)
[9874, 9875, 9876]
>>> reduce(lambda item, func: map(func, item), (repl, int), a)
[9874, 9875, 9876]
>>> reduce(lambda *args: map(*args[::-1]), (repl, int), a)
[9874, 9875, 9876]
>>> reduce(lambda *args: map(*args[::-1]), (eval, ''.join, int), a)
[9874, 9875, 9876]
>>> func = lambda item: int(''.join(char for char in item if char in digits))
>>> map(func, a)
[9874, 9875, 9876]
>>> from textwrap import wrap
>>> map(int, wrap(re.sub('[^\d]', '', str(a)), 4))
[9874, 9875, 9876]
>>> d = set(digits)
>>> fltr = partial(filter, d.issuperset)
>>> map(int, map(fltr, a))
[9874, 9875, 9876]
>>> map(int, re.findall('\d{4}', re.sub('[^\d]', '', str(a))))
[9874, 9875, 9876]
def find_word(line):
for step in xrange(1, len(line)):
for start in xrange(step):
if len(set(line[(start or None)::step])) != 1:
break
else:
return line[:step]
return line
print find_word('HELLOHELLOHELLOHEL')
print find_word('HHHELLOHHHELLOHHHELLOHHH')
print find_word('_HHELLOHHELLOHHELLOHHELLOHHELLOHHE')
HELLO
HHHELLO
_HHELLOHHELLOHHELLOHHELLOHHELLOHHE
data = '[{0}000,{1},{2}],'.format(str(r[i])[:-2], e[i], c[i])
f.write(data)
>>> x = None
>>> x or 0
0
from itertools import izip
...
data = izip(r, e, c)
for trio in data:
if all(trio):
entry = '[{:.0f}000,{},{}],'.format(*trio)
f.write(entry)
from itertools import izip, ifilter
...
for triplet in ifilter(all, izip(r, e, c)):
entry = '[{:.0f}000,{},{}],'.format(*triplet)
f.write(entry)
# -*- coding: utf-8 -*-
from difflib import SequenceMatcher
from itertools import combinations, imap
def ratio(pair):
return (SequenceMatcher(None, *pair).ratio(), pair[0])
def findword(wordlist):
pairs = combinations(wordlist, 2)
found = max(imap(ratio, pairs))[1]
return found
print findword(['голубец', 'конь', 'голубцы', 'лист'])
print findword(['стол', 'день', 'свет', 'клинок', 'светильник'])
print findword(['восток', 'дань', 'исток', 'жир', 'голубь', 'да'])
голубец
свет
восток
def tree(levels=0, func=None):
if levels > 0 and func:
return defaultdict(reduce(lambda f, i: lambda: defaultdict(f), xrange(levels-1), func))
else:
return defaultdict(tree)
>>> d = tree()
>>> d[1][2][3][4][5] = 6
>>> d = tree(3, float)
>>> d
defaultdict(<function <lambda> at 0x0280E3F0>, {})
>>> d[1][2][3]
0.0
>>> d[7][8][9] += 10
>>> d[7][8][9]
10.0
def tree(func=lambda: tree(), depth=0):
return defaultdict(reduce(lambda f, i: lambda: defaultdict(f), xrange(depth-1), func))
p = re.compile(ur"^(?P<name>.+?)[ ]*-[ ]*(?P<value>\d+?)$", flags=re.M|re.U)
# -*- coding: utf-8 -*-
import re
text = u"""Вася - 10
Ваня - 20
Петя - 30"""
d = dict(re.findall(u"^(.+?) - (\d+?)$", text, flags=re.M|re.U))
print d
p = re.compile(u"^(?P<name>.+?) - (?P<value>\d+?)$", flags=re.M|re.U)
d = [match.groupdict() for match in p.finditer(text)]
print text
print text.encode('utf-8')
if querry:
dataset = querry.split()
if len(dataset) >= 5:
with sqlite3.connect('aybremote') as connection:
cursor = connection.cursor()
cursor.execute('INSERT INTO main VALUES(?,?,?,?,?)', dataset[0:5])
connection.commit()