Basically trying to learn Python and I was doing the hackerrank 30 day challenge.
Task
Given an integer, n , perform the following conditional actions:
If n is odd, print ok
If n is even and in the inclusive range of 2 to 5, print nok
n = 4
if n in range(2,5) and type(n/2) == int:
print ("ok")
else:
print ("nok")
it prints "nok" no matter what n is.
In Python 3 / always returns a float (isinstance(4 / 2, int) is False since 4 / 2 returns 2.0).
Since you are essentially checking for the parity of n, check it explicitly:
... and n % 2 == 0:
Because, n/2 = 2.0 not 2, i.e division returns a float not int here are some ways to check it :
n in range(2,5) and n % 2 == 0
#or
n in range(2,5) and n & 1 != 1 #because, every odd number has last bit 1
Related
I need to test whether each number from 1 to 1000 is a multiple of 3 or a multiple of 5.
I tried this code in Python 2.x:
n = 0
s = 0
while (n < 1001):
x = n/3
if isinstance(x, (int, long)):
print 'Multiple of 3!'
s = s + n
if False:
y = n/5
if isinstance(y, (int, long)):
s = s + n
print 'Number: '
print n
print 'Sum:'
print s
n = n + 1
The idea is to try dividing the number and see if the result is an integer. However, I'm not getting the expected result.
How do I test whether the number is an integer?
In 2.x, division like this will produce an integer, discarding the remainder; see How can I force division to be floating point? Division keeps rounding down to 0? for details.
In 3.x, the division will produce a floating-point value; the result is not "an integer" even if it is a whole number, so the isinstance check will fail. See Why does integer division yield a float instead of another integer? for details.
If you need the remainder from integer division rather than just testing for divisibility, see Find the division remainder of a number.
You do this using the modulus operator, %
n % k == 0
evaluates true if and only if n is an exact multiple of k. In elementary maths this is known as the remainder from a division.
In your current approach you perform a division and the result will be either
always an integer if you use integer division, or
always a float if you use floating point division.
It's just the wrong way to go about testing divisibility.
You can simply use % Modulus operator to check divisibility.
For example: n % 2 == 0 means n is exactly divisible by 2 and n % 2 != 0 means n is not exactly divisible by 2.
You can use % operator to check divisiblity of a given number
The code to check whether given no. is divisible by 3 or 5 when no. less than 1000 is given below:
n=0
while n<1000:
if n%3==0 or n%5==0:
print n,'is multiple of 3 or 5'
n=n+1
This code appears to do what you are asking for.
for value in range(1,1000):
if value % 3 == 0 or value % 5 == 0:
print(value)
Or something like
for value in range(1,1000):
if value % 3 == 0 or value % 5 == 0:
some_list.append(value)
Or any number of things.
I had the same approach. Because I didn't understand how to use the module(%) operator.
6 % 3 = 0
*This means if you divide 6 by 3 you will not have a remainder, 3 is a factor of 6.
Now you have to relate it to your given problem.
if n % 3 == 0
*This is saying, if my number(n) is divisible by 3 leaving a 0 remainder.
Add your then(print, return) statement and continue your
a = 1400
a1 = 5
a2 = 3
b= str(a/a1)
b1 = str(a/a2)
c =b[(len(b)-2):len(b)]
c1 =b[(len(b1)-2):len(b1)]
if c == ".0":
print("yeah for 5!")
if c1 == ".0":
print("yeah for 3!")
For small numbers n%3 == 0 will be fine. For very large numbers I propose to calculate the cross sum first and then check if the cross sum is a multiple of 3:
def is_divisible_by_3(number):
if sum(map(int, str(number))) % 3 != 0:
my_bool = False
return my_bool
Try this ...
public class Solution {
public static void main(String[] args) {
long t = 1000;
long sum = 0;
for(int i = 1; i<t; i++){
if(i%3 == 0 || i%5 == 0){
sum = sum + i;
}
}
System.out.println(sum);
}
}
The simplest way is to test whether a number is an integer is int(x) == x. Otherwise, what David Heffernan said.
I want to make a function where given a number like 7 I want to factorise the number by as many 3s and 2s. If left with a remainder then return -1.
Note: Through further examples it seems any number can be made up of the addition of multiples of 3s and 2s so -1 for remainder not needed. Goal is to get as many multiples of 3 before having to add multiples of 2 to factorise completely
For example given the number 11 I want the function to return 3:3 and 2:1 as 3 fits into 11 3 times and 2 once ie. 3+2+2=7, 3+3+3+2=11, 3+3+3+2+2=13. The preference should be being able to fit as many 3s first.
This is part of a wider problem:
from collections import Counter
#Choose two packages of the same weight
#Choose three packages of the same weight
#Minimum number of trips to complete all the deliveries else return -1
def getMinimumTrips(weights):
weights_counted = Counter(weights)
minimum_trips = 0
print(weights_counted)
for i in weights_counted:
if weights_counted[i]==1:
return -1
elif weights_counted[i]%3==0:
minimum_trips += (weights_counted[i]//3)
elif weights_counted[i]%2==0:
minimum_trips += (weights_counted[i]//2)
return minimum_trips
print(getMinimumTrips([2, 4, 6, 6, 4, 2, 4]))
Possible solution:
#Looking at inputs that are not a multiple of 3 or 2 eg, 5, 7, 11, 13
def get_components(n):
f3 = 0
f2 = 0
if n%3==1:
f3 = (n//3)-1
f2 = 2
elif n%3==2:
f3 = (n//3)
f2=1
return f"3:{f3}, 2:{f2}"
If we are given some integer value x we have 3 different cases:
x == 3 * n, solution: return 3 n times. The easiest case.
x == 3 * n + 1, solution: return 3 n - 1 times, then return 2 2 times, Note that we can put 3 * n + 1 == 3 * (n - 1) + 2 + 2
x == 3 * n + 2, solution: return 3 n times, then return 2.
As one can see in cases #1 and #3 solutions ever exist; in case #2 there's no solution for x = 1 (we can't return 3 -1 times). So far so good if x <= 1 we return -1 (no solutions), otherwise we perform integer division // and obtain n, then find remainder % and get the case (remainder 0 stands for case #1, 1 for case #2, 2 for case #3). Since the problem looks like a homework let me leave the rest (i.e. exact code) for you to implement.
This will return 0 if you can completely factorise the number, or -1 if 1 is remaining:
return -(i % 3 % 2)
If this helps?
Try this method using math.floor()
import math
def get_components(n: int) -> str:
q3 = math.floor(n / 3)
q2 = math.floor(q3 / 2)
if not (q3 and q2):
return '-1' # returning '-1' as a string here for consistency
return f'3:{q3}, 2:{q2}'
This question already has answers here:
Fast prime factorization module
(7 answers)
Closed 5 years ago.
I'm trying to get a fast way to determine if a number is prime using Python.
I have two functions to do this. Both return either True or False.
Function isPrime1 is very fast to return False is a number is not a prime. For example with a big number. But it is slow in testing True for big prime numbers.
Function isPrime2 is faster in returning True for prime numbers. But if a number is big and it is not prime, it takes too long to return a value. First function works better with that.
How can I come up with a solution that could quickly return False for a big number that is not prime and would work fast with a big number that is prime?
def isPrime1(number): #Works well with big numbers that are not prime
state = True
if number <= 0:
state = False
return state
else:
for i in range(2,number):
if number % i == 0:
state = False
break
return state
def isPrime2(number): #Works well with big numbers that are prime
d = 2
while d*d <= number:
while (number % d) == 0:
number //= d
d += 1
if number > 1:
return True
else:
return False`
Exhaustive division until the square root is about the simplest you can think of. Its worst case is for primes, as all divisions must be performed. Anyway, until a billion, there is virtually no measurable time (about 1.2 ms for 1000000007).
def FirstPrimeFactor(n):
if n & 1 == 0:
return 2
d= 3
while d * d <= n:
if n % d == 0:
return d
d= d + 2
return n
Note that this version returns the smallest divisor rather than a boolean.
Some micro-optimizations are possible (such as using a table of increments), but I don' think they can yield large gains.
There are much more sophisticated and faster methods available, but I am not sure they are worth the fuss for such small n.
Primality tests is a very tricky topic.
Before attempting to speed up your code, try to make sure it works as intended.
I suggest you start out with very simple algorithms, then build from there.
Of interest, isPrime2 is flawed. It returns True for 6, 10, 12, ...
lines 3 to 6 are very telling
while d*d <= number:
while (number % d) == 0:
number //= d
d += 1
When a factor of number d is found, number is updated to number = number // d and at the end of the while loop, if number > 1 you return True
Working through the code with number = 6:
isPrime2(6)
initialise> number := 6
initialise> d := 2
line3> check (2 * 2 < 6) :True
line4> check (6 % 2 == 0) :True
line5> update (number := 6//2) -> number = 3
line6> update (d : d + 1) -> d = 3
jump to line3
line3> check (3 * 3 < 3) :False -> GOTO line7
line7> check(number > 1) -> check(3 > 1) :True
line8> return True -> 6 is prime
Here is what I came up with
def is_prime(number):
# if number is equal to or less than 1, return False
if number <= 1:
return False
for x in range(2, number):
# if number is divisble by x, return False
if not number % x:
return False
return True
I'm trying to solve this problem in hackerrank. At some point I have to check if a number divides n(given input) or not.
This code works perfectly well except one test case(not an issue):
if __name__ == '__main__':
tc = int(input().strip())
for i_tc in range(tc):
n = int(input().strip())
while n % 2 == 0 and n is not 0:
n >>= 1
last = 0
for i in range(3, int(n ** 0.5), 2):
while n % i == 0 and n > 0:
last = n
n = n // i # Concentrate here
print(n if n > 2 else last)
Now you can see that I'm dividing the number only when i is a factor of n.For example if the numbers be i = 2 and n = 4 then n / 2 and n // 2 doesn't make any difference right.
But when I use the below code all test cases are getting failed:
if __name__ == '__main__':
tc = int(input().strip())
for i_tc in range(tc):
n = int(input().strip())
while n % 2 == 0 and n is not 0:
n >>= 1
last = 0
for i in range(3, int(n ** 0.5), 2):
while n % i == 0 and n > 0:
last = n
n = n / i # Notice this is not //
print(n if n > 2 else last)
This is not the first time.Even for this problem I faced the same thing.For this problem I have to only divide by 2 so I used right shift operator to get rid of this.But here I can't do any thing since right shift can't help me.
Why is this happening ? If the numbers are small I can't see any difference but as the number becomes larger it is somehow behaving differently.
It is not even intuitive to use // when / fails. What is the reason for this ?
The main reason of the difference between n // i and n / i given that n and i are of type int and n % i == 0 is that
the type of n // i is still int whereas the type of n / i is float and
integers in Python have unlimited precision whereas the precision of floats is limited.
Therefore, if the value of n // i is outside the range that is accurately representable by the python float type, then it will be not equal to the computed value of n / i.
Illustration:
>>> (10**16-2)/2 == (10**16-2)//2
True
>>> (10**17-2)/2 == (10**17-2)//2
False
>>> int((10**17-2)//2)
49999999999999999
>>> int((10**17-2)/2)
50000000000000000
>>>
I was trying to come up with a simple on-liner to detect if an integer was even and if not add 1 to make it even. So I came up with this:
N = 62465
N += 1 if bool(N % 2) else N
print N
This works fine if N is odd but if it is even it returns double the value. What is happening here?
You are doubling your N when it is even; you essentially do this:
if N % 2:
N += 1
else:
N += N
You'd want to use N += 1 if N % 2 else 0 instead (the bool() is implied in conditionals).
To simplify that you can just add N % 2 as that'll be 0 for even and 1 for odd:
N += N % 2
The often-used way of doing this is by dividing then multiplying.
N = (N + 2 - 1)//2*2
This works with other moduluses that are not 2.