-
-
Save bbookman/1a98da47a1a6d1ceffdd3bae7be36abe to your computer and use it in GitHub Desktop.
''' | |
Find all of the numbers from 1-1000 that have a 3 in them | |
''' | |
three = [n for n in range(0,1000) if '3' in str(n)] | |
print(three) |
Hello,
because a string is an itterable object whereas an integer isn't. So to find if there is a 3 you have to itterate the number with "in" and this can only be done with a string.
Hope it helped.
We can write it without converting into str
print([i for i in range(1, 1000) if i % 10 == 3])
your answer is missing 171 numbers that has 3 in them which are:
[30, 31, 32, 34, 35, 36, 37, 38, 39, 130, 131, 132, 134, 135, 136, 137, 138, 139, 230, 231, 232, 234, 235, 236, 237, 238, 239, 300, 301, 302, 304, 305, 306, 307, 308, 309, 310, 311, 312, 314, 315, 316, 317, 318, 319, 320, 321, 322, 324, 325, 326, 327, 328, 329, 330, 331, 332, 334, 335, 336, 337, 338, 339, 340, 341, 342, 344, 345, 346, 347, 348, 349, 350, 351, 352, 354, 355, 356, 357, 358, 359, 360, 361, 362, 364, 365, 366, 367, 368, 369, 370, 371, 372, 374, 375, 376, 377, 378, 379, 380, 381, 382, 384, 385, 386, 387, 388, 389, 390, 391, 392, 394, 395, 396, 397, 398, 399, 430, 431, 432, 434, 435, 436, 437, 438, 439, 530, 531, 532, 534, 535, 536, 537, 538, 539, 630, 631, 632, 634, 635, 636, 637, 638, 639, 730, 731, 732, 734, 735, 736, 737, 738, 739, 830, 831, 832, 834, 835, 836, 837, 838, 839, 930, 931, 932, 934, 935, 936, 937, 938, 939].
so the condition i % 10 == 3 doesn't target all the numbers containing 3 in them.
I thought 'range(0,1000)' does not actually include 1000. Also wouldn't the first element of the range be zero instead of one?
I have found the following solution without using strings:
numbers=range(1,1001)
r=[i for i in numbers if i%10==3 or (i//10)%10==3 or ((i//10)//10)%10==3 or (((i//10)//10)//10)%10==3]
I think with the string option is better because is the simplest and that's the more legible solution, instead of you can write several conditions to get it without using strings. However, strings are a tool to use to and our goal should be make it easy.
These 3 options work:
x = [i for i in range(1, 1001) if str(i).find("3") != -1]
y = [i for i in range(1, 1001) if str(i).count("3") > 0]
z = [i for i in range(1, 1001) if '3' in str(i)]
print("x ->", x, len(x), "\n")
print("y ->", y, len(y), "\n")
print("z ->", z, len(z))
You could also do it this way:
lst_include3=list(filter(lambda x: '3' in str(x), range(1,1000)))
print(lst_include3)
solution = [a for a in range(1, 1000+1) if '3' in str(a)]
why written in string format if its a integer