假币问题python代码
时间: 2023-12-20 12:30:10 浏览: 150
三分法查找假币问题.zip
以下是两种假币问题的Python代码:
方法一:直接遍历所有纸币,找到质量小的纸币就返回下标,否则返回“找不到”
```python
def findFalseCoin(coins, start, n):
min = coins[start]
flag = 0
for i in range(start, n + 1):
if coins[i] < min:
flag = 1
min = i
break
elif coins[i] > min:
flag = 1
min = start
break
if flag == 1:
print("Fake coin:{}".format(min))
else:
print("Fake coin is not found")
coins = list(input().split(','))
coins = [int(i) for i in coins]
findFalseCoin(coins, 0, len(coins) - 1)
```
方法二:将两堆硬币上天平比较重量,如果有一堆较轻,那么假的硬币必然在轻的那一堆中。如果两堆硬币重量相等,且两堆之外有一个剩余硬币,则那个剩余硬币就是假硬币。如果两堆硬币重量相等,且两堆之外没有剩余硬币,则查找任务失败,未发现假硬币。
```python
def findFalseCoin(coins):
n = len(coins)
if n % 2 == 0:
left = coins[:n//2]
right = coins[n//2:]
left_sum = sum(left)
right_sum = sum(right)
if left_sum < right_sum:
return findFalseCoin(left)
elif left_sum > right_sum:
return findFalseCoin(right)
else:
return -1
else:
left = coins[:n//2]
right = coins[n//2+1:]
left_sum = sum(left)
right_sum = sum(right)
if left_sum < right_sum:
return findFalseCoin(left)
elif left_sum > right_sum:
return findFalseCoin(right)
else:
return coins[n//2]
coins = list(input().split(','))
coins = [int(i) for i in coins]
result = findFalseCoin(coins)
if result == -1:
print("Fake coin is not found")
else:
print("Fake coin:{}".format(result))
```
阅读全文