Проблема с ошибкой IndexError: list index out of range

big lil

Новичок
Пользователь
Авг 19, 2020
6
0
1
Пытался написать программу для вычисления скалярного произведения двух векторов. Загуглил как искать, и написал вот такой код. Выдаёт указанную в названии ошибку. Много раз пытался что-то изменить, но ничего не помогает. Версия питона 3.8.5

Python:
vectorOne = str(input('enter the coordinates of the first vektor: '))
vectorTwo = str(input('enter the coordinates of the second vektor: '))
while len(vectorOne.split()) != len(vectorTwo.split()):
    print()
    print('vectors mast have the same number of parameters!')
    vectorOne = str(input('enter the coordinates of the first vektor: '))
    vectorTwo = str(input('enter the coordinates of the second vektor: '))

amountParameter = int(len(vectorOne))
def scalar(vectorOne,vectorTwo,amountParameter):
    amountParameter -=1
    if amountParameter == -1:
        return 0
    else:
        return int(vectorOne.split()[amountParameter])*int(vectorTwo.split()[amountParameter])+scalar(vectorOne,vectorTwo,int(amountParameter))


print(scalar(vectorOne,vectorTwo,int(amountParameter)))
input()
 

alext

Популярный
Пользователь
Май 10, 2020
288
66
28
1. str() вокруг input можно убрать, input и так возвращает строку.
2. int вокруг len(vektorOne) можно убрать, len и так возвращает число.
3. int вокруг amountParameter можно убрать, потому что он уже заинтован до этого.
4.
Python:
while ...
    vectorOne = str(input('enter the coordinates of the first vektor: '))
    ...
amountParameter = int(len(vectorOne))
Этот код записывает в amountParameter длину введенной строки, а не размерность вектора.
Если введено "42 42", то в amountParameter лежит 5, и при выполнении строки vectorOne.split()[amountParameter] получается, что ты пытаешься достать пятый элемент списка из двух элементов - ['42', '42'][5]. Разумеется, вылетает ошибка. Дели на составляющие до вычисления длины.

Python:
while True:
    vectorOne = input('enter the coordinates of the first vector: ').split()
    vectorTwo = input('enter the coordinates of the second vector: ').split()
    if len(vectorOne) == len(vectorTwo):
        break
    else:
        print('vectors mast have the same number of parameters!')
        continue

vec1 = map(int, vektorOne)
vec2 = map(int, vektorTwo)
scalar = sum(x * y for x, y in zip(vec1, vec2))
 
  • Мне нравится
Реакции: big lil

big lil

Новичок
Пользователь
Авг 19, 2020
6
0
1
1. str() вокруг input можно убрать, input и так возвращает строку.
2. int вокруг len(vektorOne) можно убрать, len и так возвращает число.
3. int вокруг amountParameter можно убрать, потому что он уже заинтован до этого.
4.
Python:
while ...
    vectorOne = str(input('enter the coordinates of the first vektor: '))
    ...
amountParameter = int(len(vectorOne))
Этот код записывает в amountParameter длину введенной строки, а не размерность вектора.
Если введено "42 42", то в amountParameter лежит 5, и при выполнении строки vectorOne.split()[amountParameter] получается, что ты пытаешься достать пятый элемент списка из двух элементов - ['42', '42'][5]. Разумеется, вылетает ошибка. Дели на составляющие до вычисления длины.

Python:
while True:
    vectorOne = input('enter the coordinates of the first vector: ').split()
    vectorTwo = input('enter the coordinates of the second vector: ').split()
    if len(vectorOne) == len(vectorTwo):
        break
    else:
        print('vectors mast have the same number of parameters!')
        continue

vec1 = map(int, vektorOne)
vec2 = map(int, vektorTwo)
scalar = sum(zip(vec1, vec2))
спасибо
 

Форум IT Специалистов