Count Perfect Squares
Count perfect square numbers in array.
IntermediatePhase 4 - Level 2: Searching & Counting LogicExample 10 of 10
count-perfect-squares.py
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
What's going on
Check if number is perfect square.
Key Concepts:
Calculate square root
Check if root * root == num
Count matching elements
🔗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