gpt4 book ai didi

Python 不接受一些数字输入

转载 作者:太空宇宙 更新时间:2023-11-03 13:43:48 24 4
gpt4 key购买 nike

使用这段代码,我要做的就是在奇数之间插入破折号,在偶数之间插入星号。它不能对每个输入都正常工作。它适用于,例如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())

最佳答案

您的函数定义是我一段时间以来看到的最过度构建的函数之一;以下应该做你想做的事情,没有复杂性。

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())

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

关于Python 不接受一些数字输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24619098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com