So, I have a script in python (2.7) that makes a list of 1000000 numbers between 1 and 5000 and then runs a for loop over the entire list checking each element against multiple embedded if statments.
ex:
i = 0
for number in random_list:
i += 1
if random_list[number] <= 3000:
i += 1
if random_list[number] <= 300:
i += 1
if random_list[number] <= 30:
i += 1
if random_list [number] <= 3:
i += 1
break
print i
the whole point being I want to see how many "checks" occur over the entire list.
unfortunately my i value is less than the total number of elements in the list which should not be the case since each element should be checked at least once. I'm getting something in the range of 1000's to 10000's.
I'm sure there's a more pythonic way of doing this, so any advice on how to achieve what I'm trying will be greatly appreciated.
extra = 0
values = (random_list[number] for i,number in enumerate(my_numbers))
for v in values:
extra += sum(v < x for x in [3000,300,30,3])
if v < 3:break;
print i+extra
maybe ...
Related
This question already has answers here:
how to stop a for loop
(9 answers)
Closed 2 years ago.
As I am getting more and more comfortable with writing scripts in Python I wrote a script that finds prime numbers by trying to divide each number in a range in each number (kinda like Brute Force haha).
It works but I wanted to make the process faster and more efficient.
My code:
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
j = j + 1
if count == 1:
print(i)
count = 0
Explanation:
I check and store in count how many time does a number can be divided.
If by the end of the check count equals 1 that means that the number is prime (gets divided only by itself).
What I want now is to stop the process of checking how many times the number can get divided when the "count" variable exceed 1 (2 or more). How do I do that?
I wanted to do something with try and except but didn't know what...
Add an extra condition in here, and break out of the loop if the count is greater than one. Put this inside the while loop:
if i % j == 0:
count += 1
if count > 1:
break
As mentioned in the comments, it's cleaner to just use count as part of the loop condition. Here's an improved version:
for i in range(2, 1000):
j = 2
count = 0
while j <= i and count < 2:
if i % j == 0:
count += 1
j += 1
if count == 1:
print(i)
Of course, there are faster ways to find if a number is prime - in particular, in the inner loop you should not iterate until 1000, not even until i is reached, just until the sqrt(i), but I'll leave that as an improvement for you to make ;)
You can try using break. What break does is that it skips the remaining part of the loop and jumps to the statement following the loop.
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
break
j = j + 1 ### line 8
if count == 1:
print(i)
count = 0
In this code, when python encounters break, it skips the remaining part of the loop (that is, the remaining loop is not executed) and jumps straight to the next statement, which is line 8
Its all wrong, first you have to understand the algorithm to check for prime, basically a number is prime if it can't be fully divided by any number between 2 to (number//2)-1
Now in your question, you couldn't use break anywhere, bcz you first searching for all divisible and then checking prime, better I'm adding a sample code to your problem which is more feasible to find primes
Code
number = int(input("Enter A Number"))
for i in range(2,number//2+1): #See range arguments
if(number%i==0):
print("Not A Prime")
break #Break loop when condition reached
I'm essentially trying to re-create a version of the insert() function for a homework assignment.
I've written the following function:
def insert_value(my_list, value, insert_position):
list_copy = []
if insert_position < 0:
insert_position = 0
if insert_position >= len(my_list):
insert_position = len(my_list) - 1
i = 0
while i < len(my_list) + 1:
while i < insert_position:
list_copy.append(my_list[i])
i += 1
while i == insert_position:
list_copy.append(value)
i += 1
while i > insert_position:
list_copy.append(my_list[i-1])
i += 1
return list_copy
I get the error list index out of range for the final while sub-loop, and I can't work out why. The while loop is accounting for the new list length (while i < len(my_list) + 1). What am I missing?
Your problem is because you are using those nested while loops which do not exit until their condition is false. So the outer while loop check for i being less then the length of my_list doesn't happen until all nested while loops finish (which it never does). Specifically I think the issue is with the last while loop here:
while i > insert_position:
list_copy.append(my_list[i-1])
i += 1
This while loop will not end because i will always be greater then the insert_position and eventually the i value will be outside the length of your my_list.
If you change your code logic to use if statements inside the while loop I think that will be better and then you only have to increase i once at the end:
i = 0
while i < len(my_list) + 1:
if i < insert_position:
list_copy.append(my_list[i])
elif i == insert_position:
list_copy.append(value)
else:
list_copy.append(my_list[i-1])
i += 1
I am having trouble finish python code.
overlap('','hello') → 0.
I have managed to get the number back when the length of the strings match but if one of the strings has a smaller length than the other. I keep getting index out of range. Can someone help me finish this.
def overlap(string1,string2):
count = 0
for i in range(len(string1)):
for j in range(len(string2)):
if string1[i] == string2[j]:
count = count + 1
i+=1
else:
i+=1
return count
When running this with a function call. if both strings are equal it gives me the correct number, but if one is smaller or longer then its index out of range.
Thanks
Create one for loop which iterates through min(len(string1), len(string2)) and you would avoid problem when one string is smaller than another, see sample below:
def overlap(string1,string2):
count = 0
for i in range(min(len(string1), len(string2))):
if string1[i] == string2[i]:
count = count + 1
return count
print overlap('summer','winter') #2
print overlap('abcb','dbeb') #2
print overlap('summer','sum') #3
print overlap('','winter') #0
Good Luck!
Replace the nested loops and repeat only for the smaller length.
def overlap(string1, string2):
count=0;
len1= len(string1)
len2= len(string2)
smallLen= len1
if len2<len1:
smallLen= len2
for i in range(smallLen):
if string1[i]== string2[i]:
count+= 1
return count
Thinking about it in order of things that need to be done, you have to first figure out which of the two given strings have the shortest length because that will be your bound for the amount of loop iterations. In Python you can do a conditional assignment like:
maxloop = len(str1) if len(str1) <= len(str2) else len(str2)
You make the condition <= because it doesnt matter which is chosen if they're equal, so just pick the first.
Now that you have the amount of iterations you'll do, you can set up the loop and counter:
count = 0
for i in range(maxloop):
if str1[i] == str2[i]:
count += 1
The single if statement is checking the character at position i in both strings and seeing if they are equal, and if they are, then it'll add one to the overlap counter. Then simply return the count after the loop has terminated.
Try this:
count = 0
if len(string1) < len(string2):
for i in range(len(string1)):
if string1[i] == string2[i]:
count += 1
else:
for i in range(len(string2)):
if string1[i] == string2[i]:
count += 1
return count
I'm trying to solve the following question: What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? The problem is that I get a MemoryError. Is there a better way to do this, using the same logic?
for n in range(1,1000000000):
count = 0
for i in range(1,21):
if n%i == 0:
count = count + 1
if count == 20:
print n
Thanks
Assuming you're using Python 2, range allocates a list.
Utilize Python's lazy abilities with generators* , and use xrange instead.
for n in xrange(1,1000000000):
count = 0
for i in xrange(1,21):
if n%i == 0:
count = count + 1
if count == 20:
print n
That should solve your memory error. That said, there is a much faster solution to that particular problem (however, you asked for 'using the same logic').
* actually, a sequence object
I'm stuck on a Python 101 type problem involving loops. Here are the directions:
The square numbers are the integers of the form K × K, e.g. 9 is a square number since 3 × 3 = 9. Write a program that reads an integer n from input and outputs all the positive square numbers less than n, one per line in increasing order. For example, if the input is 16, then the correct output would be
1
4
9
This is what I have so far but it sort of works but runs on forever. My code never reaches the if statement so it breaks(stops) before it gets to 17.
Suppose n = 17.
n=int(input())
counter = 1
while counter * counter < n:
for counter in range(1,n):
a = counter*counter
print(a)
if a < n:
break
Results:
1
4
9
16
25
36
49
64
81
Here is a correction of your code.
n=int(input())
counter = 1
for counter in range(1,n):
a = counter*counter
if a >= n:
break
print(a)
There were three things wrong with your code. First, the condition you want to break on is a >= n not a < n. Second, that condition needs to be tested before you print the number. Thus the if statement needs to be inside the for loop and before your print, statement. Third, the outer while loop is not really necessary :) Though you can add it, but a simple inner for loop will suffice.
if a < n: will never succeed unless n = 2; because inside the loop a is becoming (n-1)*(n-1) which is greater than n for n > 2; that's why the infinite loop. Try this:
>>> counter = 1
>>> n = 16 # int(input())
>>> r = counter**2
>>> while r<n:
print r
counter += 1
r = counter**2
1
4
9
Or just modify yours one by removing the outer loop, and placing the conditional inside the for loop like:
for counter in range(1,n):
a = counter*counter
if a >= n:break
print(a)
Your code loops might be the case in you semantics error try this out light on the memory and simple
def number(n):
for i in range(0,n):
w=i*i
if w>n-1:
break
print(w)
number(144)
You've got three issues here, but, as you can tell, you're on the right track.
First off, you're using two loops when you only need to be using one, and I think it's because you're a little unclear as to how the while loop works. The while loop checks that the condition is true before each time it runs. If the condition becomes false while going through the loop, the loop will still finish - it just won't start another. For example:
n = 17
while n < 18:
n += 1
print n
n += 1
print n
prints:
18
19
In your case, each iteration through the while loop creates a for loop. In order for a single iteration through the while to take place, your computer has to go through for every number from 1 to n, meaning that it'll print out all those extra numbers before your while loop even has a second chance to do its check. The easiest way to fix this is to remove the while loop and structure your code a little differently. As I'll show you in a few lines, you don't really need it.
When you say if a < n:, you've got your sign backwards and you need an equals sign. The problem asks that you give all values less than n, but, without the =, the program won't stop until it's greater than n. It should be if a >= n:.
Finally, the order of the operations isn't what you want it to be. You'd like it to check that a is less than n before printing, but you print before you do that check. If you switch them around, you'll get something like this:
n=int(input())
for counter in range(1,n):
a = counter*counter
if a >= n:
break
print(a)
which should do the trick.
What about
n= int(input())
counter= 1
while counter * counter < n:
print( counter * counter )
counter+= 1
?
Turtle man was perfect but for me. I needed to be able to get all the way to 100 so if you need to get past 81 do this
n = int(input())
counter = 1
for counter in range(1,n + 1):
a = counter*counter
if a > n:
break
print(a)