예제 #1
0
파일: network.py 프로젝트: Sofshik/cs102
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: Идентификаторы друзей, между которыми устанавливаются связи.
    """
    graph = []
    if not friends:
        friends_fields: tp.List[tp.Dict[str, tp.Any]] = get_friends(
            user_id, fields=["nickname",
                             "is_closed, deactivate"]).items  # type: ignore
        friends = [
            friend["id"] for friend in friends_fields
            if not (friend.get("deactivate") or friend.get("is_closed"))
        ]
    mutuals = get_mutual(user_id, target_uids=friends)
    for mutual in mutuals:
        mutual_m = tp.cast(MutualFriends, mutual)  # type: ignore
        for common in mutual_m["common_friends"]:
            graph.append((mutual_m["id"], common))
    return graph
예제 #2
0
파일: age.py 프로젝트: Sofshik/cs102
def age_predict(user_id: int) -> tp.Optional[float]:
    """
    Наивный прогноз возраста пользователя по возрасту его друзей.

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

    :param user_id: Идентификатор пользователя.
    :return: Медианный возраст пользователя.
    """
    age = []
    time = dt.date.today()
    friends = get_friends(user_id, fields=["bdate"]).items
    for friend in friends:
        try:
            bdate = dt.datetime.strptime(friend["bdate"], "%d.%m.%Y")  # type: ignore
        except (KeyError, ValueError):
            continue
        age.append(
            time.year
            - bdate.year
            - (time.month < bdate.month or (time.month == bdate.month and time.day < bdate.day))
        )

    if age:
        return statistics.median(age)
    return None
예제 #3
0
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: Идентификаторы друзей, между которыми устанавливаются связи.
    """
    if not friends:
        friends = tp.cast(
            tp.List[int],
            get_friends(user_id=tp.cast(int, user_id),
                        fields=["nickname"]).items,
        )

    mutual = get_mutual(source_uid=user_id, target_uids=friends)
    res = []

    for m in mutual:
        m = tp.cast(MutualFriends, m)
        for f in m["common_friends"]:
            res.append((int(m["id"]), int(f)))
    return res
예제 #4
0
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: Идентификаторы друзей, между которыми устанавливаются связи.
    """
    network = []
    if not friends:
        get_friends(user_id).items  # type: ignore
    mutual_friends = get_mutual(source_uid=user_id, target_uids=friends)
    for target in mutual_friends:
        for friend in target["common_friends"]:  # type: ignore
            network.append((target["id"], friend))  # type: ignore
    return network
예제 #5
0
 def test_get_friends(self):
     expected_fids = [1, 2, 3, 4, 5]
     responses.add(
         responses.GET,
         "https://api.vk.com/method/friends.get",
         json={"response": {"count": len(expected_fids), "items": expected_fids}},
         status=200,
     )
     fids = get_friends(user_id=1)
     expected_response = FriendsResponse(count=len(expected_fids), items=expected_fids)
     self.assertEqual(expected_response, fids)
예제 #6
0
def age_predict(user_id: int) -> tp.Optional[float]:
    friends = get_friends(user_id, fields=["bdate"]).items
    arr_ages = []
    for i in friends:
        try:
            bdate = dt.datetime.strptime(friend["bdate"], "%d.%m.%Y").year
        except (KeyError, ValueError):
            continue
        arr_ages.append(dt.date.today().year - bdate)
    try:
        return statistics.median(arr_ages)
    except statistics.StatisticsError:
        return None
예제 #7
0
def age_predict(user_id: int) -> tp.Optional[float]:
    """
    Наивный прогноз возраста пользователя по возрасту его друзей.
    Возраст считается как медиана среди возраста всех друзей пользователя
    :param user_id: Идентификатор пользователя.
    :return: Медианный возраст пользователя.
    """
    ages = []
    friends = get_friends(user_id, fields=["bdate"])
    for friend in friends.items:
        try:
            birthdate = dt.datetime.strptime(friend["bdate"], "%d.%m.%Y")  # type: ignore
            age = relativedelta(dt.datetime.now(), birthdate).years
            ages.append(age)
        except (KeyError, ValueError):
            pass
    if not ages:
        return None
    return statistics.median(ages)
예제 #8
0
def ego_network(
        user_id: tp.Optional[int] = None,
        friends: tp.Optional[tp.List[int]] = None
) -> tp.List[tp.Tuple[int, int]]:

    if friends is False:
        fields: tp.List[tp.Dict[str, tp.Any]] = get_friends(
            user_id, fields=["nickname", "is_closed, deactivate"]).items
        friends = [
            i["id"] for i in fields
            if not (i.get("deactivate") or i.get("is_closed"))
        ]

    mutuals = get_mutual(user_id, target_uids=friends)
    ego_net_graph = []
    for mut in mutuals:
        mut = tp.cast(MutualFriends, mut)
        for common in mut["common_friends"]:
            ego_net_graph.append((mut["id"], common))
    return ego_net_graph
예제 #9
0
def age_predict(user_id: int) -> tp.Optional[float]:
    """
    Наивный прогноз возраста пользователя по возрасту его друзей.

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

    :param user_id: Идентификатор пользователя.
    :return: Медианный возраст пользователя.
    """
    friends = get_friends(user_id, 10000, fields=["bdate"]).items
    current_date = dt.datetime.today().year
    ages = []
    for friend in friends:
        try:
            ages.append(current_date - dt.datetime.strptime(friend["bdate"], "%d.%m.%Y").year)  # type: ignore
        except:
            pass
    try:
        return statistics.median(ages)
    except statistics.StatisticsError:
        return None
예제 #10
0
def age_predict(user_id: int) -> tp.Optional[float]:
    """
    Наивный прогноз возраста пользователя по возрасту его друзей.

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

    :param user_id: Идентификатор пользователя.
    :return: Медианный возраст пользователя.
    """
    friends = get_friends(user_id, fields=["bdate"])
    ages = []
    for f in friends.items:
        try:
            if isinstance(f, dict):
                bdate = list(map(int, f["bdate"].split(".")))
            if len(bdate) < 3:
                continue
            else:
                ages.append(
                    calculate_age(
                        dt.date(day=bdate[0], month=bdate[1], year=bdate[2])))
        except (TypeError, KeyError) as e:
            continue
    return statistics.median(ages) if ages else None