在Python中处理非常大的数字

在Python中处理非常大的数字

本文介绍了在Python中处理非常大的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在考虑使用Python进行快速手牌评估.在我看来,加快处理速度的一种方法是将所有牌面和西服表示为素数,然后将它们相乘以表示手牌.加白:

I've been considering fast poker hand evaluation in Python. It occurred to me that one way to speed the process up would be to represent all the card faces and suits as prime numbers and multiply them together to represent the hands. To whit:

class PokerCard:
    faces = '23456789TJQKA'
    suits = 'cdhs'
    facePrimes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 53, 59, 61]
    suitPrimes = [2, 3, 5, 7]

AND

    def HashVal(self):
      return PokerCard.facePrimes[self.cardFace] * PokerCard.suitPrimes[self.cardSuit]

这将为每只手提供一个数值,该数值通过取模可以告诉我手中有多少个国王或有多少个心.例如,任何有五个或更多球杆的手将平均除以2 ^ 5;任何有四个国王的手都会平均除以59 ^ 4,依此类推.

This would give each hand a numeric value that, through modulo could tell me how many kings are in the hand or how many hearts. For example, any hand with five or more clubs in it would divide evenly by 2^5; any hand with four kings would divide evenly by 59^4, etc.

问题在于,像AcAdAhAsKdKhKs这样的七张牌手的哈希值约为62.7万亿次,这将需要超过32位才能在内部进行表示.有没有一种方法可以在Python中存储如此大的数字,从而允许我对其执行算术运算?

The problem is that a seven-card hand like AcAdAhAsKdKhKs has a hash value of approximately 62.7 quadrillion, which would take considerably more than 32 bits to represent internally. Is there a way to store such large numbers in Python that will allow me to perform arithmetic operations on it?

推荐答案

Python支持"bignum"整数类型,该整数类型可以处理任意大数.在Python 2.5+中,此类型称为long,与int类型分开,但是解释器将自动使用更合适的那个.在Python 3.0+中,int类型已被完全删除.

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the int type has been dropped completely.

不过,这只是实现细节-只要您具有2.5或更高版本,就只需执行标准数学运算,并且任何超出32位数学界限的数字都将自动(透明地)转换为bignum.

That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.

您可以在 PEP 0237 中找到所有详细信息.

You can find all the gory details in PEP 0237.

这篇关于在Python中处理非常大的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 22:22