Skip to content

Commit e7e2506

Browse files
committed
feat (day 10): add squares_with_three counter with optimal generator solution
1 parent 579ece9 commit e7e2506

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
3 Strikes
3+
Given an integer between 1 and 10,000, return a count of how many numbers from 1 up to that integer whose square contains at least one digit 3.
4+
5+
6+
O/P : ==>
7+
8+
squares_with_three(1) should return 0.
9+
"""
10+
11+
def squares_with_three(n):
12+
count = 0
13+
14+
for i in range(1, n+1):
15+
num = i ** 2
16+
if '3' in str(num):
17+
count += 1
18+
return count
19+
20+
21+
# Optimal Optimization
22+
# If the code ever need to be optimized and slightly faster for large n,
23+
# we could avoid recomputing str(num) twice:
24+
25+
def squares_with_three_optimal(n):
26+
return sum('3' in str(i * i) for i in range(1,n+1))
27+
# This uses a generator expression and is just as readable.
28+
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import unittest
2+
from threeStrikes import squares_with_three
3+
4+
class threeStrikesTest(unittest.TestCase):
5+
6+
def test1(self):
7+
self.assertEqual(squares_with_three(1),0)
8+
9+
def test2(self):
10+
self.assertEqual(squares_with_three(10),1)
11+
12+
def test3(self):
13+
self.assertEqual(squares_with_three(100),19)
14+
15+
def test4(self):
16+
self.assertEqual(squares_with_three(1000),326)
17+
18+
def test5(self):
19+
self.assertEqual(squares_with_three(10000),4531)
20+
21+
22+
if __name__ == "__main__":
23+
unittest.main()

0 commit comments

Comments
 (0)