Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/cs102.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
- name: Set up Python 3.8.6
uses: actions/setup-python@v2
with:
python-version: '3.8.6'
python-version: '3.10'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
Expand Down
98 changes: 82 additions & 16 deletions homework02/sudoku.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import pathlib
import random
import typing as tp

T = tp.TypeVar("T")


def read_sudoku(path: tp.Union[str, pathlib.Path]) -> tp.List[tp.List[str]]:
""" Прочитать Судоку из указанного файла """
"""Прочитать Судоку из указанного файла"""
path = pathlib.Path(path)
with path.open() as f:
puzzle = f.read()
Expand All @@ -19,7 +20,7 @@ def create_grid(puzzle: str) -> tp.List[tp.List[str]]:


def display(grid: tp.List[tp.List[str]]) -> None:
"""Вывод Судоку """
"""Вывод Судоку"""
width = 2
line = "+".join(["-" * (width * 3)] * 3)
for row in range(9):
Expand All @@ -38,11 +39,18 @@ def group(values: tp.List[T], n: int) -> tp.List[tp.List[T]]:
Сгруппировать значения values в список, состоящий из списков по n элементов

>>> group([1,2,3,4], 2)
[[1, 2], [3, 4]]
[[1, 2], [3, 4]])
>>> group([1,2,3,4,5,6,7,8,9], 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
"""
pass
i = 0
j = n
s = []
while j <= len(values):
s.append(values[i:j])
i = j
j += n
return s


def get_row(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[str]:
Expand All @@ -55,7 +63,7 @@ def get_row(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[str
>>> get_row([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (2, 0))
['.', '8', '9']
"""
pass
return grid[pos[0]]


def get_col(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[str]:
Expand All @@ -68,7 +76,10 @@ def get_col(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[str
>>> get_col([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (0, 2))
['3', '6', '9']
"""
pass
post = []
for i in range(len(grid)):
post.append(grid[i][pos[1]])
return post


def get_block(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[str]:
Expand All @@ -82,10 +93,14 @@ def get_block(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[s
>>> get_block(grid, (8, 8))
['2', '8', '.', '.', '.', '5', '.', '7', '9']
"""
pass
square = []
for i in range(pos[0] // 3 * 3, pos[0] // 3 * 3 + 3):
for j in range(pos[1] // 3 * 3, pos[1] // 3 * 3 + 3):
square.append(grid[i][j])
return square


def find_empty_positions(grid: tp.List[tp.List[str]]) -> tp.Optional[tp.Tuple[int, int]]:
def find_empty_positions(grid: tp.List[tp.List[str]]):
"""Найти первую свободную позицию в пазле

>>> find_empty_positions([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']])
Expand All @@ -95,7 +110,14 @@ def find_empty_positions(grid: tp.List[tp.List[str]]) -> tp.Optional[tp.Tuple[in
>>> find_empty_positions([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']])
(2, 0)
"""
pass
x = -1
for i in range(len(grid)):
x += 1
y = 0
for j in range(len(grid[i])):
if grid[i][j] == ".":
return x, y
y += 1


def find_possible_values(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.Set[str]:
Expand All @@ -109,11 +131,13 @@ def find_possible_values(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -
>>> values == {'2', '5', '9'}
True
"""
pass
full = set(get_row(grid, pos) + get_col(grid, pos) + get_block(grid, pos))
possible_values = set("123456789") - full
return possible_values


def solve(grid: tp.List[tp.List[str]]) -> tp.Optional[tp.List[tp.List[str]]]:
""" Решение пазла, заданного в grid """
def solve(grid: tp.List[tp.List[str]]):
"""Решение пазла, заданного в grid"""
""" Как решать Судоку?
1. Найти свободную позицию
2. Найти все возможные значения, которые могут находиться на этой позиции
Expand All @@ -125,13 +149,33 @@ def solve(grid: tp.List[tp.List[str]]) -> tp.Optional[tp.List[tp.List[str]]]:
>>> solve(grid)
[['5', '3', '4', '6', '7', '8', '9', '1', '2'], ['6', '7', '2', '1', '9', '5', '3', '4', '8'], ['1', '9', '8', '3', '4', '2', '5', '6', '7'], ['8', '5', '9', '7', '6', '1', '4', '2', '3'], ['4', '2', '6', '8', '5', '3', '7', '9', '1'], ['7', '1', '3', '9', '2', '4', '8', '5', '6'], ['9', '6', '1', '5', '3', '7', '2', '8', '4'], ['2', '8', '7', '4', '1', '9', '6', '3', '5'], ['3', '4', '5', '2', '8', '6', '1', '7', '9']]
"""
pass
empty_positions = find_empty_positions(grid)
if empty_positions is None:
return grid
else:
possible_values = find_possible_values(grid, empty_positions)
for i in possible_values:
grid[empty_positions[0]][empty_positions[1]] = i
next = solve(grid)
if next:
return next
grid[empty_positions[0]][empty_positions[1]] = "."


def check_solution(solution: tp.List[tp.List[str]]) -> bool:
""" Если решение solution верно, то вернуть True, в противном случае False """
"""Если решение solution верно, то вернуть True, в противном случае False"""
# TODO: Add doctests with bad puzzles
pass
all = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
for i in range(0, len(solution)):
for j in range(0, len(solution)):
pos = i, j
if (
not sorted(get_row(solution, pos)) == all
or not sorted(get_col(solution, pos)) == all
or not sorted(get_block(solution, pos)) == all
):
return False
return True


def generate_sudoku(N: int) -> tp.List[tp.List[str]]:
Expand All @@ -156,7 +200,24 @@ def generate_sudoku(N: int) -> tp.List[tp.List[str]]:
>>> check_solution(solution)
True
"""
pass
grid = [["." for i in range(9)] for i in range(9)]
print(N)
if N > 81:
N = 81
print(grid)
grid = solve(grid)
print(grid)
k = 0
while k != 81 - N:
i = random.randint(0, 8)
j = random.randint(0, 8)
if grid[i][j] == ".":
k = k
else:
grid[i][j] = "."
k += 1
print(grid)
return grid


if __name__ == "__main__":
Expand All @@ -168,3 +229,8 @@ def generate_sudoku(N: int) -> tp.List[tp.List[str]]:
print(f"Puzzle {fname} can't be solved")
else:
display(solution)
if check_solution(solution):
print("Solution is correct")
else:
print("LoL")
display(generate_sudoku(1))
7 changes: 6 additions & 1 deletion homework05/access_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ def get_access_token(client_id: int, scope: str) -> None:
parser = argparse.ArgumentParser()
parser.add_argument("client_id", help="Application Id", type=int)
parser.add_argument(
"-s", dest="scope", help="Permissions bit mask", type=str, default="", required=False
"-s",
dest="scope",
help="Permissions bit mask",
type=str,
default="",
required=False,
)
args = parser.parse_args()
get_access_token(args.client_id, args.scope)
23 changes: 12 additions & 11 deletions homework05/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
responses==0.12.1
requests==2.24.0
httpretty==1.0.2
tqdm==4.52.0
networkx==2.5
pandas==1.1.4
matplotlib==3.3.3
python-louvain==0.14
gensim==3.8.3
textacy==0.10.1
pyLDAvis==2.1.2
responses
requests
httpretty
tqdm
networkx
pandas
matplotlib
python-louvain
gensim
textacy
pyLDAvis
types-requests
18 changes: 15 additions & 3 deletions homework05/research/age.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,22 @@
def age_predict(user_id: int) -> tp.Optional[float]:
"""
Наивный прогноз возраста пользователя по возрасту его друзей.

Возраст считается как медиана среди возраста всех друзей пользователя

:param user_id: Идентификатор пользователя.
:return: Медианный возраст пользователя.
"""
pass
data = get_friends(user_id, fields=["bdate"]).items
data = tp.cast(tp.List[tp.Dict[str, tp.Any]], data)
ages = []
for friend in data:
try:
day, month, year = [int(i) for i in friend["bdate"].split(".")]
bdate = dt.date(year, month, day)
age = dt.date.today().year - bdate.year
ages.append(age)
except:
pass
if ages:
return statistics.median(ages)
else:
return None
17 changes: 13 additions & 4 deletions homework05/research/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,29 @@
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd

from vkapi.friends import get_friends, get_mutual
from vkapi.friends import MutualFriends, get_friends, get_mutual


def ego_network(
user_id: tp.Optional[int] = None, friends: tp.Optional[tp.List[int]] = None
) -> tp.List[tp.Tuple[int, int]]:
"""
Построить эгоцентричный граф друзей.

:param user_id: Идентификатор пользователя, для которого строится граф друзей.
:param friends: Идентификаторы друзей, между которыми устанавливаются связи.
"""
pass
graph = []
if friends is None:
friends_response = get_friends(user_id, fields=["nickname"]).items
friends_response = tp.cast(tp.List[tp.Dict[str, tp.Any]], friends_response)
friends = [user["id"] for user in friends_response if not user.get("deactivated")]
mutual_users = get_mutual(source_uid=user_id, target_uids=friends)
mutual_users = tp.cast(tp.List[MutualFriends], mutual_users)
for user in mutual_users:
for common_friend in user["common_friends"]:
link = (user["id"], common_friend)
graph.append(link)
return graph


def plot_ego_network(net: tp.List[tp.Tuple[int, int]]) -> None:
Expand Down
1 change: 0 additions & 1 deletion homework05/research/topic_modeling.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from gensim.corpora import Dictionary
from textacy import preprocessing
from tqdm import tqdm

from vkapi.wall import get_wall_execute


Expand Down
1 change: 0 additions & 1 deletion homework05/tests/tests_api/test_friends.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import unittest

import responses

from vkapi.friends import FriendsResponse, get_friends, get_mutual


Expand Down
1 change: 0 additions & 1 deletion homework05/tests/tests_api/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import httpretty
import responses
from requests.exceptions import ConnectionError, HTTPError, ReadTimeout, RetryError

from vkapi.session import Session


Expand Down
1 change: 0 additions & 1 deletion homework05/tests/tests_api/test_wall.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

import pandas as pd
import responses

from vkapi.wall import get_wall_execute


Expand Down
1 change: 0 additions & 1 deletion homework05/tests/tests_research/test_age.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import unittest

import responses

from research.age import age_predict


Expand Down
1 change: 0 additions & 1 deletion homework05/tests/tests_research/test_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import unittest

import responses

from research.network import ego_network


Expand Down
2 changes: 1 addition & 1 deletion homework05/vkapi/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

VK_CONFIG = {
"domain": "https://api.vk.com/method",
"access_token": "",
"access_token": "vk1.a.UFTN6YfTQC6xL6suMVEjBZKzWnFlu5PoGa-JJ_C4zi51ns17LyVgsqyOKlDQDFGNZ-PeYeZwxmDSG0mk18bm_QuaApT8i5H9kg40Xd0ujQpnCw0PLykno3l_ohCOLvvMtSjQ_PCR6agAAkvr0hsLIcvsEDb5dt-1GJ3LvkomoDvJ10jfiDQ1VrHSofAl6nMf&expires_in=86400&user_id=337563534",
"version": "5.126",
}
Loading