0
Can i automate range()?
I have written a simple code i.e a=0 b=10 for i in range(a,b): if i==20: print("jackpot") Now, as you can see, i is never gonna be 20, right? So my query is that, is it possible to automate the a and b variable in range()..by making a=b and increasing 'b' until it reaches 20? I am asking this question because, in certain problem solving questions it is asked to find out the largest number etc. , And for this purpose we need to change the range([max]) again and again if the largest number is in a larger range. So i was thinking about the above question.. If it's possible, help me!
8 Respostas
+ 2
Range is a special set of numbers. A range is once defined in the for line, and then it won't change.
What you want to do, sounds more like a case for the while loop.
while True:
...
And then handle a and b from within the body.
Exit with break.
+ 2
i = 0
xmax = 10
while i < xmax:
print("i: {0}, xmax: {1}".format(i, xmax)
if i == 20:
print("jackpot")
break
elif i == 5:
xmax = 20
elif i == 15:
xmax = 30
i += 1
#Point is that with while loop you can perform more customized loops.
+ 2
Amit Dubey
So the problem is we are given a range of numbers and we have to find the largest number from that range which divides the given number.
Solution:
you can start from the largest number specified in the range down to the smallest number in the range, and check if the number that you are choosing is dividing the given number than we can say its the largest factor.
so if the range is : 1 to 10000
given number is : 600851475143
then the code will look something like this:
n=600851475143
max=1
for i in range(10000,1,-1): # << solved
if n%i==0:
max=i
break
print(max)
+ 1
range objects are immutable.
They have start, stop and step attributes, but those can't be changed.
Making a generator object to fill the purpose sounds the best solution.
0
Well, i think i need to put the actual program in which i am having the problem...
So the problem is, i need to change the range function's limit again and again so as to get the largest prime factor..
In the attached program, i have taken enough range to get the correct result, but i had to change it from 100, 1000, 10000, 100000..so as to check if the largest Factor resides in those ranges....i need some type of solution that can automatically change the range and find the largest Factor.... that's the whole point of this discussion...
https://code.sololearn.com/cZBs3WfVfqbk/?ref=app