How to check the given number is digit or not? - python

How can I check if a number is composed by a single digit?
Here is what I have tried so far:
n=5
def digit(n):
for i in [0,1,2,3,4,5,6,7,8,9]:
if ???
return True
else:
return False
The output in this case should be `True
`

I'm not saying it's the best way to do it, but it's probably what you meant to do:
def digit(n):
for i in [0,1,2,3,4,5,6,7,8,9]:
if n == i:
return True
else:
return False
digit(5)
Output:
True
Please pay attention that the else clause is not part of the if, but part of the for, which means that it will be executed only if the loop ended without any return or break during the iterations. You can also not use the else at all, and just return False after the loop.

You can simply do
def isdigit(n):
return n in range(10)

Related

Define a function in python which returns if the number is in the range say 1,000 to 10,000. But the catch is I have to do it in one line only

def RangeChecker(num):
if num in range(1000, 10001):
return True
return False
x = RangeChecker(500)
This is my code , how do I change the function to a single return statement ?
Simply return the condition itself as it evaluates to the exact boolean value you want to return:
def RangeChecker(num):
return num in range(...)
If you want to allow non-integers and understand "range" in a more natural language way, you could go with comparison operator chaining:
def RangeChecker(num):
return 1000 <= num <= 10000
Just rewrite your if to a single line with else:
def RangeChecker(num):
return True if num in range(1000, 100001) else False

How to find if there are 2 elements of same value consecutively in a list?

For example,
[1,3,3,5] should return True while [1,3,1,3] should return False.
I am looking for a simple solution using loops.
I tried the following:
def conseq(nums):
for i in range (len(nums)):
if nums[i]==nums[i+1]:
return True
break
else:
return False
The first time your function encounters 2 consecutive numbers which are different, it returns False. Returning from a function ends that function immediately, the function does not continue after that. This is also why the break is not necessary.
Another issue with your code is that once you reach the final number, nums[i + 1] will access out of the bounds of the array. That's why you should iterate over len(nums) - 1 rather than len(nums) - there's no reason to check the final number because there's nothing after it.
def conseq(nums):
for i in range(len(nums) - 1):
if nums[i]==nums[i+1]:
return True
# Only return False once we've exhausted all numbers.
# Since we didn't return True so far - it means there are
# no consecutive equal numbers, so we can safely return False
return False
the return ends the function, so here it will stop the processing as well
your true statement mostly works, and the break is unnecessary
you don't want the else statement until after the for loop ends (it returns False only if everything else has been parsed)
Also the way you parse through the code, nums can't access nums[i+1] when you're at the final nums so you need the range len(nums) - 1
If you feel like putting an else that does nothing, you can with a single semicolon or pass I believe, but the else is unnecessary here
def conseq(nums):
for i in range (len(nums)-1):
if nums[i]==nums[i+1]:
return True
else:
;
return False
You can't return False until the loop is done (since the match may be in the part of the list you haven't checked yet). And the break after return will never happen (since return ends the function and everything in it).
Enumerate list without last (to avoid try catch for i+1 being out of range) then compare each item with next one and return True if they are same. After loop return False because none are similar consequtively (returns break functions)
def function(number_list):
for i, item in enumerate(number_list[:-1]):
if item == number_list[i+1]:
return True
return False
def conseq(nums):
for i in range (len(nums)):
if nums[i]==nums[i-1]:
return True
return False
I modified your Code. Please check and let know if useful
def conseq(nums):
flag=True
for i in range (len(nums)-1):
if nums[i]==nums[i+1]:
print(True)
flag=False
break
else:
continue
if(flag):
print(False)
nums=[1,3,3,5]
nums1=[1,3,1,3]
conseq(nums)
conseq(nums1)
We have many solutions here already. I have tried out using numpy without a loop:
>>> import numpy as np
>>> f = np.array([1,3,3,5])
>>> (np.where(np.diff(f) == 0)[0]).astype('bool')[0] #check if we have any difference of two elements 0?
True

Beginner Python user Boolean Query

CodeAcademy's Python course is running me through loop functions and I don't understand an outcome. The goal is to see if a list is a mirror of the other list. i.e. [1,2,3] to [3,2,1]
After 20 minutes I looked at the solution and I don't understand why this does not return True every time?:
def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if lst1[index] != lst2[len(lst2)-1-index]:
return False
return True
The "return True" is indented to the same level as "for index", which would override any value returned from the prior line.
Alternatively, when I introduce an "else" at the "if" indentation, everything returns True:
def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if lst1[index] != lst2[len(lst2)-1-index]:
return False
else:
return True
Can anyone help a noob?
The return False causes the function to exit completely while returning False, so the return True line is never reached in that case. Placing an early return statement is a way of interrupting function execution
If your statement if lst1[index] != lst2[len(lst2)-1-index] statement finds any items that do not match, our function will end right at that moment. No more code will be executed.
When you add that else statement, it means that if there are any items that do match, the function will return True and no more code will be executed.
The first and the second code you proposed give different outputs.
And you should know that functions can use return only once.
What helps is to print out intermediate results.
1
def reversed_list(lst1, lst2):
for index in range(len(lst1)):
print(index)
if lst1[index] != lst2[len(lst2)-1-index]:
print('False')
return False
print('True')
return True
2
def reversed_list(lst1, lst2):
for index in range(len(lst1)):
print(index)
if lst1[index] != lst2[len(lst2)-1-index]:
print('False')
return False
else:
print('True')
return True
Run my code with the added lines that prints you intermediate results. You will see that the second function will only iterate over the first element and then return either True or False.
In the first case return True is the end of your function. You have to iterate through the whole range(len(lst1)) in order to reach it. So if the condition of the ifin the loop is matched, the return False statement is executed and the function ends there.
In your second case, you never iterate through the whole list. At the first iteration, you check the condition lst1[index] != lst2[len(lst2)-1-index] where index = 0 and return a True or a False.

Recursively checking for odd or even

In this code:
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_even(2))
print(is_odd(2))
I keep going through this in my head and wondering how it's working. It seems to me that eventually x in is_even(x) will return True every time. However, when I run the code, it works perfectly fine and returns True and False appropriately. Can someone explain how that's happening?
I understand the basic concept of recursion and fully understand how the famous factorial example works. However, this one is hard for me to wrap my head around.
Feeling inept right now...
It always helps to decompose a recurrence relation till you find its base case.
is_even(2) => return is_odd(1)
=> return not is_even(1)
=> return not is_odd(0)
=> return not not is_even(0)
=> return not not True
=> return True ---- (1)
is_odd(2) => return not is_even(2)
=> return not True [from (1)]
=> return False
In general, from your recurrence functions, it is easy to observe that is_even(n) will return [not not not ... n times] True, while is_odd(n) will return [not not not ... n - 1 times] True. So the number of nots and hence the final expression depend on n (aha!). Well, that's certainly a roundabout way of asking whether
n % 2 == 0
Add a couple of print statements and you will see what it is doing:
from __future__ import print_function
def is_even(x):
if x == 0:
print('True')
return True
else:
return is_odd(x-1)
def is_odd(x):
print('not', end=' ')
return not is_even(x)
>>> is_even(5)
not not not not not True
False
>>> is_odd(5)
not not not not not not True
True
Like in most cases it might be helpful to include simply prints to follow the execution:
def is_even(x):
print('check if {} is even'.format(x))
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
print('check if {} is odd'.format(x))
return not is_even(x)
Then in your cases:
>>> print(is_even(2))
check if 2 is even
check if 1 is odd
check if 1 is even
check if 0 is odd
check if 0 is even
True
>>> print(is_odd(2))
check if 2 is odd
check if 2 is even
check if 1 is odd
check if 1 is even
check if 0 is odd
check if 0 is even
False
So basically it decrements the number until it's 0. The point is just how many nots have been accumulated in the is_odd calls. If it's an even number of nots then the result will be True, otherwise False.
That's true; the recursion is supposed to end inside is_even.
And when that will happen, you'll know that the number you have is 0.
Now lets go backwards. This final state will be achieved by two cases - direct call to is_even(0) or a call from is_odd(0). In the first case - the result is all good. In the second - the result will be returned to the is_odd function, negated, and therefore will be falsy - giving a correct result.
Now, here the missing piece comes - the recursion: in order to reach this state, we need to decrease the argument each time, passing it through the opposite function - and that's exactly what we get with return is_odd(x-1).
Note: eventually this recursion leads to a chain of negations of the value True returned by the is_even. This chain is of length x where x is your number, and therefore odd or even in correspondence.
Therefore, the following code will do the same (lacking the is_odd nice side effect):
def is_even (x):
res = True
while x:
res = not res
x -= 1
return res
I think that all the other answers are great but potentially the easiest way to understand the problem is how many times the answer will get "not"ed. Every time it passes through the is_odd function a not will be added on to the final answer. True will always be returned but for even numbers, there will always be an even number of nots which cancel each other out, but for odd numbers they will always have an odd number of nots and therefore return false.

How can this behavior be acomplished? Python "short circuting" test

I have the following code:
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
for x in geodatabaseList:
if x == self.outputGeodatabase:
return True
else:
pass
return False
What i need to know the following: in case the if condition evaluates to true, will the function stop looking in the list and never return False? Or do i need a break statement?
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
for x in geodatabaseList:
if x == self.outputGeodatabase:
return True
break
else:
pass
return False
If the following code does not solve my problem, what can i use to do simulate that behavior?
Thanks
return is the end of the line, and nothing else will happen in that function afterwards. On the other hand, you could rewrite your function as
def testGeodatabase(self):
return self.outputGeodatabase in self.gp.ListWorkspaces("*","ALL")
You don't need the break keyword in the code above. Actually, you don't need the
else:
pass
either. The
return True
will exit the function.
The return statement will indeed cause the function to be exited at that point. No further code is executed in the function.
Here is a simple test which you could run to prove the point:
def someFunction(nums):
for i in nums:
if i == 1:
return "Found 1!"
return "Never found 1"
And running it:
>>> someFunction([2])
'Never found 1'
>>> someFunction([2,1,3])
'Found 1!'
I think that using any() is the best choice:
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
return any(x == self.outputGeodatabase for x in geodatabaseList)

Categories

Resources