Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10
When it is required to find all numbers in a range that are perfect squares and the sum of digits in the number is less than 10, list comprehension is used. A perfect square is a number that can be expressed as the product of an integer with itself.
Below is the demonstration of the same −
Example
lower_limit = 5
upper_limit = 50
numbers = []
numbers = [x for x in range(lower_limit, upper_limit + 1) if (int(x**0.5))**2 == x and sum(list(map(int, str(x)))) < 10]
print("The result is:")
print(numbers)
Output
The result is: [9, 16, 25, 36, 49]
How It Works
Let's break down the algorithm step by step ?
# Check if a number is perfect square
def is_perfect_square(n):
sqrt_n = int(n**0.5)
return sqrt_n * sqrt_n == n
# Calculate sum of digits
def sum_of_digits(n):
return sum(int(digit) for digit in str(n))
# Find numbers in range
lower = 1
upper = 100
result = []
for num in range(lower, upper + 1):
if is_perfect_square(num) and sum_of_digits(num) < 10:
result.append(num)
print("Perfect squares with digit sum < 10:")
print(result)
Perfect squares with digit sum < 10: [1, 4, 9, 16, 25, 36, 49, 64, 81]
Using List Comprehension
The same logic can be implemented more concisely using list comprehension ?
lower = 1
upper = 100
# One-liner using list comprehension
result = [x for x in range(lower, upper + 1)
if (int(x**0.5))**2 == x and sum(int(d) for d in str(x)) < 10]
print("Perfect squares with digit sum < 10:")
print(result)
# Let's also show the digit sums for verification
for num in result:
digit_sum = sum(int(d) for d in str(num))
print(f"{num}: digit sum = {digit_sum}")
Perfect squares with digit sum < 10: [1, 4, 9, 16, 25, 36, 49, 64, 81] 1: digit sum = 1 4: digit sum = 4 9: digit sum = 9 16: digit sum = 7 25: digit sum = 7 36: digit sum = 9 49: digit sum = 13 64: digit sum = 10 81: digit sum = 9
Key Points
Perfect square check:
(int(x**0.5))**2 == xverifies if a number is a perfect squareDigit sum calculation:
sum(int(d) for d in str(x))converts number to string, then sums individual digitsList comprehension provides a concise way to filter numbers based on multiple conditions
The condition
< 10ensures only numbers with single-digit sum are included
Conclusion
This program efficiently finds perfect squares within a range where the sum of digits is less than 10 using list comprehension. The key is combining perfect square detection with digit sum calculation in a single filtering condition.
