排列组合与概率

排列组合与概率

一.如何求数字的组合

class Test:
    def __init__(self,arr):
        self.numbers=arr
        self.visited=[None]*len(self.numbers)

        self.graph=[([None]*len(self.numbers)) for i in range(len(self.numbers))]
        self.n=len(self.numbers)

        self.combination=""
        self.s=set()

    def DepthFirstSearch(self,start):
        self.visited[start]=True
        self.combination+=str(self.numbers[start])

        if len(self.combination)==self.n:
            if self.combination.index("4")!=2:
                self.s.add(self.combination)


        j=0
        while j<self.n:
            if self.graph[start][j]==1 and self.visited[j]==False:
                self.DepthFirstSearch(j)
            j+=1

        self.combination=self.combination[:-1]
        self.visited[start]=False

    def GetAllCombinations(self):
        i=0

        while i<self.n:
            j=0
            while j<self.n:
                if i==j:
                    self.graph[i][j]=0
                else:
                    self.graph[i][j]=1
                j+=1
            i+=1

        self.graph[3][5]=0
        self.graph[5][3]=0

        i=0
        while i<self.n:
            self.DepthFirstSearch(i)
            i+=1

    def PrintAllCombinations(self):
        for strs in self.s:
            print(strs)


if __name__=="__main__":
    arr=[1,2,2,3,4,5]
    t=Test(arr)
    t.GetAllCombinations()
    t.PrintAllCombinations()
521342
521423
542231
512432
513422
542123
542321
523421
523241
521234
542132
512342
512423
521432
522134
522431
543212
512324
513242
521243
542312
541223
523124
523142
512234
541232
542213
523214
513224
523412
521324
522341
512243
522413
543221
543122
541322
522143
522314

二.如何拿到最多金币

import random

def GetMaxNum(n):
    if n<1:
        print("参数不合法")
        return

    a=[None]*n

    i=0
    while i<n:
        a[i]=random.uniform(1,n)
        i+=1

    max4=0
    i=0
    while i<4:
        if a[i]>max4:
            max4=a[i]
        i+=1

    i=4
    while i<n:
        if a[i]>max4:
            return True
        i+=1
    return False


if __name__=="__main__":
    monitorCount=1000
    success=0
    i=0
    while i<monitorCount:
        if GetMaxNum(10):
            success+=1
        i+=1

    print(success/monitorCount)
0.592

三.如何求正整数n所有可能的整数组合

四.如何用一个随机函数得到另外一个随机函数

import random

def Func1():
    return int(round(random.random()))

def Func2():
    a1=Func1()
    a2=Func1()

    tmp=a1
    tmp|=a2
    if tmp==0:
        return 0
    else:
        return 1

if __name__=="__main__":
    i=0
    while i<16:
        print(Func2(),end=" ")
        i+=1

    print("
")
    i = 0
    while i < 16:
        print(Func2(),end=" ")
        i += 1
1 1 0 1 1 1 0 1 0 0 1 0 1 1 0 1 

1 1 1 1 0 0 1 1 0 1 0 1 1 1 0 1

五.如何等概率地从大小为n的数组中选取m个整数

原文地址:https://www.cnblogs.com/LQ6H/p/12940544.html