Q) neighbours m and n order takeout on new year's. after this, they order at a fixed interval. write a python program to find out the number of days both will order on the same day in january.
for example: if m orders every 2 days after jan 1st and n orders every 3 days after jan 1st, the number of times they order on same day is 6 (include jan 1st)
I tried this.
c1 and c2 in the while loop will give the days on which they ordered takeout. I was planning to add all the values of c1 and c2 to two separate lists and compare them?? i'm not sure if that's possible, and if it is this is wrong code. I'm not sure how to do this. please someone help
m=int(input())
n=int(input())
c1=1
c2=1
count=0
while c1 in range(1,31):
c1=c1 m
l1=[1,c1]
while c2 in range(1,31):
c2=c2 n
l2=[1,c2]
for x in l1:
for y in l2:
if x==y:
count=count 1
print(count)
CodePudding user response:
This is easily solvable using comprehensions/generators.
The days where they order together are both multiples of the step (counting from 0).
You can get those days using:
[day 1 for day in range(31 1) if not (day%2 or day%6)]
# output: [1, 7, 13, 19, 25, 31]
NB. day%x
returns 0
if day
if a multiple of x
, so not (day%2 or day%6)
is True when day
is simultaneously a multiple of 2
and 6
.
However, you quickly realize that you do not need to test all days, only those of the largest multiplier:
[day 1 for day in range(0, 31 1, 6) if not (day%2 or day%6)]
# output: [1, 7, 13, 19, 25, 31]
If you only want the count of days:
sum(1 for day in range(0, 31 1, 6) if not (day%2 or day%6))
# output: 6
CodePudding user response:
m=int(input())
n=int(input())
c1=1
c2=1
l1=[]
l2=[]
count=1
while c1< 32:
c1=c1 m
l1.append(c1)
while c2< 32:
c2=c2 n
if c2 in l1:
l2.append(c2)
count =len(l2)
print(count)
as 1 January is common in all times so i started count from 1
CodePudding user response:
First, to correct your code, you should know that =
does not add items to a list
. It just re-writes it. So, this is the correct way of your code:
m=int(input())
n=int(input())
c1=1
c2=1
count=0
l1 = []
l2 = []
while c1 in range(1,31):
c1=c1 m
l1.append(c1)
while c2 in range(1,31):
c2=c2 n
l2.append(c2)
for x in l1:
if x in l2:
count=count 1
print(count)
BUT I think there is a better way to solve this question. as you see, the days that they both order is the LCM
of the m
and n
and its multiples
lesser than 31
. So the code would be something like this:
count = 0
i = 2
lcm = m * n
while lcm <= 31:
counter = counter 1
lcm = lcm * i
i = i 1
print(counter)