如何计算调用此函数的次数?

时间:2018-04-04 20:43:46

标签: python python-3.x

所以我的作业(我必须使用while语句)是制作数字猜谜游戏,其中一部分是显示玩家获得数字后猜测的数量。我发现我读过的东西应该可以工作但不会。这是我的代码。

#A text program that is a simple number guessing game.
import time
import random
#Setting up the A.I.
Number = random.randint(1,101)
def AI():
    B = AI.counter =+ 1
    Guess = int(input("Can you guess what number I'm Thinking of?: "))
    while Guess > Number:
        print("nope, to high.")
        return AI()
    while Guess < Number:
        print("Sorry, thats to low. try again!")
        return AI()
    while Guess == Number:
        print("Congragulations! you win! You guessed " + str(B) + " times")
        time.sleep(60)
        quit()
AI.counter = 0
AI()

虽然当玩家获得正确的数字时,它表示即使不是这样,玩家也会猜到它。

5 个答案:

答案 0 :(得分:1)

你非常接近@Simpson!这是一个稍微改变的版本,可以为您提供您正在寻找的东西:)

如果您有任何疑问,请与我联系!

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void buttonCalculate_Click(object sender, EventArgs e)
    {
        double minSkill;
        double maxSkill;
        double coolDown;
        minSkill = float.Parse(txtMinSkill.Text) * 10;
        maxSkill = float.Parse(txtMaxSkill.Text) * 10;
        coolDown = float.Parse(txtCooldown.Text);
        SkillGainCalculator skill = new SkillGainCalculator();
        skill.IntegerMax(maxSkill);
        skill.RemainderMax(maxSkill);
        skill.RemainderMin(minSkill);
        skill.IntegerMin(minSkill);
        skill.Calculate(minSkill,maxSkill);
        skill.Display(coolDown);
    }

}
class SkillGainCalculator
{
    //member variables
    private int integerMax;
    private int remainderMax;
    private int integerMin;
    private int remainderMin;

    private double counter;
    const int constant = 6480;
    private int i;

    private double totalTime;
    private int hours;
    private int minutes;
    private int seconds;

    public double IntegerMax(double intMax)
    {
        integerMax = (int)((1000 - intMax) / 50);
        return integerMax;
    }

    public int RemainderMax(double intMax)
    {
        remainderMax = (int)((1000 - intMax) % 50);
        return remainderMax;
    }

    public int RemainderMin(double intMin)
    {
        remainderMin = (int)((1000 - intMin) % 50);
        return remainderMin;
    }

    public int IntegerMin(double intMin)
    {
        if (remainderMin == 0)
        {
            integerMin = (int)((1000 - intMin) / 50) - 1;
            return integerMin;
        }
        else
        {
            integerMin = (int)((1000 - intMin) / 50);
            return integerMin;
        }
    }

    public double Calculate(double intMax, double intMin)
    {
        for (i = integerMax; i <= integerMin; i++)
        {
            if (i == integerMax && remainderMax != 0)
            {
                if (intMax <= 700)
                {
                    counter = counter + constant * Math.Pow(0.8, i) * (50 - remainderMax) / 50;
                }
                else
                {
                    counter = counter + constant * Math.Pow(0.8, i) * (50 - remainderMax) / 50;
                }
            }
            else if (i == integerMin && remainderMin != 0)
            {
                if (intMin < 700)
                {
                    counter = counter + constant * Math.Pow(0.8, i) * remainderMin / 50;
                }
                else
                {
                    counter = counter + constant * Math.Pow(0.8, i) * remainderMin / 50;
                }
            }
            else if (i >= 6)
            {
                counter = counter + constant * Math.Pow(0.8, i);
            }
            else
            {
                counter = counter + constant * Math.Pow(0.8, i);
            }
        }
        return counter;
    }

    public void Display(double clD)
    {
        totalTime = counter * clD / 3600;
        hours = (int)(counter * clD / 3600);
        minutes = (int)((totalTime - hours) * 3600 / 60);
        seconds = (int)((totalTime - hours) * 3600 % 60);
    }

}

答案 1 :(得分:1)

没有递归 - 将while更改为ifs并在方法中添加了计数器。

import time
import random

Number = random.randint(1,101)

def AI():
    B = 1
    Guess = int(input("Can you guess what number I'm Thinking of?: "))
    while True:
        if Guess > Number:
            print("nope, to high.")
        elif Guess < Number:
            print("Sorry, thats to low. try again!")

        if Guess == Number:
            print("Congragulations! you win! You guessed " + str(B) + " times")
            time.sleep(2)
            break # leave the while true

        # increment number
        B += 1   
        Guess = int(input("Can you guess what number I'm Thinking of?: "))
AI()

答案 2 :(得分:1)

计算函数调用是function decorators的一个完美案例,这是Python的一个非常有用的功能。您可以将装饰器定义为:

def call_counted(funct):
    def wrapped(*args, **kwargs):
        wrapped.count += 1  # increase on each call
        return funct(*args, **kwargs)
    wrapped.count = 0  # keep the counter on the function itself
    return wrapped

然后您可以使用它来装饰您希望计算调用的函数,而无需在处理流程中处理计数器本身:

import time
import random

secret_number = random.randint(1, 101)

@call_counted  # decorate your AI function with the aforementioned call_counted
def AI():
    current_guess = int(input("Can you guess what number I'm thinking of?: "))
    while current_guess > secret_number:
        print("Nope, too high. Try again!")
        return AI()
    while current_guess < secret_number:
        print("Sorry, that's too low. Try again!")
        return AI()
    while current_guess == secret_number:
        print("Congratulations! You win! You guessed {} times.".format(AI.count))
        time.sleep(60)
        quit()

AI()

我重新调整了你的代码,但它基本上是一样的。

我会避免递归,因为这可以写得更简单,而且不需要计算函数调用:

import time
import random

secret_number = random.randint(1, 101)

def AI():
    counter = 0
    while True:
        counter += 1
        current_guess = int(input("Can you guess what number I'm thinking of?: "))
        if current_guess > secret_number:
            print("Nope, too high. Try again!")
        elif current_guess < secret_number:
            print("Sorry, that's too low. Try again!")
        else:
            break
    print("Congratulations! You win! You guessed {} times.".format(counter))
    time.sleep(60)
    quit()

AI()

答案 3 :(得分:1)

你可以通过函数装饰器来执行它,该函数装饰器将调用计数器添加到应用它的任何函数:

(注意我也修改了你的代码,使其更紧密地跟随PEP 8 - Style Guide for Python Code。)

""" A text program that is a simple number guessing game. """
import functools
import time
import random

def count_calls(f):
    """ Function decorator that adds a call count attribute to it and counts
        the number of times it's called.
    """
    f.call_count = 0
    @functools.wraps(f)
    def decorated(*args, **kwargs):
        decorated.call_count += 1
        return f(*args, **kwargs)

    return decorated

# Setting up the A.I.
number = random.randint(1, 101)
# print('The number is:', number)  # For testing.

@count_calls
def AI():
    guess = int(input("Can you guess what number I'm thinking of?: "))
    while guess > number:
        print("Nope, too high.")
        return AI()
    while guess < number:
        print("Sorry, that's too low. Try again!")
        return AI()
    while guess == number:
        print("Congragulations! You win! You guessed " + str(AI.call_count) + " times")
        time.sleep(10)
        quit()

AI()

答案 4 :(得分:0)

使用默认参数:

def AI(B=1):
    Guess = int(input("Can you guess what number I'm Thinking of?: "))
    while Guess > Number:
        print("nope, to high.")
        return AI(B + 1)
    while Guess < Number:
        print("Sorry, thats to low. try again!")
        return AI(B + 1)
    while Guess == Number:
        print("Congragulations! you win! You guessed " + str(B) + " times")
        time.sleep(60)
        return

然后调用函数:

AI()

另外,你应该在这里使用if而不是while,因为循环只运行一次,但while也可以使用,所以这很好。此外,递归可能会占用你的RAM,这会浪费资源,前提是你可以实现与循环相同的东西,但你的方法也可以,所以也很好。