使用这段代码,我所要做的就是在奇数之间插入一个破折号,在偶数之间插入一个星号。它并不是对每个输入都能正常工作。它适用于,例如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())
发布于 2014-07-07 20:27:02
你的函数定义是我在一段时间内见过的最过度构建的函数之一;下面的函数应该做你想做的事情,消除复杂性。
def DashInsertII(num):
num_str = str(num)
new_str = ''
for i in num_str:
n = int(i)
if n % 2 == 0:
new_str += i + '*'
else:
new_str += i + '-'
return new_str
print DashInsertII(raw_input())
编辑:我只是重新读了一下问题,发现我误解了你想要的东西,那就是在两个奇数之间插入一个-
,在两个偶数之间插入一个*
。为此,我能想到的最好的解决方案是使用正则表达式。
第二次编辑:根据alvits的要求,我在这里包含了对正则表达式的解释。
import re
def DashInsertII(num):
num_str = str(num)
# r'([02468])([02468])' performs capturing matches on two even numbers
# that are next to each other
# r'\1*\2' is a string consisting of the first match ([02468]) followed
# by an asterisk ('*') and the second match ([02468])
# example input: 48 [A representation of what happens inside re.sub()]
# r'([02468])([02468])' <- 48 = r'( \1 : 4 )( \2 : 8 )'
# r'\1*\2' <- {\1 : 4, \2 : 8} = r'4*8'
num_str = re.sub(r'([02468])([02468])',r'\1*\2',num_str)
# This statement is much like the previous, but it matches on odd pairs
# of numbers
num_str = re.sub(r'([13579])([13579])',r'\1-\2',num_str)
return num_str
print DashInsertII(raw_input())
如果这仍然不是你真正想要的,请对此发表评论,让我知道。
发布于 2016-04-29 04:54:48
RevanProdigalKnight的答案几乎是正确的,但当3个或更多的偶数/奇数放在一起时就会失败。
使用正则表达式的正确方法是使用正向先行(使用?=)。
def insert_right_way(num):
#your code here
num_str = str(num)
num_str = re.sub(r'([13579])(?=[13579])', r'\1-', num_str)
num_str = re.sub(r'([02468])(?=[02468])', r'\1*', num_str)
return num_str
def DashInsertII(num):
num_str = str(num)
num_str = re.sub(r'([02468])([02468])',r'\1*\2',num_str)
num_str = re.sub(r'([13579])([13579])',r'\1-\2',num_str)
return num_str
print insert_right_way(234467776667888)
print DashInsertII(234467776667888)
这将输出:
234*4*67-7-76*6*678*8*8 ( what is desired)
234*467-776*6678*88 ( not what we wanted)
发布于 2014-07-07 20:39:28
如果我理解您的问题-对于11223344
,您需要1-12*23-34*4
def DashInsertII(num):
prev_even = ( int(num[0])%2 == 0 )
result = num[0]
for i in num[1:]:
curr_even = (int(i)%2 == 0)
if prev_even and curr_even:
result += '*'
elif not prev_even and not curr_even:
result += '-'
result += i
prev_even = curr_even
return result
print DashInsertII(raw_input())
https://stackoverflow.com/questions/24619098
复制相似问题