# lockers = [1] * 1001
# for student in range(1, 1001, 1):
# # on second students
# if student % 2 == 0:
# for i in range(2, 1001, 2):
# lockers[i] = 1
# # on third student
# elif student % 3 == 0:
# for i in range(3, 1001, 3):
# lockers[i] = not lockers[i]
# else:
# for i in range(1, 1001, 1):
# lockers[i] = 0
# print(lockers.count(1))
# theres a bug in this code: person 4 will actually be counted as second person instead of first
# and i misunderstaod the problem, oops..
# ---------------------------------------------------------------------------------------
lockers = [1] * 1001
for student in range(1, 1001):
for locker in range(student, 1001, student):
# Student 1 -> change locker 1, 2, 3, 4, 5, ...
# Student 2 -> change locker 2, 4, 6, 8, ...
# Student 3 -> change locker 3, 6, 9, 12, ...
# Student 4 -> change locker 4, 8, 12, 16, ...
# Student 5 -> change locker 5, 10, 15, 20, ...
lockers[locker] = not lockers[locker] # each student's action is just changing the state of the locker
# so doing not lockers[locker] is fine
print(lockers.count(1) - 1)
# this version works!
No comments:
Post a Comment