float sum(list)ValueError

时间:2016-11-02 20:17:53

标签: python

我一直在构建这个程序,根据给定列表中的数字总和做出决定。当我对给定函数中的数字求和时,它也测试了ceratin所需的逻辑,它给出了正确的答案,但是测试值的if语句没有正常工作,或者会执行错误的if语句:

import random
from decimal import Decimal
from decimal import getcontext


def language_equate(sentence_parsing):
    both = ["and", ",", "then", "next"]
    ignore = ["don't", "not"]
    travel = ["move", "go", "travel"]
    dial = ["rotate", "turn", "spin", "twist"]
    lever_positive = ["push", "back"]
    lever_negative = ["pull", "forward"]
    north = ["north", "up", "forward"]
    east = ["east", "right"]
    west = ["west", "left"]
    south = ["south", "down", "backward"]
    modded_sentence = []
    getcontext().prec = 20
    for i, word in enumerate(sentence_parsing):
        if word.lower() in both:
            modded_sentence.append(Decimal(99))
        elif word.lower() in ignore:
            modded_sentence.append(Decimal(-20))
        elif word.lower() in travel:
            modded_sentence.append(Decimal(1))
        elif word.lower() in dial:
            modded_sentence.append(Decimal(1/3))
        elif word.lower() in lever_positive:
            modded_sentence.append(Decimal(1/5))
        elif word.lower() in lever_negative:
            modded_sentence.append(Decimal(1/7))
        elif word.lower() in north:
            modded_sentence.append(Decimal(1/11))
        elif word.lower() in east:
            modded_sentence.append(Decimal(1/13))
        elif word.lower() in west:
            modded_sentence.append(Decimal(1/17))
        elif word.lower() in south:
            modded_sentence.append(Decimal(1/19))
    return modded_sentence


def language_evaluate(sentence_parsing):
    modded_sentence = language_equate(sentence_parsing)
    a = sum(modded_sentence)
    return a


def entrance(dial, lever, win, current_room, EPSILON):
    print("You are in the entrance.")
    print("Go north to try the closed door")
    print("Go east to the kitchen")
    print("Go west to the pantry")
    print("Go south to exit")
    print("What would you like to do?")
    sentence_parsing = input().split(" ")
    go = language_evaluate(sentence_parsing)
    # Exclusive Disjunction Answer Bank
    answer_bank = ["Y", "y", "Yes", "yes", "YES"]
    if abs(go - Decimal(1/11)) <= EPSILON or abs(go - Decimal(12/11)) <= EPSILON: # separate statements
        if dial == "red" and lever == "backward":
            win = True
            current_room = ""
        else:
            print("Sorry the door remains locked")
    elif abs(go - Decimal(1/13)) <= EPSILON or abs(go - Decimal(14/13)) <= EPSILON:
        current_room = "kitchen"
    elif Decimal(1/17) or Decimal(18/17):
        current_room = "pantry"
    elif abs(go - Decimal(1/19)) <= EPSILON or (go - Decimal(20/19)) <= EPSILON:
        print("Are You sure you want to quit? [Y/N]")
        give_up = input()
        if give_up in answer_bank:
            print("Ok, maybe next time")
            raise SystemExit
    else:
        print("Sorry I don't understand that")
    return win, current_room


def kitchen(lever, lever_position, current_room, EPSILON):
    print("You are in the kitchen.")
    print("Go north to move the lever the %s position" % lever)
    print("Go west to the entrance")
    print("What would you like to do?")
    sentence_parsing = input().split(" ")
    go = language_evaluate(sentence_parsing)
    print(go)
    if abs(go - 16/55) <= EPSILON or abs(go - 71/55) <= EPSILON or abs(go - 1/5) <= EPSILON:
        lever = lever_position[1]
    elif abs(go - 18/77) <= EPSILON or abs(go - 95/77) <= EPSILON or abs(go - 1/7) <= EPSILON:
        lever = lever_position[0]
    elif abs(go - 1/17) <= EPSILON or abs(18/17) <= EPSILON:
        print("test works")
        current_room = "entrance"
    else:
        print("Sorry I don't understand that")
    return lever, current_room


def pantry(dial, current_room, EPSILON):
    print("You are in the pantry.")
    print("South of you is a three coloured dial, with the color %s glowing" % dial)
    print("Go east to the entrance")
    print("Go south to turn the dial")
    print("What would you like to do?")
    sentence_parsing = input().split(" ")
    go = language_evaluate(sentence_parsing)
    print(int(go))
    if abs(go - 1/19) <= EPSILON or abs(go - 20/19) <= EPSILON or abs(go - 22/57) <= EPSILON or abs(go - 79/57) <= EPSILON or abs(go - 1/3) <= EPSILON:
        dial += 1
        if dial == 3:
            dial = 0
    elif abs(go - 1/13) <= EPSILON or abs(14/13) <= EPSILON:
        current_room = "entrance"
    else:
        print("Sorry I don't understand that")
    return dial, current_room


def main():
    EPSILON = Decimal(0.00000000001)
    current_room = "entrance"
    dial_color = ["green", "blue", "red"]
    dial = dial_color[random.randrange(3)]
    lever_position = ["forward", "backward"]
    lever = lever_position[random.randrange(2)]
    win = False
    while win is False:
        while current_room is "entrance":
            entrance(dial, lever, win, current_room, EPSILON)
            win, current_room = entrance(dial, lever, win, current_room, EPSILON)
        while current_room is "kitchen":
            kitchen(lever, lever_position, current_room, EPSILON)
            lever, current_room = kitchen(lever, lever_position, current_room, EPSILON)
        while current_room is "pantry":
            pantry(dial, current_room, EPSILON)
            dial, current_room = pantry(dial, current_room, EPSILON)
main()

从一开始,如果你往南走3次你会得到一个错误,2次你将在食品储藏室东边结束,1次不会做任何事情???我非常迷失 此时程序后面会有三个类似的elif语句,但是第一次输入的输入将被忽略,第二次它将执行错误的操作,除了包含1/11的素数部分之外;旁注所有其他elifs使用增加的素数分数{1 / 11,1 / 13,1 / 17,1 / 19}。我很少有编程经验(3个月),我只是学习python作为我的第一语言。任何帮助都会有很大的吸引力

2 个答案:

答案 0 :(得分:1)

您的代码中存在大量错误。当您输入"south"作为输入三次时,让我们看看您描述的问题。

entrance函数有一个严重破坏的测试:

elif Decimal(1/17) or Decimal(18/17):

这总是如此,所以如果你达到那个条件(不向北或向东,这是先前测试的),你总是最终去食品室。

pantry函数有一个类似的问题,在从减去您从解析代码中获得的值之前,您不会将某些分数转换为Decimal。这会导致你看到的异常。

两次entry的原因是你的main函数总是调用当前房间的两次函数(连续两行)。第一次做出的选择被忽略了。

我看到的代码的其他部分可能存在更多错误。

通过将分数用于解析输入文本的值,您可以使任务变得更加困难。一个更好的方法是使用2的整数幂,并使用按位或(|)来组合它们。例如,如果单词move已解析为12**0)而south已解析为162**4),则表示您对{ {1}}或south可以是move south(不需要类型转换或epsilon)。如果您不关心额外的单词,可以使用按位和(if go == 16 or go == 17)来测试一个术语:&

如果您使用的是包含if go & 16模块的Python版本(在Python 3.4中添加),您也可以考虑使用Enum

答案 1 :(得分:0)

这是您的计划的问题:

  1. 使用is进行同等测试时应使用==,例如在此

    while current_room is "entrance":
    

    is运算符告诉你对象在内存中是否具有相同的位置,如果它们具有相同的值,通常它们对于不可变对象(如字符串)可能是相同的但是你不能指望它,例如

    >>> "asfdvfgbgdf" is "".join("asfdvfgbgdf")
    False
    >>> 
    

    使用==时给出正确答案

    >>> "asfdvfgbgdf" == "".join("asfdvfgbgdf")
    True
    >>> 
    

    更改is

  2. 的所有==
  3. 您无需将布尔值或任何其他值与TrueFalse进行比较。在python中,当一个对象被用于Boolean context时,该对象表现为True或False

      

    值被解释为false:FalseNone,所有类型的数字零,以及空字符串和容器(包括字符串,元组,列表,字典,集合和frozensets)。所有其他值都被解释为true。用户定义的对象可以通过提供__bool__()方法来自定义其真值。

    所以这个例如

    while win is False:
    

    将其更改为

    while not win:
    
  4. main函数中,您将其他函数调用两次,这会导致第一次忽略结果而不对其执行任何操作

    就像在这里

    entrance(...)
    win, current_room = entrance(...)
    

    kitchenpantry相同。删除每个人的第一个电话以解决该问题。

  5. 在食品室功能中,这里

    elif abs(go - 1/13) <= EPSILON or abs(14/13) <= EPSILON:
    

    也许你的意思是?

    elif abs(go - 1/13) <= EPSILON or abs(go - 14/13) <= EPSILON:
    

    与第三个kitchen

  6. 中的elif相同 第二个entrance

    中的elif中的
  7. elif Decimal(1/17) or Decimal(18/17):
    

    这是什么意思?从第2点开始,总是如此,因为这些数字都不为零,所以如果其他检查失败,这总是会通过

  8. 在for-loop中的language_equate

    for i, word in enumerate(sentence_parsing):
    

    你从不使用i,因此没有理由使用枚举,所以将其改为

    for word in sentence_parsing:
    

    你也重复word.lower()次,你应该尝试avoid repeat instructions总是给出相同的结果,因为这是浪费时间,而是制作一个新变量或重用你所拥有的变量该方法的结果,例如

    for word in sentence_parsing:
        word = word.lower()
        if word in both:
            ...
        elif word in ignore:
            ...
        ...
    

    您也可以在获得

    之类的输入后立即致电lower
    input().lower()
    

    或者当你拆分它时

    input().lower().split()
    
  9. 最后你可能已经注意到十进制和花车并不像我在之前的评论中所说的那样非常喜欢,选择其中一个并一直坚持下去。

    或者 Blckknght 建议,改为使用Bit Maskenumeration