Untitled

mail@pastecode.io avatar
unknown
python
a year ago
3.9 kB
1
Indexable
Never
from rdflib import Graph

g = Graph()
g.parse("lab2.rdf", format="xml")


def run_sparql_query(query):
    return g.query(query)


# Список доступных участков
properties = [
    'mediterranean_avenue',
    'baltic_avenue',
    'oriental_avenue',
    'vermont_avenue',
    'connecticut_avenue',
    'st_charles_place',
    'states_avenue',
    'virginia_avenue',
    'st_james_place',
    'tennessee_avenue',
    'new_york_avenue',
    'kentucky_avenue',
    'indiana_avenue',
    'illinois_avenue',
    'atlantic_avenue',
    'ventnor_avenue',
    'marvin_gardens',
    'pacific_avenue',
    'north_carolina_avenue',
    'pennsylvania_avenue',
    'park_place',
    'boardwalk'
]
# Запрос данных у пользователя
money = float(input("Сколько у вас денег? "))
print("Список всех участков:")
for prop in properties:
    print("-", prop)
owned_properties = input("Какими участками вы уже владеете? (Введите названия участков через запятую) ").split(",")
owned_properties = [prop.strip() for prop in owned_properties]
groups_and_number_bought = {}

for street in owned_properties:
    que = f"""
    PREFIX monopoly: <http://www.semanticweb.org/nastyabeggin/ontologies/2023/9/lab_work2#>
    SELECT ?group
    WHERE {{
      ?property rdf:type monopoly:Property .
      ?group rdf:type monopoly:Group .
      FILTER (?property = monopoly:{street})
      ?property monopoly:be_part_of_group ?group .
    }}
    """
    results = run_sparql_query(que)
    for row in results:
        group = (row.group.split("#")[1])
        groups_and_number_bought[group] = groups_and_number_bought.get(group, 0) + 1
        print(group + " - " + street)

properties_to_buy = {}
property_to_buy_group = {}
groups_and_number_bought = dict(sorted(groups_and_number_bought.items(), key=lambda item: -item[1]))
groups = [group for group in groups_and_number_bought.keys()]
for group in groups:
    que = f"""
        PREFIX monopoly: <http://www.semanticweb.org/nastyabeggin/ontologies/2023/9/lab_work2#>
        SELECT ?group ?property ?propertyCost
        WHERE {{
          ?group rdf:type monopoly:Group .
          ?property rdf:type monopoly:Property .
          FILTER (?group = monopoly:{group})
          ?property monopoly:be_part_of_group ?group .
          ?property monopoly:property_cost ?propertyCost .
        }} 
        """
    results = run_sparql_query(que)
    for row in results:
        if row.property.split("#")[1] not in owned_properties and int(row.propertyCost) <= money:
            properties_to_buy[row.property.split("#")[1]] = row.propertyCost
            property_to_buy_group[row.property.split("#")[1]] = row.group.split("#")[1]
    if len(properties_to_buy) != 0:
        break

if len(properties_to_buy) == 0:
    que = f"""
        PREFIX monopoly: <http://www.semanticweb.org/nastyabeggin/ontologies/2023/9/lab_work2#>
        SELECT ?property ?cost
        WHERE {{
        ?property rdf:type monopoly:Property .
        ?property monopoly:property_cost ?cost .
  
        FILTER (?cost <= {money})
        }}
        ORDER BY DESC(?cost)
        LIMIT 1
        """
    results = run_sparql_query(que)
    for row in results:
        properties_to_buy[row.property.split("#")[1]] = row.cost
else:
    # Сортируем по возрастанию цены
    properties_to_buy = dict(sorted(properties_to_buy.items(), key=lambda item: item[1]))

if len(properties_to_buy) > 0:
    print("\nУчасток, который вам стоит купить в первую очредь:")
    prop = next(iter(properties_to_buy))
    print("-", prop, "стоимостью", properties_to_buy[prop], "в группе", property_to_buy_group[prop])
else:
    print("У вас недостаточно денег, чтобы купить участок")