How to find specific digit in integer in Python? [duplicate] - python

This question already has answers here:
Check if a digit is present in a list of numbers
(3 answers)
Closed 4 years ago.
I need to write function which can check if there is a specific digit in some entered number.
def number(m):
while (m>0):
n=m%10
m = m/100
if n==2:
return True
return False
some_number = 223
number(some_number)
For example I'm searching for number 2. But with this code it returns True only if number 2 is on last place.
Thanks.

You should divide by 10 instead of 100 in your code.
Also as Tilman B. aka Nerdyyy mention, you can just convert the integer to str, and search using in opearator:
def number(m):
return '2' in str(m)

You are close. Why do steps of 100? Do instead steps of 10 using floor division , otherwise you'll miss some algorisms and your loop will be waaay deeper than it should (for example, for the number 123, your loop as of now would check 12.3, 1.23, 0.123, 0.0123, 0.00123...... until it is so small that its computationally 0 - You don't want that, because you'd just be adding more and more zeros to your m and a 2 would never show up anyway).
def number(m):
while (m>0):
n = m%10
m = m//10
if n==2:
return True
return False
Checking
>> print(number(1))
False
>> print(number(2))
True
>> print(number(13))
False
>> print(number(12))
True
>> print(number(21))
True
>> print(number(11))
False
>> print(number(121))
True

Related

How can I write this code so that I do not have to round the logarithm?

I was doing a programming challenge question where you need to found out if a given number (n) is equal to 3 raised to some exponent(x)
9 is True since 3^x -> 3^3 = 9
10 is False since no x for 3^x is equal to 10
my problem occurred when 243 was entered into my code, which returned a result of 4.999 repeating.
my solution was to simply add a round function, in which I arbitrarily decided on 5 decimal places, this solved the problem.
now another problem occurred when the input was 531440, this returns an x value of 11.999998287222695 which, according to the challenge, was false, but with my code returned a true since I rounded to the fifth decimal place. I then changed my round to 10 decimal places and this fixed the code.
I was wondering if there was a way to implement my solution without having to round, as I'm sure if I plugged in enough numbers eventually another one would need to round past >10 decimal places and cause my code to fail. Please see the code below.
import math as math
def isPowerOfThree(n):
print(math.log(n,3)) #this line prints the unrounded log result
print(round((math.log(n,3)),10)) #this line prints the rounded result
return n>0 and round((math.log(n,3)),10).is_integer()
n = 243
print(isPowerOfThree(n))
The 'trick' allowing to avoid problems with chosen precision is to round to an integer and then check if this exponent gives the required result. The code below implements this approach:
import math
def isPowerOfThree(N):
if 3**round(math.log(N,3)) == N:
return True
return False
N = 531440 # 243
print(isPowerOfThree(N)) # gives False
Another approach will be to check all powers of 3 against the target number:
def isPowerOfThree(N):
x = 1
while True:
n = 3**x
if n == N:
return True
elif n > N:
return False
x += 1
And here an approach detecting directly without the need to run multiple loop runs if a number is not a power of 3:
def isPowerOfThree(N):
while True:
N , r = divmod(N, 3)
if r != 0:
return False
if N == 1:
return True
P.S. the two last approaches provide code to what Karl Knechtel mentioned in his comment to the question.

How to check a specific digit in integer Python [duplicate]

This question already has answers here:
How to take the nth digit of a number in python
(7 answers)
Closed 8 months ago.
I want to check if there is a specific digit (let's say 8) in a specific integer (let's say 83) at a specific place (let's say second place). In this example, the answer is True. I wrote the following function :
def check_number(integer: int, digit: int, place: int) -> bool:
if str(integer)[::-1][place-1] == str(digit) :
return True
return False
I want to have the more optimized way (in terms of speed) to do it as possible. Is my algorithm good or is there is better ?
A more optimized (though slightly uglier) approach would be to iterate over the integer and use division along with the modulus to check each digit:
import math
def check_number(integer: int, digit: int, place: int) -> bool:
while place > 1:
integer = math.floor(integer / 10)
place -= 1
if integer == 0:
return False
if integer % 10 == digit:
return True
else:
return False
print(check_number(12345, 3, 3)) # True
print(check_number(12345, 1, 5)) # True
print(check_number(12345, 4, 1)) # False
In the above in order to "queue up" the digit to be checked, we iterate in a while loop and divide the input by 10 however many times is required to put the digit to be examined in place into the tens position. Then we check that value using the modulus. Should the input not have a digit in that place, we return false, and likewise we return false should the digit exist but not match the input.
Note that in general the above solution is preferable to a string based solution, because the overhead in creating and manipulating a string is fairly high, much higher than doing simple division of the input integer.

Python: What does 'and not' mean in this code [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 3 years ago.
This is the entire code. What does 'and not' mean in the code. I understand it to mean that only a number that will equal to 0 when the number modulus 2 is carried out.
That is if 10 is entered by the user, 2,4,6,8 will be sum to get 20.
the_max = int(input("Enter the upper limit:"))
the_sum = 0
extra = 0
for number in range(1,the_max):
if number%2 and not number%3:
the_sum = the_sum + number
else:
extra = extra + 1 # Line 1
print(the_sum) # Line 2
print(extra) # Line 3
It means that the number is not a multiple of 2 but a multiple of 3;
the if statement has two conditions:
number % 2
since the % returns the remainder of a a number divided by 2, it will return 0 on a multiple of 2 and will result in rejection of if condition.
and not number % 3
This means that we need both condition to be good. But with this one the not operand reverses it.
So this time any number % 3 in which number is a multiple of 3 will result in 0 and will be reversed to 1;
You're parsing it wrong. The correct interpretation is
if (number % 2 != 0) and (number % 3 == 0):
This code is taking shortcuts by omitting the explicit comparison to zero, since 0 evaluates to False in a boolean expression like this one, whereas any other integer value evaluates to True.
The second clause, thus, is given a not to flip its polarity. not (number % 3) is equivalent to (number % 3 == 0).

How can I test if a number is a square number in Python? [duplicate]

This question already has answers here:
Check if a number is a perfect square
(25 answers)
Closed 8 days ago.
My code is
if graph == square_grid and type(math.sqrt(nodes)) is not int:
print "Your netork can't have that number of nodes"
Of course this doesn't work because math.sqrt always returns a float. How can I do this?
One way is
int(math.sqrt(x)) ** 2 == x
Because math.sqrt always returns a float, you can use the built in is_integer method
def is_square(x):
answer = math.sqrt(x)
return answer.is_integer()
this will return True if x is a square and False if it's not
>>> is_square(25)
True
>>> is_square(14)
False
try:
math.sqrt(nodes) == int(math.sqrt(nodes))
Using pure maths (no libraries) a square number can be determined in Python as follows:
not n**0.5 % 1
As the square root of a square integer is an integer, this test uses modulo 1 equal to zero to test if the square root is an integer.
For example:
The following will print the first five square numbers:
for i in range(1, 26):
if not i**0.5 % 1:
print(i)
Output:
1
4
9
16
25

Checking to see if a number ends in 5?

I'm trying to define a function that takes 2 parameters, adds them up, and if the sum of the two parameters ends in 5, it reports a 2. If it doesn't end in 5, it returns 8.
Any ideas?
I was thinking of doing an if statement, but I'm confused as to how I would check if a number ends in 5( or is 5).
Thanks for your help, trying to teach myself how to program is so difficult yet so rewarding :)
Solution
My answer assumes you are checking integers (which seems pretty reasonable judging from your question):
def sum_ends_with_5(a, b):
"""
Checks if sum ends with "5" digit.
"""
result = a + b
return 2 if result % 10 == 5 else 8
or more flexible (with any number of arguments):
def sum_ends_with_5(*args):
"""
Checks if sum ends with "5" digit.
"""
result = sum(args)
return 2 if result % 10 == 5 else 8
How it works (aka tests)
The function behaves like that:
>>> sum_ends_with_5(5)
2
>>> sum_ends_with_5(3)
8
>>> sum_ends_with_5(2, 8)
8
>>> sum_ends_with_5(7, 8)
2
>>> sum_ends_with_5(10, 20, 3, 2)
2
Shorter version
So, if you want to write it in shorter and more flexible way, you can do this:
def sum_ends_with_5(*args):
return 2 if sum(args) % 10 == 5 else 8
Take the modulus by 10 and check if it's 5.
print num % 10 == 5
Numbers end in 5 if and only if they are are divisible by 5 but are not divisible by 10. You can easily check for these conditions with modulo arithmetic. More generally, you can check if a number ends with a digit by comparing the mod 10 value of that number to the digit.
num = 1234
isDivisibleByFive = num % 10 == 5
One easy approach is to take the number and convert it to a string and check the last digit using indexing to see if it is 5:
E.g.,
n = 153
str(n)[-1] == '5':
False
and
n = 155
str(155)[-1] == '5'
True
So as part of an if-statement:
if str(n)[-1] == `5`:
print "number ends in 5"
else:
print "number did not end in 5"
If you just wanted to check for divisibility by 5 (which is different than ending with 5) you could use the mod operation.
But you also could mod by 10 and check for a remainder of 5 to determine if the number (int) ends with 5. My solution checks for the last digit of any number (including floats)
I like the solution from Tadeck best but there is another way, not as good in my opinion for this specific use case, but still may be useful if your return values ever need to follow more complex rules than is available from a simple modulo operation.
def xlatVal (*nums):
# 0 1 2 3 4 5 6 7 8 9
lookupTbl = [8,8,8,8,8,2,8,8,8,8]
return lookupTbl[sum(nums) % 10]
While the values are still reduced to a range using modulo, this allows arbitrary translations across that range.
Convert it to a string and check the last character:
str(num)[-1] == "5"

Categories