python概率计算器实例分析

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Python实现代码统计工具(终极篇)

Python实现代码统计工具(终极篇)

本文对于先前系列文章中实现的C/Python代码统计工具(CPLineCounter),通过C扩展接口重写核心算法加以优化,并与网上常见的统计工具做对比。实测表明,CPLineCount...

Python利用字典将两个通讯录文本合并为一个文本实例

Python利用字典将两个通讯录文本合并为一个文本实例

本文实例主要实现的是利用字典将两个通讯录文本合并为一个文本,具体代码如下: def main(): ftele1=open("d:\TeleAddressBook.txt","r...

PYTHON压平嵌套列表的简单实现

list 是 Python 中使用最频繁的数据类型, 标准库里面有丰富的函数可以使用。 不过,如果把多维列表转换成一维列表(不知道这种需求多不多),还真不容易找到好用的函数, 要知道...

Ubuntu下升级 python3.7.1流程备忘(推荐)

Ubuntu下升级 python3.7.1流程备忘(推荐)

下载源码 wget https://www.python.org/ftp/python/3.7.1/Python-3.7.1.tgz 解压源码 tar -xvzf Python-3.7....

Python冒泡排序注意要点实例详解

冒泡排序注意三点: 1. 第一层循环可不用循环所有元素。 2.两层循环变量与第一层的循环变量相关联。 3.第二层循环,最终必须循环集合内所有元素。 示例代码一: 1.第一层循环,只循环...