range interview questions
Top range frequently asked interview questions
It is my understanding that the range()
function, which is actually an object type in Python 3, generates its contents on the fly, similar to a generator.
This being the case, I would have expected the following line to take an inordinate amount of time, because in order to determine whether 1 quadrillion is in the range, a quadrillion values would have to be generated:
1000000000000000 in range(1000000000000001)
Furthermore: it seems that no matter how many zeroes I add on, the calculation more or less takes the same amount of time (basically instantaneous).
I have also tried things like this, but the calculation is still almost instant:
1000000000000000000000 in range(0,1000000000000000000001,10) # count by tens
If I try to implement my own range function, the result is not so nice!!
def my_crappy_range(N):
i = 0
while i < N:
yield i
i += 1
return
What is the range()
object doing under the hood that makes it so fast?
EDIT: This has turned out to be a much more nuanced topic than I anticipated - there seems to be a bit of history behind the optimization of range()
.
Martijn Pieters' answer was chosen for its completeness, but also see abarnert's first answer for a good discussion of what it means for range
to be a full-fledged sequence in Python 3, and some information/warning regarding potential inconsistency for __contains__
function optimization across Python implementations. abarnert's other answer goes into some more detail and provides links for those interested in the history behind the optimization in Python 3 (and lack of optimization of xrange
in Python 2). Answers by poke and by wim provide the relevant C source code and explanations for those who are interested.
Source: (StackOverflow)
How can I set the y axis range of the second subplot to e.g. [0,1000] ?
The FFT plot of my data (a column in a text file) results in a (inf.?) spike so that the actual data is not visible.
pylab.ylim([0,1000])
has no effect, unfortunately. This is the whole script:
# based on http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/
import numpy, scipy, pylab, random
xs = []
rawsignal = []
with open("test.dat", 'r') as f:
for line in f:
if line[0] != '#' and len(line) > 0:
xs.append( int( line.split()[0] ) )
rawsignal.append( int( line.split()[1] ) )
h, w = 3, 1
pylab.figure(figsize=(12,9))
pylab.subplots_adjust(hspace=.7)
pylab.subplot(h,w,1)
pylab.title("Signal")
pylab.plot(xs,rawsignal)
pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
#~ pylab.axis([None,None,0,1000])
pylab.ylim([0,1000])
pylab.plot(abs(fft))
pylab.savefig("SIG.png",dpi=200)
pylab.show()
Other improvements are also appreciated!
Source: (StackOverflow)
Given two inclusive integer ranges [x1:x2] and [y1:y2], where x1 <= x2 and y1 <= y2, what is the most efficient way to test whether there is any overlap of the two ranges?
A simple implementation is as follows:
bool testOverlap(int x1, int x2, int y1, int y2) {
return (x1 >= y1 && x1 <= y2) ||
(x2 >= y1 && x2 <= y2) ||
(y1 >= x1 && y1 <= x2) ||
(y2 >= x1 && y2 <= x2);
}
But I expect there are more efficient ways to compute this.
What method would be the most efficient in terms of fewest operations.
Source: (StackOverflow)
As the title suggests, I am trying to figure out a way of generating random numbers using the new c++11 <random>
library. I have tried it with this code:
std::default_random_engine generator;
std::uniform_real_distribution<double> uniform_distance(1, 10.001);
The problem with the code I have is that every time I compile and run it, it always generates the same numbers. So my question is what other functions in the random library can accomplish this while being truly random?
For my particular use case, I was trying to get a range within [1, 10]
Source: (StackOverflow)
Currently the onChange event on my range inputs is firing at each step.
Is there a way to stop this event from firing until the user has let go of the slider?
I'm using the range to create a search query. I want to be able to run the search every time the form is changed but issuing a search request at each step of the slider's movement is too much.
Thanks for your help
Here's the code as it stands:
HTML:
<div id="page">
<p>Currently viewing page <span>1</span>.</p>
<input class="slider" type="range" min="1" max="100" step="1" value="1" name="page" />
</div>
JavaScript:
$(".slider").change(function() {
$("#query").text($("form").serialize());
});
Does that help?
Source: (StackOverflow)
I just discovered that at one point, the C++11 draft had std::begin
/std::end
overloads for std::pair
that allowed treating a pair of iterators as a range suitable for use in a range-based for loop (N3126, section 20.3.5.5), but this has since been removed.
Does anyone know why it was removed?
I find the removal very unfortunate, because it seems there is no other way to treat a pair of iterators as a range. Indeed:
- The lookup rules for begin/end in a range-based for loop say that begin/end are looked for in 1) as member functions of the range object 2) as free functions in "associated namespaces"
std::pair
does not have begin/end member functions
- The only associated namespace for
std::pair<T, U>
in general is namespace std
- We are not allowed to overload
std::begin
/std::end
for std::pair
ourselves
- We cannot specialize
std::begin
/std::end
for std::pair
(because the specialization would have to be partial and that's not allowed for functions)
Is there some other way that I am missing?
Source: (StackOverflow)
Random class has a method to generate random int in a given range. For example:
Random r = new Random();
int x = r.nextInt(100);
This would generate an int number more or equal to 0 and less than 100. I'd like to do exactly the same with long number.
long y = magicRandomLongGenerator(100);
Random class has only nextLong(), but it doesn't allow to set range.
Source: (StackOverflow)
I have an event with start_time
and end_time
and want to check if the event is "in progress". That would be to check if today's date is in the range between the two dates.
How would you do this in a function?
Source: (StackOverflow)
Is there a way to step between 0 and 1 by 0.1?
I thought I could do it like the following, but it failed:
for i in range(0, 1, 0.1):
print i
Instead, it says that the step argument cannot be zero, which I did not expect.
Source: (StackOverflow)
The way to iterate over a range in bash is
for i in {0..10}; do echo $i; done
What would be the syntax for iterating over the sequence with a step? Say, I would like to get only even number in the above example.
Source: (StackOverflow)
Suppose I have a std::vector
(let's call it myVec
) of size N
. What's the simplest way to construct a new vector consisting of a copy of elements X through Y, where 0 <= X <= Y <= N-1? For example, myVec [100000]
through myVec [100999]
in a vector of size 150000
.
If this cannot be done efficiently with a vector, is there another STL datatype that I should use instead?
Source: (StackOverflow)
I am using Ruby on Rails 3.0.9 and I would like to check if a number is included in a range. That is, if I have a variable number = 5
I would like to check 1 <= number <= 10
and retrieve a boolean value if the number
value is included in that range.
I can do that like this:
number >= 1 && number <= 10
but I would like to do that in one statement. How can I do that?
Source: (StackOverflow)
I'm new to programming. Can someone explain what .map
would do in:
params = (0...param_count).map
Source: (StackOverflow)
Is is possible to do this;
for i in range(some_number):
#do something
without the i? If you just want to do something x amount of times and don't need the iterator.
Source: (StackOverflow)
To generate a random number between 3 and 10, for example, I use: rand(8) + 3
Is there a nicer way to do this (something like rand(3, 10)
) ?
Source: (StackOverflow)