我怎样才能找到一个号码是否在另一个号码及其在python中的位置?
示例:查找58是否在45896及其位置?
输出:True和2位
PS:有没有办法不调用字符串。只是数字?
答案 0 :(得分:8)
>>> x=str(45896)
>>> str(58) in x
True
>>> x.index(str('58')) + 1
2
答案 1 :(得分:3)
因为您要求的方法是不将值转换为字符串。 请注意,我没有针对所有可能的情况对此进行测试。所以你可能会发现错误。如果你这样做,请告诉我,以便我能解决这个问题。
def find_length(num):
# If number is 0, return the length as 1.
if num == 0:
return 1
length = 0
# Loop over the number by dividing it by 10
# and incrementing the length counter.
while num != 0:
length += 1
num /= 10
return length
def find_inside(num1, num2):
# Trivial case, when the numbers are same.
if num1 == num2:
return (True, 1)
len_n2 = find_length(num2)
place = find_length(num1)
# Iterate over the numbers, extracting the last
# n digits everytime, where n is length of num2
# Keep dividing the original number by 10 and
# decrementing place everytime.
while num1 != 0:
if num2 == (num1 % (10 ** len_n2)):
return (True, place - len_n2 + 1)
num1 /= 10
place -= 1
return (False, -1)
一些测试用例(Trivial):
>>> find_inside(10, 0)
(True, 2)
>>> find_inside(3456, 98)
(False, -1)
>>> find_inside(4589678, 58)
(True, 2)
>>> find_inside(10, 1)
(True, 1)
答案 2 :(得分:0)
使用re的另一种方式:
re.search('58','45896').start()+1
答案 3 :(得分:0)
一个班轮:
>>> x=45896
>>> y=58
>>> str(x).index(str(y))+1 if str(y) in str(x) else -1
2
>>>
替代方案(仅对长度使用str(...)
!):
x=45896
y=58
yLength = len(str(y)) #you need the size!
t = 10**yLength
found = "false"
position = 0
while x > 0:
position = position +1
if(x%t == y):
found = "true"
break
x = x/10
print found
print str(position - 1)
注意:您可以在不使用str(...)
的情况下轻松获取尺寸,但我会留下您编写该代码。
答案 4 :(得分:0)
如果你想要没有字符串的工作,你会喜欢这种方法:
import math
original = 45896
find = 58
org_dgt = int(math.log10(original))+1
fnd_dgt = int(math.log10(find))+1
count = 1
found = False
while not found:
curr_dgt = org_dgt-fnd_dgt
if curr_dgt < 0:
break
if int((original%(10**org_dgt))/(10**(curr_dgt))) == find:
found = True
break
org_dgt -= 1
count += 1
if found:
print count
else:
print 'Not Found'