My issue
I’ve taken nested loops for counting the number of holidays and inside that loop, I’ve mentioned a while loop which checks the elements of the array and compares it to the days that are already holidays and if it is then it won’t be counted and vice versa.
But it shows the Time limit exceeded as an output!
My code
t=int(input())
for i in range(t):
N=int(input())
A=list(map(int, input().split()))
i=0
days=0
holidays=0
for days in range(1,31):
for i in range(1,31):
if(days==7*i or days==7*i-1):
holidays += 1
j=0
while(j<N):
if(A[j] != 7*i or A[j] != 7*i-1):
holidays += 1
else:
holidays = holidays+0
j=j+1
print(holidays)
Learning course: Python for problem solving - 2
Problem Link: CodeChef: Practical coding for everyone
@priyanka_021
Plzz refer this solution u get logic.
# Solution as follows
t = int(input())
for i in range(t):
N = int(input())
A = list(map(int, input().split()))
# Weekend holiday dates
weekend = [6, 7, 13, 14, 20, 21, 27, 28]
#merging the list of holidays
overall = A + weekend
#finding the unique list after removing duplicates
overall_unique = list(set(overall))
# number of elements in the final holiday list
print(len(overall_unique))
Hey, so there are basically 2 mistakes in the code because of which you are getting TLE:
Variable i
keeps on changing: You are already using i
in for i in range(t)
but then changing its value in i=0
, then looping using i
again in for i in range(1,31)
I suggest using a different value for last 2.
Wrong indentation level of j
: Your while(j<N)
and j=j+1
are on same level, meaning j
remains 0 throughout the while
loop. Its an infinite loop basically.
Now, after you fix them you won’t get TLE but you will still get WA, as there are quite a few logical errors in your code. I am assuming you will want to find them yourself but I will leave a solution derived from your code here.
Please try yourself before checking it out. Note that this isn’t as optimal as @dpcoder_007 's solution but should be easier to understand:
t=int(input())
for i in range(t):
N=int(input())
A=list(map(int, input().split()))
days=0
holidays=0
for days in range(1,31):
if(days%7==0 or days%7==6): # if its Saturday or Sunday, add 1 to holidays.
holidays += 1
j=0
while(j<N):
if(not (A[j]%7==0 or A[j]%7==6)): # if festival is NOT on Saturday or Sunday, add 1 to holidays.
holidays += 1
else:
holidays = holidays+0
j=j+1
print(holidays)