#### Counterfeit coin detection puzzle for any number of coins – python

I’ve tried creating a simple python code for this puzzle, which goes like this:
You have 9 coins. one of the coins is counterfeit, and weighs less than the other coins, while all the other coins weigh the same.
Your goal is to find the counterfeit coin by weighing it using a libra Twice.

I wanted to create a code that would work for any number of coins, by using the libra it the least amount of times.

``````# Generate a chosen number of coins with one random 'Fake' coin

from random import randrange, uniform

n_coins = int(input("How many coins do you want? > "))

coins = {}
for coin in range(1, n_coins + 1):
coins[coin] = 5

random_coin = randrange(1, n_coins)
coins[random_coin] = 4

print(f"Generated {n_coins} coins.")

# Devide to groups function
def group(a,b,c,coins):
group_1, group_2, group_3 = {}, {}, {}
for coin in coins:
if coin <= a:
group_1[coin] = coins[coin]
elif coin <= a+b:
group_2[coin] = coins[coin]
elif coin <= a+b+c:
group_3[coin] = coins[coin]
return group_1, group_2, group_3

# Weighing function
def weigh(group_1, group_2):
weight_1, weight_2 = 0, 0

for coin in group_1:
weight_1 += group_1[coin]
for coin in group_2:
weight_2 += group_2[coin]

if weight_1 > weight_2:
return "1"
elif weight_1 < weight_2:
return "2"
else:
return "="

# Fake coin finder algorithm
current_coins = coins

while len(current_coins) != 1:
a, b = len(current_coins) // 3, len(current_coins) // 3
if len(current_coins) % 3 == 0:
c = len(current_coins) // 3
else:
c = len(current_coins) // 3 + len(current_coins) % 3

group_1, group_2, group_3 = group(a,b,c,current_coins)

if weigh(group_1, group_2) == "=":
current_coins = group_3
elif weigh(group_1, group_2) == "1":
current_coins = group_2
elif weigh(group_1, group_2) == "2":
current_coins = group_1

# Fake coin was found
print(current_coins)
``````

The problem I have rn is that after the third weigh, ‘current_coins’ becomes empty {} for no reason, and the fake coin could not be detected.
If anyone has any idea of why this is happening and what can I do about it, please share your idea.
thanks ðŸ™‚

Source: Python Questions