Python: pick appropriate datatype size (int) automatically?

Def type_chooser(N): import numpy as np for dtype in np. Uint8, np. Uint16, np.

Uint32, np. Uint64: if N >> type_chooser(255) >>> type_chooser(256) >>> type_chooser(18446744073709551615) >>> type_chooser(18446744073709551616) Traceback (most recent call last): File "", line 1, in File "spam.Py", line 6, in type_chooser raise StandardError('{} is really big! '.

Format(N)) StandardError: 18446744073709551616 is really big!

If you want to be really clever, you could implement this using np. Log2(N)! – wim 3 hours ago Aha, this was what I was after.

I did come up with my own version using bitshifts, but it's basically the same as yours. Cheers – mathematical. Coffee 3 hours ago.

Create a mapping of maximum value to type, and then look for the smallest value larger than N. Typemap = { 256: uint8, 65536: uint16, ... } return typemap. Get(min((x for x in typemap.iterkeys() if x > N))).

Cheers! I ran with @wim's because it didn't rely on me making a dict, although I realise your approaches are essentially the same. – mathematical.

Coffee 3 hours ago The dict isn't really being used as a dict here, though. You could just as easily use a tuple of 2-tuples. – Karl Knechtel 2 hours ago.

For interest, here is the version I had been toying with until @Ignacio Vazquez-Abrams and @wim posted their answers, using bitshifts: def minimal_uint_type(N): bases = 8,16,32,64 a = N>>i for I in bases try: dtype = baseslen(np. Nonzero(a)0) except: raise StandardError('{} is really big! '.

Format(N)) return dtype.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions