确定输入是偶数还是奇数

2024-09-29 22:25:27 发布

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

你好,我试图用python编写一个程序,要求用户输入一组1和0的数字,我希望程序告诉我,如果我有偶数个零,或奇数个零,或根本没有零。谢谢你的帮助!!在

forstate = "start"
curstate = "start"
trans = "none"
value = 0


print "Former state....:", forstate
print "Transition....:", trans
print "Current state....", curstate
    while curstate != "You hav and even number of zeros":
        trans = raw_input("Input a 1 or a 0: ")
        if trans == "0" and value <2:
            value = value + 1
            forstate = curstate
        elif trans == "1" and value < 2:
            value = value + 0
            forstate = curstate
        curstate = str(value) + "  zeros"
        if value >= 2:
            curstate = "You have and even number of zeros"
        print "former state ...:", forstate
        print "Transition .....:", trans
        print "Current state....", curstate

Tags: and程序younumbertransvaluezeroscurrent
3条回答

听起来像是家庭作业,或者更糟的是面试问题,但这会让你开始。在

def homework(s):
 counter = 0
 if '0' in s:
   for i in s:
     if i == '0':
       counter = counter + 1
 return counter

别忘了这部分

^{pr2}$

如果你打电话给家庭作业并给它一个数字串,它会给你回0的数字

homework('101110101')

现在你知道了有多少个0需要用这个号码来打奇数或偶数

odd_or_even_or_none(23)

所以解决方案是这样的

txt = input('Feed me numbers:  ')
counter = str( homework(txt) )
print odd_or_even_or_none(counter)
try:
    inp = raw_input
except NameError:
    inp = input

zeros = sum(ch=='0' for ch in inp('Can I take your order? '))

if not zeros:
    print "none"
elif zeros%2:
    print "odd"
else:
    print "even"

看起来你在做一个有限状态机?在

try:
    inp = raw_input
except NameError:
    inp = input

def getInt(msg):
    while True:
        try:
            return int(inp(msg))
        except ValueError:
            pass

START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str  = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']

state = START
while True:
    num = getInt('Enter a number (-1 to exit)')

    if num==-1:
        break
    elif num==0:
        state = state_next[state]

    print 'I have seen {0}.'.format(state_str[state])

编辑:

^{pr2}$

相关问题 更多 >

    热门问题