Please let me know what is the error here:
numbers = [3,11,17,25,28,30,35,32,46,65,97,72,45,22,14,150]
def fizz_buzz(numbers):
for i,num in enumerate(numbers,start=10):
if num%3==0:
numbers[i] = 'fizz'
if num%5==0:
numbers[i]= 'buzz'
if num%3==0 and num%5==0:
numbers[i]= 'fizzbuzz'
else:
continue
return numbers
print(fizz_buzz(numbers))
Output:
numbers[i]= 'buzz'
IndexError: list assignment index out of range
You start with index 10
for i,num in enumerate(numbers,start=10):
So you are accessing the array numbers[16]
in the 7th iteration which is out of range.
Your array has 16 elements and since array indexing is 0 based, the last element will be numbers[15] and not numbers[16] and your programs is trying to execute numbers[16] so it is getting index out of range error.
Give a check to your function like below:
numbers = [3,11,17,25,28,30,35,32,46,65,97,72,45,22,14,150]
def fizz_buzz(numbers):
for i,num in enumerate(numbers,start=10):
if i < len(numbers):
if num%3==0:
numbers[i] = 'fizz'
if num%5==0:
numbers[i]= 'buzz'
if num%3==0 and num%5==0:
numbers[i]= 'fizzbuzz'
else:
continue
return numbers
print(fizz_buzz(numbers))
To achieve the following output:
[(10,3),(11,11),(12,17),(13,25),(14,28), and so on].
It can be the following:
numbers = [3,11,17,25,28,30,35,32,46,65,97,72,45,22,14,150]
def fizz_buzz(numbers):
result = []
for i,num in enumerate(numbers):
if num%3==0 and num%5==0:
result.append((i+10, 'fizzbuzz'))
elif num%3==0:
result.append((i+10, 'fizz'))
elif num%5==0:
result.append((i+10, 'buzz'))
else:
result.append((i+10, num))
return result
print(fizz_buzz(numbers))
# [(10, 'fizz'), (11, 11), (12, 17), (13, 'buzz'), (14, 28), (15, 'fizzbuzz'), (16, 'buzz'), (17, 32), (18, 46), (19, 'buzz'), (20, 97), (21, 'fizz'), (22, 'fizzbuzz'), (23, 22), (24, 14), (25, 'fizzbuzz')]
If you want the answer without fizz/buzz words, do the following:
numbers = [3,11,17,25,28,30,35,32,46,65,97,72,45,22,14,150]
numbers = [(i+10, num) for i, num in enumerate(numbers)]
print(numbers)
# [(10, 3), (11, 11), (12, 17), (13, 25), (14, 28), (15, 30), (16, 35), (17, 32), (18, 46), (19, 65), (20, 97), (21, 72), (22, 45), (23, 22), (24, 14), (25, 150)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.