How can I see if a number contains certain digits?
numbers = [2349523234, 12345123, 12346671, 13246457, 134123431]
for number in numbers:
if (4 in number):
print(number + "True")
else:
print("False")
How can I see if a number contains certain digits?
numbers = [2349523234, 12345123, 12346671, 13246457, 134123431]
for number in numbers:
if (4 in number):
print(number + "True")
else:
print("False")
You would have to do string comparisons for this
for number in numbers:
if '4' in str(number):
print('{} True'.format(number))
else:
print('{} False'.format(number))
It isn't really meaningful to ask if the number 4
is "in" another number (unless you have some particular definition of "in" in mind)
You can convert the number to string and if you want to get the first number that has 4
in it you can use a generator expression within next
:
>>> next(i for i in numbers if '4' in str(i))
2349523234
Or you can use a list comprehension if you want to preserve the number that satisfy the condition:
expected_numbers=[i for i in numbers if '4' in str(i)]
But from a mathematical point of view you can generate all the digits using following function:
In [1]: def decomp(num):
...: while num:
...: yield num % 10
...: num = num // 10
Then you can do the following:
In [3]: numbers = [2349523234, 12345123, 12346671, 13246457, 134123431]
In [4]: [n for n in numbers if any(4==i for i in decomp(n))]
Out[4]: [2349523234, 12345123, 12346671, 13246457, 134123431]
number=[number for number in numbers if '4' in str(numbers)]
print(number)
Klist = []
count = 0
while count < 1000:
count += 1
Klist.append(count)
for k in Klist:
if '6' in str(k):
print(k)
You create the list and then iterate through the numbers but as a string.
© 2022 - 2024 — McMap. All rights reserved.