I am beginner in python and I am working on one problem which I am not able to solve.
What I am supposed to do: create a list of tuples with prime numbers, the range is two numbers(which are also prime numbers) and the tuples in that list are supposed to contain only 2 prime numbers p and p+2
For example : given range (11, 31) returned list = [(11, 13), (17, 19), (29, 31)]
This is my code
def twin_primes(a: int, b:int) -> List[Tuple[int, int]]:
list_primes = []
list_final = []
for val in range (a, b+1):
if val > 1 :
for n in range(2, val):
if (val % n) == 0:
break
else:
list_primes.append(val)
for val in list_primes:
print(val)
list_final.append((list_primes[val], list_primes[val + 2]))
return list_final
print(twin_primes(11,31))
in the first for cycle I determine which numbers in that range are prime and append them to list_primes
in the second for cycle I tried to take the prime numbers from list_primes
and append them as tuples into list_final
it tells me this:
list_final.append((list_primes[val], list_primes[val + 2]))
IndexError: list index out of range*
could someone please help me with this? I think I understand that error but I don't know how to fix the code so it just takes the p
, p+2
into one tuple and then it would take another pair and so on... also it has to ignore 23 even though it is prime number.
Your logic for iterating over the twins is incorrect. val
is set to the element in the list itself, not the index. You're treating it as if it were an index. You need to iterate over a range of numbers, not the elements themselves. I suggest using a range with a step of 2.
list_primes = []
list_final = []
for val in range (a, b+1):
if val > 1 :
for n in range(2, val):
if (val % n) == 0:
break
else:
list_primes.append(val)
for i in range(0, len(list_primes) - 1, 2):
list_final.append((list_primes[i], list_primes[i + 1]))
return list_final
This produces [(11, 13), (17, 19), (23, 29)]
when a = 11
and b = 31
.
But your logic still requires some tweaking since this produces [(53, 59), (61, 67), (71, 73), (79, 83), (89, 97)]
when a = 50
and b = 100
, and obviously this is not correct.
val
is not an index into list_primes
, it's an element of it. You need to append a tuple containing val
and val+2
to list_final
, but only if val+2
is in the list of primes.
for val in list_primes:
if val+2 in list_primes:
list_final.append((val, val+2))
This can be improved using enumerate()
, since it will always be the case that val+2
will be the next prime if it exists.
for i, val in enumerate(list_primes[:-1]):
if list_primes[i+1] == val + 2:
list_final.append((val, val+2))
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.