python概率计算器实例分析

yipeiwu_com5年前Python基础

本文实例讲述了python概率计算器实现方法。分享给大家供大家参考。具体实现方法如下:

from random import randrange
#randrange form random module
def calc_prob(strengths):
  """A function that receives an array of two numbers 
  indicating the strength of each party 
  and returns the winner"""
  if strengths[1]>strengths[0]:
#Bring the bigger number to the first position in the array
    temp=strengths[0]
    strengths[0]=strengths[1]
    strengths[1]=temp   
  prob1=abs(strengths[0]-strengths[1])
#The relative strength of the 2 parties
  prob2=randrange(0,100)
#To calculate the luck that decides the outcome
  if prob2 in range(0,33-prob1):
#Check if the weaker party is capable of winning. 
#The condition gets narrower with the increase
#in relative strengths of each parties
    return strengths[1]
  elif prob2 in range(33-prob1,66-prob1):
  #The middle condition
    return "Draw"
  else:
     return strengths[0]
#Luck favors the stronger party and if relative strength
#between the teams is too large, 
#the match ends up in favor of the stronger party 
#Example
calc_prob([50,75]);#Always has to be a list to allow exchange
#Can be programmed in hundreds of better ways. Good luck!

希望本文所述对大家的Python程序设计有所帮助。

相关文章

在cmd命令行里进入和退出Python程序的方法

在cmd命令行里进入和退出Python程序的方法

进入: 直接输入python即可,如图所示 退出: 1:输入exit(),回车 2:输入quit(),回车 3:输入ctrl+z,回车 以上这篇在cmd命令行里进入和退出Python程...

用Python写一段用户登录的程序代码

用Python写一段用户登录的程序代码

如下所示: #!/usr/bin/env python #coding: utf8 import getpass db = {} def newUser(): username =...

python中文编码问题小结

python中文编码问题小结

中文编码问题一直是Python程序设计中很头痛的问题,本文对此较为详细的进行了总结归纳。具体如下:   当字符串是:'\u4e2d\u56fd'  >&g...

Python基于回溯法子集树模板实现8皇后问题

Python基于回溯法子集树模板实现8皇后问题

本文实例讲述了Python基于回溯法子集树模板实现8皇后问题。分享给大家供大家参考,具体如下: 问题 8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、...

Python urls.py的三种配置写法实例详解

urls.py的配置写法一般有三种方式。 1. 第一种是导入视图的方式,就是 The Django Book 里面样例的写法: from blog.views import inde...