Ad

Thursday, December 7, 2017

Integer Overflow in Python - Python for Technical InterviewsProgramming Interviews Series

How to handle large integers in Python?
Unlike other lower level programming languages. Python can dynamically resize arrays and integers to fit larger data. You are less likely going to run into integer overflow issues in Python. Also less likely going to have to worry about bit manipulation. What if this question comes up in an interview?

You can use float('inf') to represent positive infinity and - float('inf'), read it as negative infinity casted as a float, to represent really large negative number. Note you are casting the number as a float not as integer.

More familiar with the notion of MAXINT from JAVA? You can use an external module to cast integers. The module is called sys


import sys 
my_max_num = sys.maxint 
my_min_num = -sys.maxint


Here's a tip for beginners: why is this useful? Let's say you are asked to find a min in an array, which can contain both positive and negative numbers. You may want to initialize current_min as -sys.maxint

https://github.com/theoptips/technical_interview/blob/master/stock_profit_basics.py

Why not just set it equal to negative one? Well the array can contain other negative numbers smaller than one so that wouldn't work.

Uniqtech Technical Interview with Python series is geared towards learn to code, learn programming beginners and bootcamp grads. subscribe to our newsletter
subscribe@uniqtech.co
subject: technical interview with python

float('inf') will result in a floating point number. That's not always the desired result.  Turns out, we can also get a maxint estimate from the sys module.

>>> import sys
>>> sys.maxint
9223372036854775807

The above behavior is Python 2.x 
The difference between Python 2.x and Python 3 can be viewed here. https://stackoverflow.com/questions/7604966/maximum-and-minimum-values-for-ints

No comments:

Post a Comment

Reinforcement Learning Q Learning

Explore <s, a> ---> s' reads: move from current state s to s' via action a.   Through the action a reward  is received, it ...