I've been learning python for about a week now, and I tried my hand at creating the binary search function:
def bin_srch(a, b, c, d):
l_c = map(int, c.split(" "))
l_d = map(int, d.split(" "))
for n in l_d:
if n <= l_c[a/2]:
for j in l_c[0:(a/2)+1]:
if j == n:
print l_c.index(j)+1,
elif n not in l_c[0:(a/2)+1]:
print -1,
elif n > l_c[a/2]:
for j in l_c[a/2:a]:
if j == n:
print l_c.index(j)+1,
elif n not in l_c[a/2:a]:
print -1,
However, when I test the function with some input:
bin_srch(5,6,
"10 30 50 60 70",
"60 10 50 10 5")
yields 4 1 3 1 -1 -1 -1 instead of 4 1 3 1 -1. Can anybody explain this?
While I don't really understand what you're code is supposed to be doing, I'm pretty sure I know the problem:
for j in l_c[0:(a/2)+1]:
if j == n:
print l_c.index(j)+1,
elif n not in l_c[0:(a/2)+1]:
print -1,
So, for each value, if it's a match, print the match (and keep looking); otherwise, check it against of the same values you're already looping over (and are going to continue to loop over) and if it's not found, print -1. So, if something isn't a match, you're going to print -1 multiple times.
What you probably want is:
for j in l_c[0:(a/2)+1]:
if j == n:
print l_c.index(j)+1,
break
else:
print -1,
At least this gives the desired output for this example. Why?
Well, the break means that as soon as you find a match, you stop going through the inner loop. The else—notice that it's attached to the for, not the if—runs if you finished the loop without ever break-ing. So, instead of checking for a match 3 times and printing -1 each time, you just check for a match 3 times and print -1 at the end, if you never found one.
(Actually, it looks like you could replace this whole loop with a list.index call, but I'll leave that up to you.)
Of course you have to make the same fix in the elif branch of your top-level if, because you have the same problem there.
Also, as a side note, if you write if n <= l_c[a/2]:, you don't need elif n > l_c[a/2]: Just use else; you already know that it's not true that n <= l_c[a/2] or you wouldn't have gotten here, therefore it must be true that n < l_c[a/2], so you don't need to check it.
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
We've been given a challenge to write a program that prints prime factors of an input number. We're given an outline: the program checks for factors of the original number; each such factor gets one point. Then, if that factor is prime, it gets another point. Each factor with two points gets printed.
Here's what I have so far.
print('Please enter a number')
x = int(input('Number:'))
a = int(0)
b = int(0)
c = int(1)
d = int(0)
counter = int(0)
while (a < x-1):
a = a + 1
counter = 0
if (x / a % 1 == 0):
b = a
counter = counter + 1
while(c < b - 1):
c = c + 1
if((b / c) % 1 != 0):
d = b
counter = counter + 1
if(counter == 2):
print(d)
With input of 15, I get 3 and 5, but also 15 (wrong). With 24, I get 3, 4, 6, 8, and 12; several of these are not prime.
I believe the issue lies somewhere in the innermost loop, but I can't pinpoint the problem.
At first the issue was I wasn't resetting the "counter", so future factors would exceed 2 "points" and nothing would print. I fixed that by resetting it before it enters the innermost loop, but sadly, that didn't fix the problem.
I've also tried getting rid of 'b' and 'd' and just using two variables to see if I was somehow overcomplicating it, but that didn't help either.
EDIT: Edited slightly for clarity.
Your first sentence was enough of a clue for me to unravel the rest of your posting. Your main problems are loop handling and logic of determining a prime factor.
In general, I see your program design as
Input target number
Find each factor of the number
For each factor, determine whether the factor is prime. If so, print it.
Now, let's look at the innermost loop:
while(c < b - 1):
c = c + 1
if((b / c) % 1 != 0):
d = b
counter = counter + 1
if(counter == 2):
print(d)
As a styling note, please explain why you are building for logic from while loops; this makes your program harder to read. Variable d does nothing for you. Also, your handling of counter is an extra complication: any time you determine that b is a prime number, then simply print it.
The main problem is your logical decision point: you look for factors of b. However, rather than waiting until you know b is prime, you print it as soon as you discover any smaller number that doesn't divide b. Since b-1 is rarely a factor of b (only when b=2), then you will erroneously identify any b value as a prime number.
Instead, you have to wait until you have tried all possible factors. Something like this:
is_prime = True
for c in range(2, b):
if b % c == 0:
is_prime = False
break
if is_prime:
print(b)
There are more "Pythonic" ways to do this, but I think that this is more within your current programming sophistication. If it's necessary to fulfill your assignment, you can add a point only when you've found no factors, and then check the count after you leave the for loop.
Can you take it from there?
I'm not entirely sure I follow you're problem description, but here is my attempt at interpreting it as best I can:
import math
def is_factor(n,m):
return m % n == 0
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def assign_points(n):
for i in range(1,n+1):
if is_factor(i,n) and is_prime(i):
print('two points for: ', i)
elif is_factor(i,n):
print('one point for: ', i)
print(assign_points(15))
Here's the code:
a = input()
b = map(int, raw_input().split())
maxcnt=1
for k in range(0,a):
cnt=1
j=k+1
while b[k]%b[j] == 0 or b[j]%b[k] == 0 :
cnt += 1
if maxcnt < cnt:
maxcnt = cnt
print maxcnt
While giving the list values, after giving the values separated with spaces, I press enter and it still keeps getting the input. What's the issue?
The statement b = map(int, raw_input().split()) is perfectly okay. The problem is that you are encountering an infinite loop in the later while part of your code. There should be some issue with the logic.
So, you are taking modulo of consecutive numbers in the list b ? So, an input like this:
b = [1,2,3,4]
will cause an infinite loop, since 1%2 == 0 or 2%1 ==0 => True. It is clearly an input dependent scenario.
Your code shows a while statement which does not change it's conditions while looping:
while (b[s] % b[j]) == 0 or
(b[j] % b[s]) == 0:
cnt += 1
As you can see here, cnt is not in the condition (b[s] % b[j]) == 0 or (b[j] % b[s]) == 0, therefore, it will just keep on incrementing cnt and will not stop.
What you see is an empty console (which you then thought meant it was asking for more input) which was actually just the while loop running continuously.
I am new to python. I am trying to write a program that counts a range of values but for multiples of 3 and 4 adds 3 and 4 to them resepectively and when the number is multiple of both adds that number to it. So for instance 1,2,3,4,5,6,7,8,9,10,11,12
should read in the end program as: 1,2,6,8,5,9,7,12,10,11,24
But my code is getting stuck somewhere.
for i in range (1,20):
if i%3==0 and i%4==0:
i=i+12
if i%3==0:
i=i+3
if i%4==0:
i=i+4
print i
This line has a typo
if i%3==0 and 1%4==0: # your second condition is 1 % 4 == 0, which is always false
I think you meant
if i%3==0 and i%4==0:
It is better (accurate and cleaner) if you use a different variable.
for i in range (1,20):
n = i
if i%3==0 and i%4==0:
n=i+12
if i%3==0:
n=i+3
if i%4==0:
n=i+4
print n
Now you will notice this fixed it for the 9 case, but not the 12 case! We now need to add the use of elif. Also, if a number is a multiple of 3 and 4, then it is also a multiple of their lowest common multiple, in this case 12. So you could re-write your first step to just check for multiples of 12. This gives us:
for i in range (1,20):
n = i
if i%12==0
n=i+12 # or possibly i + i
elif i%3==0:
n=i+3
elif i%4==0:
n=i+4
print n
The reason this works is because without the elif the i was getting added to multiple times. For example, with 9, you get to 9%3 ==0, True. Now i is set to 12. Next statement? 12%4 ==0 True. So another 4 is added.
Alternatively, if you would like to do some crazy python stuff:
for i in range(1, 20):
print i + next((n for n in (12, 4, 3) if i % n == 0), 0)
(Shout out to Jon Clements for this 2-liner answer)
You're allowing multiples cases (if conditions) for each iteration.
I think you probably wanted to do exclusive cases.
Maybe something like:
for i in range(1, 20):
print i, "=>",
if i % 3 == 0 and i % 4 == 0:
i += i
elif i % 3 == 0:
i += 3
elif i % 4 == 0:
i += 4
print i
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)