Monday 28 December 2020

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

 This is a Python Program to create a list of of all numbers in a range which are perfect squares and the sum of the digits of the number is less than 10.

Problem Description

The program takes a range and creates a list of all numbers in the range which are perfect squares and the sum of the digits is less than 10.

Problem Solution

1. User must enter the upper and lower range for the numbers.
2. A list must be created using list comprehension where the element is a perfect square within the range and the sum of the digits of the number is less than 10.
3. This list must then be printed.
4. Exit.

Program/Source Code

Here is source code of the Python Program to create a list of of all numbers in a range which are perfect squares and the sum of the digits of the number is less than 10. The program output is also shown below.

l=int(input("Enter lower range: "))
u=int(input("Enter upper range: "))
a=[]
a=[x for x in range(l,u+1) if (int(x**0.5))**2==x and sum(list(map(int,str(x))))<10]
print(a)
Program Explanation

1. User must enter the upper and lower range for the numbers.
2. List comprehension must be used to create a list of numbers which are perfect squares and sum of the digits is less than 10.
3. The second part of the list comprehension first maps separate digits of the number into a list and finds the sum of the elements in the list.
3. The list which is created is printed.

Runtime Test Cases
 
Case 1:
Enter lower range: 1
Enter upper range: 40
[1, 4, 9, 16, 25, 36]
 
Case 2:
Enter lower range: 50
Enter upper range: 100
[81, 100]

No comments:

Post a Comment