Python不接受某些数字输入

2024-10-01 11:37:11 发布

您现在位置:Python中文网/ 问答频道 /正文

有了这个代码,我所要做的就是在奇数之间插入破折号,在偶数之间插入一个星号。它不能对每个输入都正确工作。它与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()) 

Tags: 代码falsetruenewifelsenumint
3条回答

如果我理解你的问题-为了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())

您的函数定义是我最近看到的最过度构建的函数之一;下面的函数应该可以满足您的需要,而不必考虑复杂性。在

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的请求,我在这篇文章中包含了对正则表达式的解释。在

^{pr2}$

如果这仍然不是你真正想要的,请对此发表评论让我知道。在

RevanProdigalKnight的答案几乎是正确的,但是当3个或更多的偶数/奇数出现在一起时,这个答案就失败了。在

使用regex进行此操作的正确方法是使用肯定的lookahead(使用?=). 在

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)

这将产生:

^{pr2}$

相关问题 更多 >