I wanted to make a code that, when receiving data, process them in turn, and not just write them all into one list. Because in cases where numbers reach 2000 characters in length, the code consumes a lot of memory (allocated for this task). Here is the code I did, but which immediately enters all the numbers in the list.
As I understand it, these lines would be most efficient to use:
bridge_length, capacity = [int(w) for w in input().split()]
for line in sys.stdin:
nums = [int(w) for w in line.split()]
But I don’t know how to add it to my code correctly.
What I have tried:
My code:
from collections import namedtuple
Item = namedtuple("Item", "length, weight")
def support(bridge, wagons):
if not bridge.length or not wagons:
return -1
length = 0
load = wagons[0].weight
if load > bridge.weight:
return 1
if len(wagons) == 1:
return -1
load += wagons[1].weight
if load > bridge.weight:
return 2
start = 1
for end in range(1, len(wagons) - 1):
while length + wagons[end].length >= bridge.length:
load -= wagons[start - 1].weight
length -= wagons[start].length
start += 1
length += wagons[end].length
load += wagons[end + 1].weight
if load > bridge.weight:
return end + 2
return -1
def read_words_until_empty_line():
while True:
try:
line = input()
except:
break
yield from line.split()
def words_to_items(words):
it = map(int, words)
for length in it:
yield Item(length, next(it))
bridge, *wagons = words_to_items(read_words_until_empty_line())
print(support(bridge, wagons))
Explanation: this code calculates whether the train can pass the bridge, which has a length, and the maximum weight that it can support. The first line of input just the same enters the parameters of the bridge, and the rest of the parameters are wagons. To be safe, if any part of a wagon is on the bridge, we will count the entire weight of that wagon in computing the total weight at that moment. If the train can safely cross the bridge, write the number -1. Otherwise, write the number of the first wagon that will cause the weight to exceed the bridge's carrying capacity. Wagons are numbered from 1.
Input example:
10 100
10 90 10 10 9 80 1 10 9 10 9 80
5 10 5 10
1 10 1 10 1 10 1 10 1 40
Output:
-1
And this code does not require a lot of memory when the numbers are small, because it simply writes them all into one list, and then it works with them, but I would like to know if there is a way to make the data enter only when it is needed process, and then just delete, so as not to load memory