Basic for loops, while, arrays, still learning, thank you Program 1: There is a
ID: 3872717 • Letter: B
Question
Basic for loops, while, arrays, still learning, thank you
Program 1: There is a circular bus course with multiple stations, and there are multiple bus lines. Each line covers a part of the circular course. For example, there are N=10 stations and 5 lines, [0,4], 12, 6], [5,0, [7,91 and [9, 4] like below. Because of the short budget, now we want to cancel the lines that can be covered by other lines. For example, the line #1 can be covered by line #5. Also, the line #3 can cover the line #4. So, we can cancel the bus line #1 and 4 Please make a program that displays the bus lines that do not need to be canceled given a number of bus stations and multiple bus lines as a text file (see the example below). The number of bus stations is on the first line; the number of bus lines is on the second line, and then the range of stations each bus line covers are following sequentially. Example of input file (input.txt) 10 0 4 9 4 Example of output (display on the eclipse console) 2 3 5Explanation / Answer
#Working code in Python
''' In this program i am using set theory to check whether one bus_line is a subset of other or not, if it is not
a subset i am taking it otherwise ignoring it'''
stations = -1 # to read from input file total number of stations
bus_lines = -1 # reading from input file total number of bus lines
full_range = [] # this list(array) will contain all start- end range of a bus line
result = [] # this list will contain our final result
with open("input.txt", 'r') as f: # reading the input file to parse our inputs
data = f.readlines()
stations = int(data[0])
bus_lines = int(data[1])
#generating all numbers between busline range provided like [7 9]-->[7, 8, 9] and storing it in full_range to check later
for i in range(2, len(data)):
temp = data[i].split()
start = int(temp[0])
end = int(temp[1])
if start < end and end <stations: # if start is less then end
full_range.append(list(range(start, end+1)))
else: # else we need to go for a reverse range
i = abs(end - start) + 1
temp = []
while i >0:
if start < stations:
temp.append(start)
start += 1
else:
start = 0
temp.append(start)
start +=1
i -= 1
full_range.append(temp)
#using set theory to check one set in a full_range is a subset of any other set or not
for i in range(0, len(full_range)):
flag = 0
for j in range(0, len(full_range)):
if i != j:
if set(full_range[i]).issubset(set(full_range[j])):
flag = 1
break
if flag == 0:
result.append(i+1)
print (result)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.