Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Perfect Squares

Count perfect-square entries in a list. Students reject negatives, verify an integer candidate root, and recognize the limits of floating-point square roots.

IntermediatePhase 4 - Level 2: Searching & Counting LogicExample 10 of 10
count-perfect-squares.py
1# Helper function
2def is_perfect_square(num):
3 if num < 0:
4 return False
5 root = int(num ** 0.5)
6 return root * root == num
7
8# Take array
9n = int(input("Enter array size: "))
10arr = []
11for i in range(n):
12 arr.append(int(input(f"Element {i+1}: ")))
13
14# Count perfect squares
15count = 0
16for element in arr:
17 if is_perfect_square(element):
18 count += 1
19
20print(f"Perfect squares: {count}")

Output

Enter array size: 5
Element 1: 4
Element 2: 5
Element 3: 9
Element 4: 16
Element 5: 20
Perfect squares: 3

In this one

  • Reject negative roots
  • Verify a candidate square
  • Recognize floating-root limits

How it works

  1. 1

    Return false for a negative candidate.

  2. 2

    Compute an integer candidate root and square it.

  3. 3

    Count array entries passing exact equality.

Edge cases

Does zero count?

Does zero count?

Yes. Its root is zero and zero squared is zero.

Are negative squares accepted?

Are negative squares accepted?

No. Negative inputs return false before root calculation.

What's going on

The helper rejects negatives before taking num ** 0.5. It converts that approximate root to an integer, then verifies root * root == num.

This equality check accepts zero and ordinary square examples while rejecting nearby nonsquares. Every matching list entry increments count, including duplicates. Very large integers can expose rounding or overflow in the floating-root approach; an integer-root method would be safer for that domain.

Does zero count? Yes. Its root is zero and zero squared is zero.

Are negative squares accepted? No. Negative inputs return false before root calculation.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why multiply the root back?

Pick an answer to check it.

Question 2

Does zero count?

Pick an answer to check it.

Questions people ask

Does zero count?

Yes. Its root is zero and zero squared is zero.

Are negative squares accepted?

No. Negative inputs return false before root calculation.

Why multiply the root back?

To verify that the candidate square exactly equals num.