I could successfully rum a simple program to check whether the number is prime or not in C. The code looks like this
void isPrime(int n)
{
int a=0,i;
for(i=1;i<=n;i++)
{
if(n%i==0)
a++;
}
if(a==2)
{
printf("\n%d is prime",n);
}
else
{
printf("\n%d is not prime",n);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i=2;i<=20;i++)
{
isPrime(i);
}
return 0;
}
The above code runs perfectly when I compile. I am a beginner in python and I have converted the same code into python, which looks like this.
def isPrime(n):
a=0
for x in range(1,n):
if n%x==0:
a=a+1
if a==2:
print("{} is prime".format(n))
else:
print("{} is not prime".format(n))
for n in range(2,20):
isPrime(n)
But I get a wrong output in python. The output is somewhat weird which says
2 is not prime
3 is not prime
4 is prime
5 is not prime
6 is not prime
7 is not prime
8 is not prime
9 is prime
10 is not prime
11 is not prime
12 is not prime
13 is not prime
14 is not prime
15 is not prime
16 is not prime
17 is not prime
18 is not prime
19 is not prime
I have found out that the count of 'a' is 1 less than the actual count required. For example, in case of n=8, a should be 4. But its getting counted as 3.
What could be the reason?
Why don't you add some print statements so you can see where the code fails? Adding some prints should be your first reflex when debugging.
def isPrime(n):
a=0
for x in range(1,n):
print('x,a', x,a)
if n%x==0:
print('incrementing a...')
a=a+1
print('a after loop:', a)
if a==2:
print("{} is prime".format(n))
else:
print("{} is not prime".format(n))
Output for isPrime(2):
x,a 1 0
incrementing a...
a after loop: 1
2 is not prime
Output for isPrime(7):
x,a 1 0
incrementing a...
x,a 2 1
x,a 3 1
x,a 4 1
x,a 5 1
x,a 6 1
a after loop: 1
7 is not prime
As you can see, a is never 2 because the n%n test is never executed, because with x in range(1,n), the last value for x is n-1. However, if you change your range to range(1,n+1), the test will be made:
x,a 1 0
incrementing a...
x,a 2 1
x,a 3 1
x,a 4 1
x,a 5 1
x,a 6 1
x,a 7 1
incrementing a...
a after loop: 2
7 is prime
The issue you have is that the last value produced range(start, stop) is stop-1; see the docs. Thus, isPrime should have the following for loop:
for x in range(1, n+1):
This will faithfully replicate the C code, and produce the correct output. (Note that this is also why you are only checking the numbers [2, 19] for whether they're prime, as opposed to [2, 20].)
I think the problem was with your range as mentioned above. Can I give you some short tips to make your code more "Pythonic"? :)
Instead of
if n%x==0
you would simply write
if not n%x
and instead of
a=a+1
you could use the in-place operator, e.g.,
a += 1
Here, it wouldn't make much of a difference, but if you are working with mutable objects (due to the __iadd__ method, I have more details here) you would gain a significant performance increase, e.g.,
def slow(a):
for i in range(1000):
a = a + [1,2]
def fast(a):
for i in range(1000):
a += [1,2]
a = []
b = []
%timeit -r 3 -n 1000 slow(a)
%timeit -r 3 -n 1000 fast(b)
1000 loops, best of 3: 2.94 ms per loop
1000 loops, best of 3: 181 µs per loop
Same for the binary operator instead of the format() method, however, I like the latter one better (due to its more powerful minilanguange and I would recommend it if you don't care about speed in certain computations)
%timeit -r 3 -n 1000 '{} World'.format('Hello')
%timeit -r 3 -n 1000 '%s World' %('Hello')
1000 loops, best of 3: 472 ns per loop
1000 loops, best of 3: 27.3 ns per loop
def isPrime(n):
a = 0
for x in range(1, n+1):
if not n%x:
a += 1
if a==2:
print("{} is prime".format(n))
else:
print("{} is not prime".format(n))
for n in range(2, 20):
isPrime(n)
Related
I'm a newbie at python. I started it not long a ago as a hobby after uni lecture hours.
I found this exercise ( forgot where I got it from now) to do which is to print out the factorial numbers.
Which I did. But, problem is that I'm tasked to manipulate line 3 so it only prints out the number 1 once at the start of the sequence and I'm having trouble with that.
Please can any help? :)
In advance sorry if the question wasn't worded as good as it could have been.
a, b = 0, 1
while a < 19:
print b,
a, b = a + 1, b * (a+1)
Result:
1 1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 6227020800 87178291200 1307674368000 20922789888000 355687428096000 6402373705728000
a, b = 0, 1
while a < 19:
if a: print b,
a, b = a + 1, b * (a+1)
Use a in-line if statement to check if a is 1. If it's 1 then you know that you already went through the loop at least once.
How do I determine whether a given integer is between two other integers (e.g. greater than/equal to 10000 and less than/equal to 30000)?
What I've attempted so far is not working:
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
if 10000 <= number <= 30000:
pass
For details, see the docs.
>>> r = range(1, 4)
>>> 1 in r
True
>>> 2 in r
True
>>> 3 in r
True
>>> 4 in r
False
>>> 5 in r
False
>>> 0 in r
False
Your operator is incorrect. It should be if number >= 10000 and number <= 30000:. Additionally, Python has a shorthand for this sort of thing, if 10000 <= number <= 30000:.
Your code snippet,
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
actually checks if number is larger than both 10000 and 30000.
Assuming you want to check that the number is in the range 10000 - 30000, you could use the Python interval comparison:
if 10000 <= number <= 30000:
print ("you have to pay 5% taxes")
This Python feature is further described in the Python documentation.
There are two ways to compare three integers and check whether b is between a and c:
if a < b < c:
pass
and
if a < b and b < c:
pass
The first one looks like more readable, but the second one runs faster.
Let's compare using dis.dis:
>>> dis.dis('a < b and b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 COMPARE_OP 0 (<)
6 JUMP_IF_FALSE_OR_POP 14
8 LOAD_NAME 1 (b)
10 LOAD_NAME 2 (c)
12 COMPARE_OP 0 (<)
>> 14 RETURN_VALUE
>>> dis.dis('a < b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 DUP_TOP
6 ROT_THREE
8 COMPARE_OP 0 (<)
10 JUMP_IF_FALSE_OR_POP 18
12 LOAD_NAME 2 (c)
14 COMPARE_OP 0 (<)
16 RETURN_VALUE
>> 18 ROT_TWO
20 POP_TOP
22 RETURN_VALUE
>>>
and using timeit:
~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop
~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop
also, you may use range, as suggested before, however it is much more slower.
if number >= 10000 and number <= 30000:
print ("you have to pay 5% taxes")
Define the range between the numbers:
r = range(1,10)
Then use it:
if num in r:
print("All right!")
The trouble with comparisons is that they can be difficult to debug when you put a >= where there should be a <=
# v---------- should be <
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
Python lets you just write what you mean in words
if number in xrange(10000, 30001): # ok you have to remember 30000 + 1 here :)
In Python3, you need to use range instead of xrange.
edit: People seem to be more concerned with microbench marks and how cool chaining operations. My answer is about defensive (less attack surface for bugs) programming.
As a result of a claim in the comments, I've added the micro benchmark here for Python3.5.2
$ python3.5 -m timeit "5 in range(10000, 30000)"
1000000 loops, best of 3: 0.266 usec per loop
$ python3.5 -m timeit "10000 <= 5 < 30000"
10000000 loops, best of 3: 0.0327 usec per loop
If you are worried about performance, you could compute the range once
$ python3.5 -m timeit -s "R=range(10000, 30000)" "5 in R"
10000000 loops, best of 3: 0.0551 usec per loop
Below are few possible ways, ordered from best to worse performance (i.e first one will perform best)
# Old school check
if 10000 >= b and b <=30000:
print ("you have to pay 5% taxes")
# Python range check
if 10000 <= number <= 30000:
print ("you have to pay 5% taxes")
# As suggested by others but only works for integers and is slow
if number in range(10000,30001):
print ("you have to pay 5% taxes")
While 10 <= number <= 20 works in Python, I find this notation using range() more readable:
if number in range(10, 21):
print("number is between 10 (inclusive) and 21 (exclusive)")
else:
print("outside of range!")
Keep in mind that the 2nd, upper bound parameter is not included in the range set as can be verified with:
>>> list(range(10, 21))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
However prefer the range() approach only if it's not running on some performance critical path. A single call is still fast enough for most requirements, but if run 10,000,000 times, we clearly notice nearly 3 times slower performance compared to a <= x < b:
> { time python3 -c "for i in range(10000000): x = 50 in range(1, 100)"; } 2>&1 | sed -n 's/^.*cpu \(.*\) total$/\1/p'
1.848
> { time python3 -c "for i in range(10000000): x = 1 <= 50 < 100"; } 2>&1 | sed -n 's/^.*cpu \(.*\) total$/\1/p'
0.630
Suppose there are 3 non-negative integers: a, b, and c. Mathematically speaking, if we want to determine if c is between a and b, inclusively, one can use this formula:
(c - a) * (b - c) >= 0
or in Python:
> print((c - a) * (b - c) >= 0)
True
You want the output to print the given statement if and only if the number falls between 10,000 and 30,000.
Code should be;
if number >= 10000 and number <= 30000:
print("you have to pay 5% taxes")
You used >=30000, so if number is 45000 it will go into the loop, but we need it to be more than 10000 but less than 30000. Changing it to <=30000 will do it!
I'm adding a solution that nobody mentioned yet, using Interval class from sympy library:
from sympy import Interval
lower_value, higher_value = 10000, 30000
number = 20000
# to decide whether your interval shhould be open or closed use left_open and right_open
interval = Interval(lower_value, higher_value, left_open=False, right_open=False)
if interval.contains(number):
print("you have to pay 5% taxes")
Try this simple function; it checks if A is between B and C (B and C may not be in the right order):
def isBetween(A, B, C):
Mi = min(B, C)
Ma = max(B, C)
return Mi <= A <= Ma
so isBetween(2, 10, -1) is the same as isBetween(2, -1, 10).
The condition should be,
if number == 10000 and number <= 30000:
print("5% tax payable")
reason for using number == 10000 is that if number's value is 50000 and if we use number >= 10000 the condition will pass, which is not what you want.
I want to iterate through numbers which met a specific condition. I have done it with the following code. But it has two for loops which may not be efficient. Is it possible to make this code shorter?
for g in [i for i in range(10) if i % 2 == 0]:
print(g)
I tried the following but this syntax does not work:
for i in range(10) if i % 2 == 0:
print(i)
The second syntax is invalid, but you can split it into two lines:
for i in range(10):
if i % 2 == 0:
print(i)
If shortening your code is the motive(which shouldn't be), then here are 2 one-liners:
>>> print('\n'.join(map(str, filter(lambda x:not x%2, range(10)))))
0
2
4
6
8
or
>>> print('\n'.join(map(str, range(0, 10, 2))))
0
2
4
6
8
How do I determine whether a given integer is between two other integers (e.g. greater than/equal to 10000 and less than/equal to 30000)?
What I've attempted so far is not working:
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
if 10000 <= number <= 30000:
pass
For details, see the docs.
>>> r = range(1, 4)
>>> 1 in r
True
>>> 2 in r
True
>>> 3 in r
True
>>> 4 in r
False
>>> 5 in r
False
>>> 0 in r
False
Your operator is incorrect. It should be if number >= 10000 and number <= 30000:. Additionally, Python has a shorthand for this sort of thing, if 10000 <= number <= 30000:.
Your code snippet,
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
actually checks if number is larger than both 10000 and 30000.
Assuming you want to check that the number is in the range 10000 - 30000, you could use the Python interval comparison:
if 10000 <= number <= 30000:
print ("you have to pay 5% taxes")
This Python feature is further described in the Python documentation.
There are two ways to compare three integers and check whether b is between a and c:
if a < b < c:
pass
and
if a < b and b < c:
pass
The first one looks like more readable, but the second one runs faster.
Let's compare using dis.dis:
>>> dis.dis('a < b and b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 COMPARE_OP 0 (<)
6 JUMP_IF_FALSE_OR_POP 14
8 LOAD_NAME 1 (b)
10 LOAD_NAME 2 (c)
12 COMPARE_OP 0 (<)
>> 14 RETURN_VALUE
>>> dis.dis('a < b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 DUP_TOP
6 ROT_THREE
8 COMPARE_OP 0 (<)
10 JUMP_IF_FALSE_OR_POP 18
12 LOAD_NAME 2 (c)
14 COMPARE_OP 0 (<)
16 RETURN_VALUE
>> 18 ROT_TWO
20 POP_TOP
22 RETURN_VALUE
>>>
and using timeit:
~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop
~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop
also, you may use range, as suggested before, however it is much more slower.
if number >= 10000 and number <= 30000:
print ("you have to pay 5% taxes")
Define the range between the numbers:
r = range(1,10)
Then use it:
if num in r:
print("All right!")
The trouble with comparisons is that they can be difficult to debug when you put a >= where there should be a <=
# v---------- should be <
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
Python lets you just write what you mean in words
if number in xrange(10000, 30001): # ok you have to remember 30000 + 1 here :)
In Python3, you need to use range instead of xrange.
edit: People seem to be more concerned with microbench marks and how cool chaining operations. My answer is about defensive (less attack surface for bugs) programming.
As a result of a claim in the comments, I've added the micro benchmark here for Python3.5.2
$ python3.5 -m timeit "5 in range(10000, 30000)"
1000000 loops, best of 3: 0.266 usec per loop
$ python3.5 -m timeit "10000 <= 5 < 30000"
10000000 loops, best of 3: 0.0327 usec per loop
If you are worried about performance, you could compute the range once
$ python3.5 -m timeit -s "R=range(10000, 30000)" "5 in R"
10000000 loops, best of 3: 0.0551 usec per loop
Below are few possible ways, ordered from best to worse performance (i.e first one will perform best)
# Old school check
if 10000 >= b and b <=30000:
print ("you have to pay 5% taxes")
# Python range check
if 10000 <= number <= 30000:
print ("you have to pay 5% taxes")
# As suggested by others but only works for integers and is slow
if number in range(10000,30001):
print ("you have to pay 5% taxes")
While 10 <= number <= 20 works in Python, I find this notation using range() more readable:
if number in range(10, 21):
print("number is between 10 (inclusive) and 21 (exclusive)")
else:
print("outside of range!")
Keep in mind that the 2nd, upper bound parameter is not included in the range set as can be verified with:
>>> list(range(10, 21))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
However prefer the range() approach only if it's not running on some performance critical path. A single call is still fast enough for most requirements, but if run 10,000,000 times, we clearly notice nearly 3 times slower performance compared to a <= x < b:
> { time python3 -c "for i in range(10000000): x = 50 in range(1, 100)"; } 2>&1 | sed -n 's/^.*cpu \(.*\) total$/\1/p'
1.848
> { time python3 -c "for i in range(10000000): x = 1 <= 50 < 100"; } 2>&1 | sed -n 's/^.*cpu \(.*\) total$/\1/p'
0.630
Suppose there are 3 non-negative integers: a, b, and c. Mathematically speaking, if we want to determine if c is between a and b, inclusively, one can use this formula:
(c - a) * (b - c) >= 0
or in Python:
> print((c - a) * (b - c) >= 0)
True
You want the output to print the given statement if and only if the number falls between 10,000 and 30,000.
Code should be;
if number >= 10000 and number <= 30000:
print("you have to pay 5% taxes")
You used >=30000, so if number is 45000 it will go into the loop, but we need it to be more than 10000 but less than 30000. Changing it to <=30000 will do it!
I'm adding a solution that nobody mentioned yet, using Interval class from sympy library:
from sympy import Interval
lower_value, higher_value = 10000, 30000
number = 20000
# to decide whether your interval shhould be open or closed use left_open and right_open
interval = Interval(lower_value, higher_value, left_open=False, right_open=False)
if interval.contains(number):
print("you have to pay 5% taxes")
Try this simple function; it checks if A is between B and C (B and C may not be in the right order):
def isBetween(A, B, C):
Mi = min(B, C)
Ma = max(B, C)
return Mi <= A <= Ma
so isBetween(2, 10, -1) is the same as isBetween(2, -1, 10).
The condition should be,
if number == 10000 and number <= 30000:
print("5% tax payable")
reason for using number == 10000 is that if number's value is 50000 and if we use number >= 10000 the condition will pass, which is not what you want.
I want to print all the prime numbers from 1 to 10 but nothing gets printed when i run the program
c=0
nums = []
k=0
for a in range(1,11):
for b in range(1,11):
if a%b==0:
c = c+1
if c==2:
nums.append(a)
k = k+1
for d in nums:
print nums[d]
I can't figure out why you are using k
and your c should reset in "a" loop and out of "b" loop
code like this:
nums = []
for a in range(1, 11):
c = 0
for b in range(1, 11):
if a % b == 0:
c = c + 1
if c == 2:
nums.append(a)
print nums
You should reset c to zero before the beginning of each inner loop:
nums = []
for a in range(1,11):
c = 0
for b in range(1,11):
if a%b==0:
c = c+1
if c==2:
nums.append(a)
for d in nums:
print d
Additionally, you should use print d, since the for-loop already gives every element in nums.
Using a list comprehension is generally faster and considered more pythonic than using a for-loop.
There are many different ways of calculating prime numbers. Here are some of them.
Here is your original algorithm, with some improvements;
def prime_list(num):
"""Returns a list of all prime numbers up to and including num.
:num: highest number to test
:returns: a list of primes up to num
"""
if num < 3:
raise ValueError('this function only accepts arguments > 2')
candidates = range(3, num+1, 2)
L = [c for c in candidates if all(c % p != 0 for p in range(3, c, 2))]
return [2] + L
For primes >2, they must be odd numbers. So candidates should contain only odd numbers.
For an odd number c to be prime, one must ensure that c modulo all previous odd numbers (p) must be non-zero.
Lastly, 2 is also prime.
A further improvement is to restrict p up to sqrt(c):
import math
def prime_list2(num):
if num < 3:
raise ValueError('this function only accepts arguments > 2')
candidates = range(3, num+1, 2)
L = [c for c in candidates if all(c % p != 0 for p in
range(3, int(math.sqrt(c))+1, 2))]
return [2] + L
Another implementation:
def prime_list3(num):
num += 1
candidates = range(3, num, 2)
results = [2]
while len(candidates):
t = candidates[0]
results.append(t)
candidates = [i for i in candidates if not i in range(t, num, t)]
return results
This starts off with a list of candidates that contains all odd numbers. Then is calculates a new list of candidates by removing the first number of the previous list and all all multiples of it.
Let's look at the speed of the algorithms.
For small numbers, the original prime_list is the fastest;
In [8]: %timeit prime_list(10)
100000 loops, best of 3: 8.68 µs per loop
In [9]: %timeit prime_list2(10)
100000 loops, best of 3: 10.9 µs per loop
In [10]: %timeit prime_list3(10)
100000 loops, best of 3: 8.96 µs per loop
For larger numbers, prime_list2 comes out the winner:
In [5]: %timeit prime_list(1000)
100 loops, best of 3: 8.28 ms per loop
In [6]: %timeit prime_list2(1000)
100 loops, best of 3: 2.46 ms per loop
In [7]: %timeit prime_list3(1000)
10 loops, best of 3: 23.5 ms per loop
In [11]: %timeit prime_list(10000)
1 loops, best of 3: 646 ms per loop
In [12]: %timeit prime_list2(10000)
10 loops, best of 3: 25.4 ms per loop
In [13]: %timeit prime_list3(10000)
1 loops, best of 3: 2.13 s per loop
I added two print statements to your code - first, under if a%b==0:, I added print a,b; and I print the final value of c after that loop. I get this output:
1 1
1
2 1
2 2
3
3 1
3 3
5
4 1
4 2
4 4
8
5 1
5 5
10
6 1
6 2
6 3
6 6
14
7 1
7 7
16
8 1
8 2
8 4
8 8
20
9 1
9 3
9 9
23
10 1
10 2
10 5
10 10
27
This tells you why you get nothing printed: after the b loop in a == 1, c is 1; after the same loop in the next iteration of the outer loop, c is now 3. So c==2 is never True when that test is made, so nums stays empty.
This also gives you a big hint as to what you need to do to fix it. c keeps increasing, but it should start counting afresh for each iteration of the outer loop - so, move your c=0 to be inside the outer for loop. You also need to change your final print loop to print d instead of print nums[d], or you will get another error. With those changes, your code looks like this:
nums = []
k=0
for a in range(1,11):
c=0
for b in range(1,11):
if a%b==0:
c = c+1
if c == 2:
nums.append(a)
k = k+1
for d in nums:
print d
and it prints
2
3
5
7
as expected.
Your c is not reset to zero inside the loop (the first loop). So set c=0 after line: for a in range(1,11):
I dont know what your k is for. Is it usefull for anything?
Printing the prime numbers dont do nums[d], print d. You are looping on the items not on the indices.
Your code has multiple issues - Every prime number is divisible by 1 so your checks will fail, you are printing nums[d] which is wrong, k is doing nothing, variable nomenclature is too obfuscated, you have unnecessary runs in for loop - you don't need to iterate for all values of b in range, it is sufficient to iterate over existing prime numbers and so on.
Here is how I would write it
primes = [2]
upper_limit = 1000 #find all primes < 1000
for candidate in range(2, upper_limit):
can_be_prime = True
for prime in primes:
if candidate % prime == 0:
can_be_prime = False
break
if can_be_prime:
primes.append(candidate)
print primes
This solution is a little neater:
nums = []
for a in range(2, 101):
for b in range(2, a):
if a % b == 0:
break
else:
nums.append(a)
print nums
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Still, there is no point trying b > sqrt(a).
Try this:
nums = []
k=0
for a in range(2,11):
c=0
for b in range(1,11):
if a%b==0:
c = c+1
if c==2:
nums.append(a)
k = k+1
for d in nums:
print d
You will get
2
3
5
7
Note the code could be more efficient.