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.
1# Helper function2def is_perfect_square(num):3 if num < 0:4 return False5 root = int(num ** 0.5)6 return root * root == num78# Take array9n = int(input("Enter array size: "))10arr = []11for i in range(n):12 arr.append(int(input(f"Element {i+1}: ")))1314# Count perfect squares15count = 016for element in arr:17 if is_perfect_square(element):18 count += 11920print(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
Return false for a negative candidate.
- 2
Compute an integer candidate root and square it.
- 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.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum