从随机数列表中计算的问题

时间:2015-12-28 14:55:53

标签: python

我决定在圣诞休假期间使用我的Rasp Pi学习Python 2.7

我正在运行import random print ("Welcome to the coin toss simulator") start = raw_input("Would you like to start: ") if start == "y": count = 0 while count <= 100: outcome = random.randint(1, 2) count +=1 if outcome == 1: print("Heads") else: print("Tails") print("You tossed: ", outcome.count(1), " Heads") print("You tossed: ", outcome.count(2), " Tails") input("\n\nPress the enter key to exit.") 并且正在阅读我正在完成的书中的一个练习,我正在尝试编写一个投掷硬币的程序,该程序将硬币投掷100次然后打印每次折腾的结果和头尾的总数。

程序生成每次投掷的结果,并在100转后停止。

这是我坚持的计数。

我的代码是:

Traceback (most recent call last):
  File "./coin_toss.py", line 23, in <module>
    print("You tossed: ", outcome.count(1), " Heads")
AttributeError: 'int' object has no attribute 'count'

我得到的错误信息是:

Car.prototype.doSomeThing = function() {
    var driveReference = this.drive.bind(this);
    driveReference();
}

3 个答案:

答案 0 :(得分:1)

你得到的实际错误只是因为random.randint()返回一个整数(因为甚至会做什么?)。然后,在最后的print调用中,您尝试调用此整数的count()方法,但整数没有count()方法。

我建议分别跟踪头部和尾部。 E.g:

if outcome == 1:
    heads_count += 1
else:
    tails_count += 1

答案 1 :(得分:0)

outcome是硬币翻转的结果。您无法找到1中有多少1个;它没有意义。您必须将结果保存在某个位置,例如list。然后你可以计算其中每个数字的出现次数:

        outcome = [] # initialize the list
        while count <= 100:
                outcome.append(randint(1, 2)) # add the result to the list
                count +=1
                if outcome[-1] == 1: # check the last element in the list
                        print("Heads")
                else:
                        print("Tails")

print("You tossed: ", outcome.count(1), " Heads") # now these work
print("You tossed: ", outcome.count(2), " Tails")

答案 2 :(得分:0)

您可以使用Python为您提供的高性能Counter数据容器:

public class FileIO {
    public static BinaryTree Level1;
    public static BinaryTree Level2;
    static BinaryTree Level3;
    static BinaryTree Val;

    public FileIO () {
       Level1 = new BinaryTree ();
       Level2 = new BinaryTree ();
       Level3 = new BinaryTree ();
       Val = new BinaryTree ();
    }

    public static void Refill () throws FileNotFoundException {
        Scanner Lev1 = new Scanner (new File ("C:\\Users\\Shandana\\Documents\\NetBeansProjects\\ScrambledWords\\Level1.txt"));
        Scanner input1 = new Scanner (new File ("C:\\Users\\Shandana\\Documents\\NetBeansProjects\\ScrambledWords\\Level1 Dictionary.txt"));

        while (Lev1.hasNextLine() && input1.hasNextLine())  {
             Level1.Insert(Lev1.nextLine(), input1.nextLine());
        }

        Lev1.close();
        input1.close();
    }
}