Street Lights Problem in Python

In this class, we write a program for street lights problem in python.

For Complete YouTube Video: Click Here

Street Lights Problem

The reader should have prior knowledge in python. For complete python course click here.

All these examples help you in improving your coding skills.

You can easily crack the placement training exams. Please take the question and try to solve it on your own for better practice.

Q1) Read the below problem statements, and write a program to satisfy the requirement given.

S1) There are N street lights in the street.

S2) Given the length of the street covered by each street light. i.e. starting and ending point.

S3) There is a possibility of an intersection of focus of two lights.

Find the length o the street covered by the light?

Let’s take an example and understand the problem better.

N=5

Given Each street light covered distance.

L1) (2,5)

L2) (4,8) Understand here, these two lights focus is intersecting. This second light starting point at 4. previous light ends at 5.

L3) (9,12)

L4) (11,15)

L5) (17,19)

Length of the street covered by light =14

Logic

Given The street lights focus may intersect.

The main logic is to subtract the intersection length.

The first street light is covering a distance from 2 to 5. means it cover 3 meters. So assume length is in meters.

The second street light starting point is from 4. i.e. the length 4 to 5 already covered by street light one.

So count street light two from 5 to 8. which is covering 3 meters.

Logic, if the light focus is intersecting with previous light, i.e. last light endpoint is greater than the present light starting point.

Take the present light starting point as the previous light endpoint.

To maintain the logic mentioned above.

In the program, we have taken a variable plep. The previous light end position.

Initially, Took the variable plep as zero.

The previous light end position is taken zero for the first light. Keep updating the plep value in each iteration.

Please identify the logic for better practice from the program given below.

Program

n=int(input("enter the number of street lights"))
list1=[]
print("enter the starting and ending value of each light with space as separator")
plep=0
sumation=0
for i in range(n):
    list2=[]
    x,y=map(int,input().split())
    list2.append(x)
    list2.append(y)
    list1.append(list2)
print(list1)
#Logic
for j in range(n):
    if list1[j][0]<plep:
        sp=plep
    else:
        sp=list1[j][0]
    ep=list1[j][1]
    sumation+=ep-sp
    plep=list1[j][1]
print(sumation)

Many practice examples and placement training tests are available. Check our placement Training Course.