I have created a function which checks if the number has any other digit other than 3 or 5, return false.
def isDecent[n]:
digits = list[map[int, str[n]]]
for digit in digits:
if digit != 3 or digit != 5: return False
return True
print[isDecent[5553334]]
But unfortunately it's not working! Can I know the problem?
asked Mar 7, 2014 at 13:40
5
It's always true that digit != 3
OR digit != 5
. So it will always return False.
Change the or
to and
.
Alternatively, check it as
if digit not in [3, 5]:
In fact, we don't need to convert the characters to ints just to check equality, and you could just do:
def isDecent[n]:
digits = str[n]
return all[digit in ["3", "5"] for digit in digits]
Or even digit in "35"
... but I think that's less readable.
Another option is to use sets:
def isDecent[n]:
return set[str[n]].issubset['35']
answered Mar 7, 2014 at 13:43
RemcoGerlichRemcoGerlich
29.6k5 gold badges63 silver badges78 bronze badges
5
Since the why part has been already answered, let me show you how to do this efficiently
def isDecent[n]:
return all[char in '35' for char in str[n]]
The sister version of the same
def isDecent[n]:
return not any[char not in '35' for char in str[n]]
answered Mar 7, 2014 at 13:48
thefourtheyethefourtheye
225k52 gold badges441 silver badges485 bronze badges
1
Your issue is that you are using an or
instead of an and
.
Just change your code to this :
def isDecent[n]:
digits = list[map[int, str[n]]]
for digit in digits:
if digit != 3 and digit != 5: return False
return True
print[isDecent[555333]]
And then everything works !
answered Mar 7, 2014 at 13:43
I suggest avoiding the conversion to a string:
def isDecent[n]:
if n == 0:
return False
while n:
if n % 10 not in [3, 5, ]:
return False
n //= 10
return True
answered Mar 7, 2014 at 13:48
tmr232tmr232
1,16115 silver badges22 bronze badges
2
You can use set:
d=str[55555333]
r=''.join[set[d]]
if r in '353':
print "Number contains 3 or 5"
answered Mar 7, 2014 at 13:50
venpavenpa
4,14819 silver badges23 bronze badges
4
Other's have shown the problem in your code, here's an alternative.
def isDecent[n]:
if not set[str[n]] - {'3','5','.'}:
return False
return True
It returns False
on if str[n] contains anything other than '3'
, '5'
or '.'
answered Mar 7, 2014 at 13:48
GuyGuy
6055 silver badges21 bronze badges
Another solution:
def isDecent[n]:
s = set[[ x for x in str[n]]]
if len[s] > 2:
return False
return [False,True]['3' in s and '5' in s]
for i in [5553334, 5553133, 111115, 33333555]:
print i, isDecent[i]
Output:
5553334 False
5553133 False
111115 False
5553335 True
answered Mar 7, 2014 at 13:50
James SapamJames Sapam
15.2k11 gold badges47 silver badges68 bronze badges
5