In: Computer Science
Try to debug it! (fixes needed are explained below)
########################################
##def primes_list_buggy(n):
## """
## input: n an integer > 1
## returns: list of all the primes up to and including n
## """
## # initialize primes list
## if i == 2:
## primes.append(2)
## # go through each elem of primes list
## for i in range(len(primes)):
## # go through each of 2...n
## for j in range(len(n)):
## # check if not divisible by elem of list
## if i%j != 0:
## primes.append(i)
#
#
## FIXES: --------------------------
## = invalid syntax, variable i unknown, variable primes
unknown
## can't apply 'len' to an int
## division by zero -> iterate through elems not indices
## -> iterate from 2 not 0
## forgot to return
## primes is empty list for n > 2
## n = 3 goes through loop once -> range to n+1 not n
## infinite loop -> append j not i
## -> list is getting modified as iterating over it!
## -> switch loops around
## n = 4 adds 4 -> need way to stop going once found a divisible
num
## -> use a flag
## --------------------------
def primes_list_buggy(n):
"""
## input: n an integer > 1
## returns: list of all the primes up to and including n
## """
# initialize primes list
if i == 2:
primes.append(2)
# go through each elem of primes list
for i in range(len(primes)):
# go through each of 2...n
for j in range(len(n)):
# check if not divisible by elem of list
if i%j != 0:
primes.append(i)
print(primes_list(2) )
print(primes_list(15) )
(a) Debug the program by using Python Programming Language.
PYTHON CODE
def primes_list(n):
# initialize primes list
primes = []
# go through each elem of primes list
for i in range(2, n+1):
#flag is used
flag = 0
# go through each of 2...i-1
for j in range(2,i):
# check if divisible by elem of list
if i%j == 0:
#if it is divisible then change flag as 1
flag = 1
break
if flag == 0:#if flag as 0, then append element in primes list
primes.append(i)
return primes
print(primes_list(2) )
print(primes_list(15) )
PYTHON CODE SCREENSHOT
OUTPUT SCREENSHOT