Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14215

How can I optimize this algorithm in Python? [closed]

$
0
0

The user indicates what he needs to water and how many liters of water he is willing to spend on it, after which a special team goes to the site. As a result, for the company, each order can be represented by three numbers:

Start time, when the team accepted the order and left; time End, when the brigade completed the order and was freed; total order cost Cost. For ease of processing and storage, the time is specified as a single integer equal to the number of minutes that have passed from the start of the service to the desired moment.

The duration of the order = End - Start

The head of the service needs to report to his superiors, so he assigned you a simple task - to find answers to several queries of one of two types:

Find the total cost of orders that began in a given period of time; Find the total duration of orders that completed within a given period of time;

n = int(input())orders = []for i in range(n):    start = list(map(int, input().split()))    orders.append(start)q = int(input())queries = []for i in range(q):    start = list(map(int, input().split()))    queries.append(start)results = []for query in queries:    query_type = query[-1]    if query_type == 1:        start_time = query[0]        end_time = query[1]        total_cost = 0        for order in orders:            order_start_time = order[0]            if order_start_time >= start_time and order_start_time <= end_time:                total_cost += order[2]        results.append(total_cost)    elif query_type == 2:        start_time = query[0]        end_time = query[1]        total_duration = 0        for order in orders:            order_end_time = order[1]            if order_end_time >= start_time and order_end_time <= end_time:                total_duration += order[1] - order[0]        results.append(total_duration)print(*results)

Input:

110 100 100061 10 11 10 210 100 110 100 2100 1000 1100 1000 2Output:

1000 0 1000 90 0 90How can this algorithm be optimized so that it runs in less than 10 seconds, taking into account that there can be 200,000 input lines?


Viewing all articles
Browse latest Browse all 14215

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>