Reputation: 107
So basically, I'm creating a function that takes a list and 2 values. The function replaces all occurrences of the first value with the second, The function has to then return the number of replacements that were completed.
I've managed to make the code work, but when it prints the number of replacements that were completed, it says 1, when there were in fact 2 replacements completed. It's as if it only checks for the first index and then stops. I don't where I went wrong.
def functionTwo(numberList, checkNum, checkNumTwo):
try:
while True:
num = numberList.index(checkNum)
numberList[num] = checkNumTwo
amount = numberList.count(checkNumTwo)
return amount
except ValueError:
pass
numberList = [4,8,22,43,42,12,1,10,1,10,32,28,8,42,13]
result = functionTwo(numberList, 1, 3)
print(result)
Upvotes: 0
Views: 37
Reputation: 780724
Using index
repeatedly is an overly complex way to do it, it searches the entire list over and over, which is O(n2). Just iterate over the list once and replace the elements as you go, incrementing a counter.
def functionTwo(numberList, checkNum, checkNumTwo):
counter = 0
for i, val in enumerate(numberList):
if val == checkNum:
numberList[i] = checkNumTwo
counter += 1
return counter
However, to fix your code, just move return amount
into the except ValueError:
block. Your code was returning after the first replacement, so of course it returned only 1.
def functionTwo(numberList, checkNum, checkNumTwo):
try:
while True:
num = numberList.index(checkNum)
numberList[num] = checkNumTwo
except ValueError:
return numberList.count(checkNumTwo)
Note that using count()
assumes that the list didn't contain any occurrences of checkNumTwo
initially, because they'll be counted.
Upvotes: 1