Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python编程是一种现成的编码_Python_Python 3.x_Numpy_Scipy_Probability - Fatal编程技术网

Python编程是一种现成的编码

Python编程是一种现成的编码,python,python-3.x,numpy,scipy,probability,Python,Python 3.x,Numpy,Scipy,Probability,嘿,我是编程新手,但我似乎不能编写概率问题的代码。例如,我将如何编写此代码? 一个盒子包含12个A型晶体管和18个B型晶体管。随机取出一个晶体管并返回。这个过程是重复的。确定第一个选择为A型,第二个选择为B型的概率。谢谢 这是我第一次尝试 from scipy import stats as st import numpy as np import random total=30 totalA=12 totalB=18 def transistor(): return random

嘿,我是编程新手,但我似乎不能编写概率问题的代码。例如,我将如何编写此代码? 一个盒子包含12个A型晶体管和18个B型晶体管。随机取出一个晶体管并返回。这个过程是重复的。确定第一个选择为A型,第二个选择为B型的概率。谢谢

这是我第一次尝试

from  scipy import stats as st
import numpy as np
import random

total=30
totalA=12
totalB=18

def transistor():
    return random.choice("A","B")

random.seed(0)
for _in range(30):
    try1=transistor()
    try2=transistor()

    if try1="A":
        prob1=totalA/total
    else:
        prob1=totalB/total

    if try2="A":
        prob2=totalA/total
    else:
        prob2=totalB/total   

    if try1=="A" and try2=="A"
     prob=2*totalA/total

如果您试图运行模拟,此代码将提供10000次试验的概率。每次都会产生不同的结果。试验越多,越准确。正确的理论答案是
0.24

import random

trials = 10000 # total number of trials
totalA = 12 # total number of A transistors
totalB = 18 # total number of B transistors

successes = 0 # variable keeping track of how many successful pulls there were

choicelist = list("A" * totalA + "B" * totalB) # list containing transitors to correct proportion

def transistor():
    return random.choice(choicelist) # pick a random transistor from list

for i in range(trials):
    try1 = transistor()
    try2 = transistor()
    if try1 == "A" and try2 == "B": # if first pull is type A and second is type B...
        successes += 1 # ...then it's successful
print float(successes) / trials # print out the proportion of successes to trials

因此,您有一个
.4
概率获得
a
.6
概率获得
B
并获取
a
,返回它并获取
B
将是
.24
。阅读更多关于概率的信息。
如果try1=“A”:
。。。使用双等于进行比较
晶体管()。你可以把12个A和18个B放在这个列表中,这样会更准确,你如何编写这样的问题?没有变量,无论发生什么,答案都是一样的。这是一个简单的数学问题,不需要代码。如果你的意思是代码模拟,那么请在问题中澄清。