Too many values to unpack, error only occurs with high iterations

huangapple go评论95阅读模式
英文:

Too many values to unpack, error only occurs with high iterations

问题

I'm here to help with the translation. Please note that I'll only translate the non-code parts.


我是新手学习Python和编程。我写了一个模拟掷骰机制的程序。现在我想计算不同情景下的成功几率。我的函数有时候有效,但我无法弄清楚为什么有时候不行。如果迭代次数较低,它有效,但如果使用较高的数字,它就会失败。

我收到以下错误:ValueError: 在simple_check_success_statistic中的for循环中解包值过多(预期7个)。

我会很感激您能提供建议。

谢谢您的考虑。

英文:

I am new to python and coding in general. I wrote a program to simulate a dice mechanic. Now I want to calculate the successchance for different scenarios. My function works...sometimes and I´m not able to figure ot why it does not. If the iterations are low it works, if I use higher numbers it fails.
I get: ValueError: too many values to unpack (expected 7) in the for loop in simple_check_success_statistic
I would be glad for hints.

Thank you for considering.

import random
import math


def roll_dice(sides):
    #get result of dice roll
    return random.randint(1, sides)


def simple_check(skillvalue, targetnumber, temptationdice, luckydice, temptfate):
    # Roll 3D20
    dice_rolls = sorted([roll_dice(20) for _ in range(3)])

    # Check for automatic failure
    if dice_rolls.count(1) >= 2:
        return "Automatic Failure"

    # Roll Temptation Dice and Lucky Dice
    td_rolls = [roll_dice(4) for _ in range(temptationdice)]
    ld_rolls = [roll_dice(4) for _ in range(luckydice)]

    # Check for 4 in TD and LD
    td_4 = 4 in td_rolls
    ld_4 = 4 in ld_rolls

    # Determine the chosen value
    if td_4 and ld_4:
        chosen_value = dice_rolls[1]  # Middle value
    elif td_4:
        chosen_value = dice_rolls[0]  # Lowest value
    elif ld_4 or tf == 1:
        chosen_value = dice_rolls[2]  # Highest value
    else:
        chosen_value = dice_rolls[1]  # Middle value

    # Calculate the Check Result
    cr = skillvalue + chosen_value - 10

    # Calculate Measure of Success
    if cr >= targetnumber:
        marks = math.floor((cr - tn) / 3)
    else:
        marks = 0

    # Determine success or failure
    if cr >= targetnumber:
        return "Success", cr, dice_rolls, td_rolls, ld_rolls, marks, temptfate
    else:
        return "Failure", cr, dice_rolls, td_rolls, ld_rolls, marks, temptfate


def userinput():
    
    #get values for the check
    skillvalue = int(input("Enter Skill Value (0-20): "))
    targetnumber = int(input("Enter Target Number (0-20): "))
    temptationdice = int(input("Enter number of Temptation Dice in pool: "))
    luckydice = int(input("Enter number of Lucky Dice in pool: "))

    while True:
        user_input = input("Tempt fate? (y/n): ").strip().lower()
        if user_input == "y":
            temptfate = True
            break
        elif user_input == "n":
            temptfate = False
            break
        else:
            print("Invalid input. Please enter 'Y' or 'N'.")

    return skillvalue, targetnumber, temptationdice, luckydice, temptfate


def simple_check_success_statistic(iterations, skillvalue, targetnumber, temptationdice, luckydice, temptfate):
    success_array = []

    #get a number of results
    for i in range(iterations):
        result, cr, dice_rolls, td_rolls, ld_rolls, marks, tempted = simple_check(skillvalue, targetnumber, temptationdice, luckydice, temptfate)
        success_array.append(result)

    #determine percentage of successful results
    print(str(success_array.count("Success")/iterations)+"%")


sv, tn, td, ld, tf = userinput()
simple_check_success_statistic(1000, sv, tn, td, ld, tf)

I ran the code through chatgpt (...no comment please Too many values to unpack, error only occurs with high iterations ) but it did not spot an error. I looked up arrays and checked the number of variables i return from simple check function. But as i said it sometimes works, othertimes not. I´m a bit lost.

答案1

得分: 1

在第16行,你返回了一个单一的值,"自动失败"

    if dice_rolls.count(1) >= 2:
        return "自动失败"

为了修复这个问题,你应该检查自动失败:

        res = simple_check(skillvalue, targetnumber, temptationdice, luckydice, temptfate)
        if len(res) == 1:
            ... # 处理自动失败(退出?)
        else:
            result, cr, dice_rolls, td_rolls, ld_rolls, marks, tempted = res
            ... # 继续之前的操作
英文:

In line 16 you return a single value, "Automatic Failure":

    if dice_rolls.count(1) >= 2:
        return "Automatic Failure"

To fix this, you should check for automatic failure

        res = simple_check(skillvalue, targetnumber, temptationdice, luckydice, temptfate)
        if len(res) == 1:
            ... # Do automatic failure handling (exit?)
        else:
            result, cr, dice_rolls, td_rolls, ld_rolls, marks, tempted = res
            ... # continue as before

答案2

得分: 0

"simple_check" 函数中你期望它返回7个不同的值然后将这些值赋给变量但在以下部分

检查自动失败

if dice_rolls.count(1) >= 2:
return "自动失败"

你只返回了一个值。我通过返回6个零来修复了这个问题,就像这样:

检查自动失败

if dice_rolls.count(1) >= 2:
return "自动失败", 0, 0, 0, 0, 0, 0


你可以考虑将所有这些作为列表返回,然后使用 if 语句检查其长度以确定接下来该做什么。你可以说如果它的长度等于7,那么我们可以访问所有7个索引,没有问题。如果长度为1,那么我们就得到了一个自动失败。

希望这能有所帮助!如果你需要更多解释,请评论,我会编辑我的答案。
英文:

In the "simple_check" function you are expecting it to return 7 different values and then assign those values to variables, but in the:

# Check for automatic failure
if dice_rolls.count(1) >= 2:
    return "Automatic Failure"

section you are only returning one value. I fixed this by returning 6 zeroes with what you expected like so:

# Check for automatic failure
if dice_rolls.count(1) >= 2:
    return "Automatic Failure", 0, 0, 0, 0, 0, 0

Something you could consider is returning this all as a list and then checking its length with an if statement to determine what to do next. You could say if its length is equal to 7, then we can access all 7 of those indices and there was no issue. If its length is 1, then we got an automatic failure.

Hope this helps! And if you need anymore clarification please comment and I'll edit my answer.

huangapple
  • 本文由 发表于 2023年6月26日 22:54:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定