有了这个代码,我所要做的就是在奇数之间插入破折号,在偶数之间插入一个星号。它不能对每个输入都正确工作。它与46879一起工作,但返回None与468799,或不插入*之间的4和6与4546793。它为什么这么做?谢谢
def DashInsertII(num):
num_str = str(num)
flag_even=False
flag_odd=False
new_str = ''
for i in num_str:
n = int(i)
if n % 2 == 0:
flag_even = True
else:
flag_even = False
if n % 2 != 0:
flag_odd = True
else:
flag_odd = False
new_str = new_str + i
ind = num_str.index(i)
if ind < len(num_str) - 1:
m = int(num_str[ind+1])
if flag_even:
if m % 2 == 0:
new_str = new_str + '*'
else:
if m % 2 != 0:
new_str = new_str + '-'
else:
return new_str
print DashInsertII(raw_input())
如果我理解你的问题-为了
11223344
你需要1-12*23-34*4
您的函数定义是我最近看到的最过度构建的函数之一;下面的函数应该可以满足您的需要,而不必考虑复杂性。在
编辑:我刚刚重读了这个问题,发现我误解了您想要的,即在两个奇数之间插入
-
,在两个偶数之间插入*
。为此,我能想出的最佳解决方案是使用正则表达式。在第二次编辑:根据alvits的请求,我在这篇文章中包含了对正则表达式的解释。在
^{pr2}$如果这仍然不是你真正想要的,请对此发表评论让我知道。在
RevanProdigalKnight的答案几乎是正确的,但是当3个或更多的偶数/奇数出现在一起时,这个答案就失败了。在
使用regex进行此操作的正确方法是使用肯定的lookahead(使用?=). 在
这将产生:
^{pr2}$相关问题 更多 >
编程相关推荐