4
Problem: The user enters an X number, and a function must check whether two numbers summed within a list, content elements that can be ' ' or integers, results in the user’s X number.
My job:
# Tentei fazer 2 laços fors, para percorrer a soma da lst[0] com os outros, da lst[1] com os outros, etc.
def plus_element(num, lst):
i1 = 0
i2 = 0
for i in range(len(lst)):
for j in range(len(lst)):
if isinstance(lst[i1], int) and isinstance(lst[i2], int):
if lst[i1] + lst[i2] == num:
print(f'{lst[i1]} + {lst[i2]} é igual ao número {num}.')
return
i1 += 1
if isinstance(lst[i1], int) and isinstance(lst[i2], int):
if lst[i1] + lst[i2] == num:
print(f'{lst[i1]} + {lst[i2]} é igual ao número {num}.')
return
i2 += 1
The mistake I’m having is that if the list has more than 2 numbers, the function gives error.
# Minha lista
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '
', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '
', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 5, 2, 10]
The error it presents:
IndexError: list index out of range
Would anyone know to help me? Thanks for your attention.
Thank you very much! I managed to understand this logic, it is much simpler than I thought.
– Pedro Barretto