确定输入是偶数还是奇数

时间:2011-02-09 02:15:21

标签: 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

4 个答案:

答案 0 :(得分:0)

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

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

不要忘记这部分

def odd_or_even_or_none(num):
  if num == 0:
    return 'This string contains no zeros'
  if num % 2 == 0
    return 'This string contains an even amount of zeros'
  else:
    return 'This string contains an odd amount of zeros'

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

homework('101110101')

现在您知道需要多少0才能用该号码调用odd_or_even_or_none

odd_or_even_or_none(23)

所以解决方案看起来像这样

txt = input('Feed me numbers:  ')
counter = str( homework(txt) )
print odd_or_even_or_none(counter)

答案 1 :(得分:0)

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"

答案 2 :(得分:0)

看起来你正在尝试使用有限状态机吗?

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

修改

try:
    inp = raw_input
except NameError:
    inp = input

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']

def reduce_fn(state, ch):
    return state_next[state] if ch=='0' else state

state = reduce(reduce_fn, inp('Enter at own risk: '), START)
print "I have seen " + state_str[state]

答案 3 :(得分:0)

解决问题的简单方法就是计算零,然后打印一条合适的消息。 num_zeros = input_stream.count('0')

如果您要构建一个有限状态机来学习如何编写一个,那么您将学习更多编写通用FSM并使用它来解决您的特定问题。这是我的尝试 - 请注意,计算零的所有逻辑都是在状态及其转换中编码的。

class FSMState(object):
    def __init__(self, description):
        self.transition = {}
        self.description = description
    def set_transitions(self, on_zero, on_one):
        self.transition['0'] = on_zero
        self.transition['1'] = on_one

def run_machine(state, input_stream):
    """Put the input_stream through the FSM given."""
    for x in input_stream:
        state = state.transition[x]
    return state

# Create the states of the machine.
NO_ZEROS = FSMState('No zeros')
EVEN_ZEROS = FSMState('An even number of zeros')
ODD_ZEROS = FSMState('An odd number of zeros')

# Set up transitions for each state
NO_ZEROS.set_transitions(ODD_ZEROS, NO_ZEROS)
EVEN_ZEROS.set_transitions(ODD_ZEROS, EVEN_ZEROS)
ODD_ZEROS.set_transitions(EVEN_ZEROS, ODD_ZEROS)

result = run_machine(NO_ZEROS, '01011001010')
print result.description