What about :
sum(map(lambda x:x*x,l))
we also use reduce
:
print reduce(lambda x,y: x+y*y,l) # as pointed by @espang reduce(lambda x,y: x+y*y,l) is only ok, when the first value is 1 (because 1*1 == 1). The first value is not squared
We can take the first element, get its square, then add it to the head of the list so we can make sure that it’s squared. Then we continue using reduce. It isn’t worth all that work, as we have better alternatives.
reduce(lambda x,y: x+y*y,[l[:1][0]**2]+l[1:])
Just out of curiosity, I tried to compare the three solutions to sum the squares of 10000
numbers generated by range
, and compute the execution time of every operation.
l=range(10000)
from datetime import datetime
start_time = datetime.now()
print reduce(lambda x,y: x+y*y,l)
print('using Reduce numbers: {}'.format(datetime.now() - start_time))
from datetime import datetime
start_time = datetime.now()
print sum(map(lambda x:x*x,l))
print('Sum after map square operation: {}'.format(datetime.now() - start_time))
from datetime import datetime
start_time = datetime.now()
print sum( i*i for i in l)
print('using list comprehension to sum: {}'.format(datetime.now() - start_time))
Output:
Using list comprehension
is faster
333283335000
using Reduce numbers: 0:00:00.003371
333283335000
Sum after map square operation: 0:00:00.002044
333283335000
using list comprehension to sum: 0:00:00.000916
Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding sum of squares of list in just one line. Let’s discuss certain ways in which this can be performed.
Method #1 : Using reduce() + lambda The power of lambda functions to perform lengthy tasks in just one line, allows it combined with reduce which is used to accumulate the subproblem, to perform this task as well. Works with only Python 2.
Python
test_list
=
[
3
,
5
,
7
,
9
,
11
]
print
(
"The original list is : "
+
str
(test_list))
res
=
reduce
(
lambda
i, j: i
+
j
*
j, [test_list[:
1
][
0
]
*
*
2
]
+
test_list[
1
:])
print
(
"The sum of squares of list is : "
+
str
(res))
Output
The original list is : [3, 5, 7, 9, 11] The sum of squares of list is : 285
Time Complexity: The reduce function in this code has a time complexity of O(n), where n is the number of elements in the input list “test_list”. The lambda function used inside the reduce function takes constant time to execute, so the overall time complexity is O(n).
Auxiliary Space: The reduce function in this code has an auxiliary space complexity of O(1), as it only requires a single accumulator variable to store the intermediate and final results. The lambda function used inside the reduce function takes constant space, so the overall auxiliary space complexity is O(1).
Method #2 : Using map() + sum() The similar solution can also be obtained using the map function to integrate and sum function to perform the summation of the squared number.
Python3
test_list
=
[
3
,
5
,
7
,
9
,
11
]
print
(
"The original list is : "
+
str
(test_list))
res
=
sum
(
map
(
lambda
i: i
*
i, test_list))
print
(
"The sum of squares of list is : "
+
str
(res))
Output
The original list is : [3, 5, 7, 9, 11] The sum of squares of list is : 285
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #3 : Using for loop and math.pow()
Python3
test_list
=
[
3
,
5
,
7
,
9
,
11
]
print
(
"The original list is : "
+
str
(test_list))
res
=
0
for
i
in
test_list:
from
math
import
pow
res
+
=
pow
(i,
2
)
res
=
int
(res)
print
(
"The sum of squares of list is : "
+
str
(res))
Output
The original list is : [3, 5, 7, 9, 11] The sum of squares of list is : 285
Time Complexity: O(n), where n is the number of elements in the input list.
Auxiliary Space: O(1), as we are not using any additional data structure or creating any new list to store intermediate results.
Method #4 : Using simple list comprehension
Here is an approach using a list comprehension:
Python3
test_list
=
[
3
,
5
,
7
,
9
,
11
]
print
(
"The original list is : "
+
str
(test_list))
res
=
sum
([i
*
*
2
for
i
in
test_list])
print
(
"The sum of squares of list is : "
+
str
(res))
Output
The original list is : [3, 5, 7, 9, 11] The sum of squares of list is : 285
Time Complexity: O(n), where n is the length of the input list, as the list comprehension iterates over each element in the input list once.
Auxiliary Space: O(1), as the space used by the algorithm is constant and does not depend on the size of the input.
Method #5: Using numpy
Python3
import
numpy as np
test_list
=
np.array([
3
,
5
,
7
,
9
,
11
])
print
(
"The original list is : "
, test_list)
res
=
np.
sum
(np.square(test_list))
print
(
"The sum of squares of list is : "
, res)
Output:
The original list is : [3, 5, 7, 9, 11] The sum of squares of list is : 285
Time Complexity: O(N)
Auxiliary Space : O(1)
Approach using reduce() and operator.mul():
The reduce() function from the functools module is used to reduce the list to a single value by applying a given function to the elements of the list. The operator.mul() function from the operator module is used to multiply the squared element of the list. In this approach, we use reduce() and operator.mul() to calculate the sum of the squares of the elements in the input list.
Algorithm:
Import reduce() and operator.mul() functions from the respective modules.
Take the input list as input_list.
Use reduce() function with operator.mul() and map() function to calculate the sum of squares of input_list.
Print the result.
Python3
from
functools
import
reduce
import
operator
input_list
=
[
3
,
5
,
7
,
9
,
11
]
print
(
"The original list is : "
, input_list)
res
=
reduce
(operator.add,
map
(
lambda
x: x
*
x, input_list))
print
(
"The sum of squares of list is : "
, res)
Output
The original list is : [3, 5, 7, 9, 11] The sum of squares of list is : 285
Time complexity: The time complexity of this approach is O(n) because map() and reduce() function iterate over the input list once.
Auxiliary space: The space complexity of this approach is O(1) because we are not using any additional data structure or creating any new list to store intermediate results.
Last Updated :
02 May, 2023
Like Article
Save Article
Вопрос от пользователя:
найти сумму квадратов всех чисел от a до b значения a и b вводятся с клавиатуры в питоне для чайников
Подождите!
Не закрывайте страницу. Нейросеть пишет ответ. Он появится тут.
Этот ответ написан нейросетью.
Искуственный интеллект во многом преуспевает, но в некоторых областях может давать неточные ответы.
Если вам не понравился ответ, попробуйте задать его более развёрнуто и конкретно, используя точные параметры.
Ответ нейросети:
Для решения задачи необходимо написать программу на языке Python, которая будет запрашивать у пользователя значения переменных a и b, а затем вычислять сумму квадратов всех чисел от a до b.
Для начала, необходимо подключить встроенную функцию в Python — range(), которая генерирует последовательность чисел. Затем, в цикле for можно пройти от начального значения a до конечного b и для каждого числа выполнить возведение в квадрат. После этого, посчитать итоговую сумму квадратов всех чисел. В таком случае код будет выглядеть следующим образом:
«`
# запрашиваем данные у пользователя и преобразуем их к целочисленному типу
a = int(input(«Введите начальное число: «))
b = int(input(«Введите конечное число: «))
# объявляем переменную для подсчета суммы квадратов чисел
sum_of_squares = 0
# проходим циклом for от начального числа a до конечного числа b включительно
for i in range(a, b + 1):
# возводим число в квадрат и прибавляем к сумме
sum_of_squares += i ** 2
# выводим результат на экран
print(«Сумма квадратов всех чисел от», a, «до», b, «равна», sum_of_squares)
«`
В данном коде мы запрашиваем у пользователя значения a и b, преобразуем их к целочисленному типу, объявляем переменную sum_of_squares для подсчета суммы квадратов чисел и начинаем цикл for. В цикле мы проходим от начального значения a до конечного b, возводим каждое число в квадрат и прибавляем его к сумме sum_of_squares. После того, как все числа будут перебраны, на экран выводится результат в виде текстового сообщения.
В целом, программа будет работать надежно, но стоит учесть некоторые ограничения, связанные с типом данных int. Например, если пользователь введет очень большие значения для переменных a и b, то результат возведения в квадрат может превысить максимально допустимое значение для типа int. Также, если пользователь введет некорректные данные (например, нечисловые значения), то возможны ошибки при выполнении программы.
⚠️Зарепортить пост!
Чтобы оставить комментарий, необходимо авторизоваться.
Задай любой вопрос нейросети!
она справится с любой поставленной задачей быстрее чем поиск в Яндекс.
Последние вопросы
(c) ChatGPT по русски 2023. Все права защищены. При обнаружении неправомерного контента пишите на [email protected]
0 / 0 / 0 Регистрация: 31.03.2020 Сообщений: 51 |
|
1 |
|
Найти сумму квадратов всех элементов списка22.09.2020, 15:11. Показов 18963. Ответов 3
То-есть для списка [ 1, 2, 3] это будет 1*1 + 2*2 + 3*3 = 14
0 |
Gdez 7259 / 4048 / 1780 Регистрация: 27.03.2020 Сообщений: 6,875 |
||||
22.09.2020, 15:31 |
2 |
|||
0 |
TaxomaSpirin 0 / 0 / 0 Регистрация: 12.03.2021 Сообщений: 1 |
||||
12.03.2021, 15:19 |
3 |
|||
0 |
gray621 36 / 51 / 11 Регистрация: 14.01.2021 Сообщений: 406 |
||||||||
12.03.2021, 17:21 |
4 |
|||||||
Twenty228,
либо
1 |
Введение
В этом разделе мы изучим код Python для вычисления суммы квадратов n натуральных чисел, предоставленных пользователем.
Математическое выражение: (n * (n + 1) * (2 * n + 1)) // 6
суррогатного материнства
def sum_square(n): sum = 0 # Математическое выражение sum = (n*(n+1) * (2*n + 1))//6 print(sum) n = int(input("Пожалуйста, введите число: ")) сумма_квадрат(n)
Результат
объяснение
В приведенной выше программе мы создали переменную n для хранения пользовательского ввода. Функция sum_square() вычисляет сумму квадратов n натуральных чисел с помощью математического выражения, а вывод отображается с помощью функции print().