from dataclasses import dataclass
from itertools import chain
from itertools import filterfalse
from itertools import product
from typing import List
@dataclass
class Obj:
p1: str
p2: str
p1_odds: float
p2_odds: float
is_found: bool = False
external_id: int = -1
API_RESPONSE = {
'sportId': 123,
'last': 216699817,
'league': [
{
'id': 3742,
'name': 'WTA French Open - R3',
'events': [
{
'id': 9999999999999,
'starts': '2019-05-31T11:30:00Z',
'home': 'Sloane Stephens',
'away': 'Polona Hercog',
'rotNum': '8705',
'liveStatus': 0,
'status': 'I',
'parlayRestriction': 2,
'parentId': 994897148,
'altTeaser': False,
'resultingUnit': 'Sets'
},
{
'id': 994906276,
'starts': '2019-05-31T11:30:00Z',
'home': 'Veronika Kudermetova (+1.5 Sets)',
'away': 'Kaia Kanepi (-1.5 Sets)',
'rotNum': '8705',
'liveStatus': 0,
'status': 'I',
'parlayRestriction': 2,
'parentId': 994897148,
'altTeaser': False,
'resultingUnit': 'Sets'
}
]
},
{
'id': 3735,
'name': 'WTA French Open - Doubles',
'events': [
{
'id': 994977085,
'starts': '2019-05-31T11:30:00Z',
'home': 'L Hradecka / A Klepac',
'away': 'S Kenin / A Petkovic',
'rotNum': '15571',
'liveStatus': 0,
'status': 'O',
'parlayRestriction': 2,
'altTeaser': False,
'resultingUnit': 'Regular'
},
{
'id': 995164497,
'starts': '2019-05-31T12:45:00Z',
'home': 'M Puig / S Rogers',
'away': 'S Hsieh / B Strycova',
'rotNum': '15575',
'liveStatus': 0,
'status': 'I',
'parlayRestriction': 2,
'altTeaser': False,
'resultingUnit': 'Regular'
}
]
}
]
}
def find_matching(container: List[Obj], api_response: dict) -> List[Obj]:
events = (
tuple(
(e.get('id', 0), e.get('home', '')) for e in
chain.from_iterable(
filter(None, (event.get('events', []) for event
in api_response.get('league', [])))
)
)
)
result = []
filtered = filterfalse(lambda x: x[0].p1 != x[1][1], product(container, events))
for obj, item in filtered:
obj.external_id = item[0]
obj.is_found = True
result.append(obj)
return result
if __name__ == '__main__':
data = [
Obj(
p1='Sloane Stephens',
p2='Polona Hercog',
p1_odds=1.2,
p2_odds=3.8,
),
Obj(
p1='Belinda Bencic',
p2='Donna Vekic',
p1_odds=1.8,
p2_odds=2.1,
),
]
result = find_matching(data, API_RESPONSE)
print(result)
# [Obj(p1='Sloane Stephens', p2='Polona Hercog', p1_odds=1.2, p2_odds=3.8, is_found=True, external_id=9999999999999)]
import xml.etree.cElementTree as ET
from typing import List
from typing import NamedTuple
from typing import Tuple
class User(NamedTuple):
internal_id: int
name: str
age: int
images: Tuple[str]
XML: str = """
<root>
<user internal-id="1233232323">
<name>Alex</name>
<age>23</age>
<image id="1">http://example.com/images/img1.jpg</image>
<image id="2">http://example.com/images/img2.jpg</image>
<image id="3">http://example.com/images/img3.jpg</image>
<image id="4">http://example.com/images/img4.jpg</image>
<image id="5">http://example.com/images/img5.jpg</image>
</user>
<user internal-id="24323423423">
<name>Daniel</name>
<age>31</age>
<image id="1">http://example.com/images/img1.jpg</image>
<image id="2">http://example.com/images/img2.jpg</image>
<image id="3">http://example.com/images/img3.jpg</image>
<image id="4">http://example.com/images/img4.jpg</image>
<image id="5">http://example.com/images/img5.jpg</image>
</user>
</root>
"""
if __name__ == '__main__':
users: List[User] = []
root = ET.fromstring(XML)
for user in root:
user_data = tuple(tag.text for tag in user)
users.append(
User(
internal_id=user.get('internal-id'),
name=user_data[0],
age=user_data[1],
images=user_data[2:]
)
)
if __name__ == '__main__':
print('Здравствуйте, я робот который определят, какое сейчас время года по числу :)')
try:
date = int(input('Введите какое сейчас число: '))
except ValueError:
print('Ты ввёл не число. Ты убил меня.')
else:
if date <= 2:
print('Сейчас на улице зима, сиди дома ;)')
elif date <= 5:
print('Ой весна иди делай фотки!')
elif date <= 8:
print('Везет тебе сейчас у тебя лето, а мне тут людям помогать, но мне даже это нравиться')
elif date <= 11:
print('Вот и осень подоспела, идти в школу, а мне тут сидеть')
else:
print('Сейчас зима и вроде грустно, но уже скоро 2020 год!')
Я только начинаю есличто)
from functools import partial
from pathlib import Path
from platform import system
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
ROOT_DIR = Path(__file__).parents[0]
if __name__ == '__main__':
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.binary_location = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
local_system = system()
make_path = partial(Path.joinpath, ROOT_DIR, 'chrome_drivers')
if local_system == 'Linux':
driver_path = make_path('chromedriver_linux64')
elif local_system == 'Darwin':
driver_path = make_path('chromedriver_mac64')
elif local_system == 'Windows':
driver_path = make_path('chromedriver_win32.exe')
else:
raise RuntimeError('Unknown os system')
driver = webdriver.Chrome(executable_path=str(driver_path), options=chrome_options)
driver.get('https://www.google.com/')
print(driver.title)
driver.quit()
import math
import os
INPUT_FILE = 'input.txt'
OUTPUT_FILE = 'output.txt'
NUMBER_THRESHOLD = 1000
if __name__ == '__main__':
if not os.path.exists(INPUT_FILE) or not os.path.isfile(INPUT_FILE):
raise FileNotFoundError
with open('input.txt') as file:
text = file.read()
if not text:
raise ValueError('File is empty')
try:
a, b, c, *_ = [int(n) for n in text.strip().split(" ") if n.isdigit() and int(n) < NUMBER_THRESHOLD]
except ValueError:
raise ValueError('Wrong input data')
out = ""
if not (a < b + c and b < a + c and c < a + b):
out = "-1"
else:
p = 0.5 * (a + b + c)
h = 2 * math.sqrt(p * (p - a) * (p - b) * (p - c)) / a
out = f'{str(a + b + c)} {("%.5f" % (a * h / 2))}'
with open(OUTPUT_FILE, 'w') as file:
file.write(out)
from sqlite3 import Connection as SqliteConnection
from sqlite3 import Cursor as SqliteCursor
sql = """
pragma foreign_keys = on;
create table if not exists users
(
id integer primary key autoincrement,
internal_id text not null,
first_name text not null,
last_name text not null,
username text not null unique,
created date not null default current_date
);
create unique index if not exists users_id_uindex
on users (id);
create unique index if not exists users_internal_id_uindex
on users (internal_id);
create index if not exists users_first_name_index
on users (created);
create index if not exists users_last_name_index
on users (created);
create unique index if not exists users_username_uindex
on users (username);
create index if not exists users_created_index
on users (created);
"""
def check_db(db_connect: SqliteConnection,
db_cursor: SqliteCursor) -> None:
db_cursor.executescript(sql)
db_connect.commit()
from sqlite3 import Connection as SqliteConnection
from sqlite3 import Cursor as SqliteCursor
from typing import List
def insert_user(db_cursor: SqliteCursor,
db_connect: SqliteConnection,
internal_id: str, username: str,
first_name: str, last_name: str) -> None:
db_cursor.execute("""
insert into users(internal_id, username, first_name, last_name)
select :internal_id, :username, :first_name, :last_name
where not exists(select 1 from users where internal_id = :internal_id and username = :username)
""", {
'internal_id': internal_id,
'username': username,
'first_name': first_name,
'last_name': last_name,
})
db_connect.commit()
def select_user(db_connect: SqliteConnection,
username: str) -> List[tuple] or None:
result = db_connect.execute(
f"""select *
from users
where username = :username""",
{'username': username},
).fetchone()
return result
from contextlib import closing
import sqlite3
from db.utils import check_db
from db.queries import insert_user
with closing(sqlite3.connect('db_name')) as db_connect:
with closing(db_connect.cursor()) as db_cursor:
check_db(db_connect, db_cursor) # проверяем есть ли таблица в базе, если нет то создаём её
insert_user(db_cursor, db_connect, 'internal_id', 'username', 'first_name', 'last_name') # если в базе ещё нет такого юзера с internal_id и username то он создастся
from contextlib import closing
import sqlite3
from db.utils import check_db
from db.queries import select_user
with closing(sqlite3.connect('db_name')) as db_connect:
with closing(db_connect.cursor()) as db_cursor:
check_db(db_connect, db_cursor) # проверяем есть ли таблица в базе, если нет то создаём её
user = select_user(db_connect, 'username')