I have to write a function to find if a given number (num) within 2 of a multiple of 10. I use modulus (%) to get the remainder, but it doesn't seem to be working quite right. Help?
def nearten(num):
if num%10<=2:
return True
elif num%10>2:
return False
Most of all, you only checked to see whether the "ones" digit is 0, 1, or 2 -- you missed 8 and 9.
As a styling note, don't check a boolean expression and then hard-code the result you just found. Your function, as currently written, reduces to this:
def nearten(num):
return num%10 <= 2
Do you see how that works? First of all, the elif check doesn't give you any new information: you already know that the result must be >2 when you get past the if condition.
Then, your statement reads like
if this condition is true, return true
otherwise, we know it's false; return false.
That's redundant. You have a True/False value sitting right in your program's hand -- just return that one, instead of using a constant.
REPAIR ...
I'll leave this as an exercise for the student: "within" 2 means that you have to check both sides, so you have to pick up the cases where the ones digit is 8 or 9. Can you write the expression to do that?
You can use Ternary operator and check for if num is within 2 of multiple of 10:
def near_ten(num):
return True if num%10<3 or num%10>7 else False
You can write this code as:
def near_ten(num):
a = num % 10
return 2 >= a or 8 <= a
Here is a little help:
def near_ten(num):
return num % 10 in [0,1,2,8,9,10]`
can also be:
return 0 <= (num % 10) <= 2 or 8 <= (num % 10) <= 10
This works:
def near_ten(num):
return num%10 <= 2 or num%10 >= (10 - 2 )
This method also works, just returning a bool value by using comparison operators in a single line to check both 'sides' of the cases:
def near_ten(num):
return (num % 10 <= 2 or num % 10 >= 8)
def near_ten(num):
if num%10<=2 :
return True
elif num%10 >=8:
return True
else:
return False
Related
For context, I am trying to solve Project Euler problem 3 using Python:
What is the largest prime factor of the number 600851475143?
As a first step to this, I am trying to write a function that returns whether or not a number is prime as a Boolean. I made a first attempt, and checked out how this has been written previously. I have ended up with the following code:
def isprime(x):
limit = x**0.5
i = 2
if x < 2:
return False
elif x == 2:
return True
else:
while i <= limit:
if x%i == 0:
return False
i = i + 1
else:
return True
For some reason, the code above does not work perfectly. For example, isprime(99) would return True.
Please, can someone help me understand why this isn't working? I am trying to avoid just copying and pasting someone else's code, as I want to understand exactly what is going on here.
To me, it looks like the issue is with the final else statement. I say this because the logic reads "in the event that x%i == 0, this number is not prime" but it doesn't explicitly say what to do in the event that no x%i iterations == 0.
Any help on this would be appreciated! I'm not necessarily looking for the cleanest, neatest way of doing this, but more just trying to first make this code work.
Just to show an alternative, what you could do is checking from number 2 to your number if the operation (x % i) is equal to zero. If it never happend, it will be a prime.
def isprime(x):
# check for factors
for i in range(2,x):
if (x % i) == 0:
return False
else:
return True
print(isprime(99))
Try this :
def isprime(x):
limit = x**0.5
i = 2
if x <= 2:
return False
while i <= limit:
if x%i == 0:
return False
i = i + 1
return True
I've changed many things. have this point in your mind that there is no need to else clauses when you return at the end of if block.
you need to tell what happens when x%i==0 condition not met and the value of i remain constant and also need to see when all conditions not met, then it is a prime
# your code goes here
def isprime(x):
limit = x**0.5
i = 2
if x < 2:
return False
elif x == 2:
return True
else:
while i <= limit:
if x%i == 0:
return False
i+=1
return True
print(isprime(144)) # false
print(isprime(99)) # false
print(isprime(131)) # true
def is_prime(x):
for i in range(2,x):
if (x % i) == 0:
return False
else:
return True
print(is_prime(9))
this is my function to find the prime number, i am not sure why its always return True for 9, any helps and explanation? Thanks
To understand why this is happening, take a look at what happens when 9 is passed into is_prime:
We enter the for loop, and set the initial value of i to be 2. Then, 9 % 2 = 1, not 0, so the if condition fails, and we go to the else condition, which then immediately returns True: But this isn't the definition of primality. We need that 9 is not divisible by any number smaller than it (apart from 1), not that it's not divisible by a single number. So, we can only return True once we've checked all the numbers in the range, like this:
def is_prime(x):
for i in range(2,x):
if (x % i) == 0:
return False
return True
Your code should now return the correct result for 9 (and, given infinite time, any natural number greater than 1).
A couple of things to think about: Do you need to check every number in range(2, x)? Perhaps you could look at what happens past the square root of x? Also, you might want to check if the number is less than 2 (i.e: 1, 0, -1, ...), because currently, your code will not give the correct result for these numbers. If you're interested also, the Sieve of Eratosthenes is a better algorithm than trial division for finding primes, which you might want to take a look at further down the line.
Because 9%2 is 1, and that is True
Here is how I fixed your code
def is_prime(x):
for i in range(2,x):
if (x % i) == 0:
return False
print(is_prime(9))
HOWEVER, this doesn't take into account of 0 and 1. So here is a more correct one
def is_prime(x):
if(x==0 or x==1):
return False
for i in range(2,x-1):
if (x % i) == 0:
return False
else:
return True
print(is_prime(9))
I am new to programming and I face an issue while trying to write a program in finding out prime number. Here is my code:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x-1):
if x % n == 0:
return False
else:
return True
I received an error stating "Your function fails on is_prime(3). It returns None when it should return True."
Can someone please explain the flaw in this code?
Thank you!
range() has an exclusive upper bound, so it's trying to get the range between 2 and 2 (3 - 1), which is no elements. Since you can't iterate over nothing, the for loop never runs, so None is returned (this is the default return type of a function if none is specified).
The solution to your immediate problem would be to use range(2, x) rather than range(2, x - 1). You'll find that you'll have problems at x > 3 though because as #khelwood said, you're returning True or False immediately after checking the first value. Instead, only return True after checking all values in the range.
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x): # range function will iterate till x-1
if x % n == 0:
return False
# return true only at the end after making sure it is not divisible by any number in the middle
return True
I'm trying to find whether a number is a power of 2 using recursion. However, I couldn't seem to figure out the correct solution. Here's what I've tried so far:
def is_power(n):
n = n/2
if n == 2:
return True
elif n > 2:
is_power(n)
else:
return False
if is_power(32):
print 'yes'
else:
print 'no'
Since '32' is a power of 2, I expected my code to return 'yes' as the output. However, the code outputs 'no' instead. What seems to be wrong with my code?
Since I already have an accepted answer here, I'll use this one to explain a bit why your approach is bad:
It uses recursion in python. Python needs to open up a stack frame for every call, so for very large numbers, this will be a bad way of solving this. It will even fail for very large integers.
I don't even think recursion in a non-purely-functional language like python is the intuitive thing to do here. There's a million easier ways to do this; for example, a while loop:
n = int(n)
while n>1:
if n/2 != n/2.0: #compare integer division to float division
return False
n = n/2
return True
Checking against power of two can be done in clever ways by realizing what the storage structure for integers on computers is: it's binary. So you could just count the binary 1s in your int's binary representation:
return bin(n).count('1') == 1
would also work. Of course, that would mean that python internally converts the integer to a string, which wastes memory on large numbers. So you might as well
power_of_2 = 1
while power_of_2 <= n:
if power_of_2 == n:
return True
power_of_2 *= 2
return False
simply compares your number to all smaller-or-equal powers of two. (which of course would probably take longer and use more memory, since your python interpreter will have to interpret python instead of just converting your integer to a string in C, but this is about algorithmic principles, right?) That way, you don't need to reserve memory just to count occurencies of 1 in your binary representation.
Of course, there's a one-liner that solves your issues, and I take it from the things I've learned writing in C/C++:
bool(n and not (n&(n-1)))
To explain n and not (n&(n-1)): n is True iff n != 0, which is would otherwise falsely qualify as power of 2.
For not (n&(n-1)): n&(n-1) checks whether something is not a power of 2, so we have to invert that. & is the bitwise "and" operator. To understand n & (n-1), imagine n is a power of 2, let's say 8. So n-1 == 7, and thus
8|0b1000
7|0b0111
--------
&|0b0000
as you can see, for all powers of two, n&(n-1) is 0, which evaluates to False. For all non-powers of two, you'll don't invert all the bits when subtracting 1, so n&(n-1) != 0, which evaluates to True.
elif n > 2:
is_power(n)
is missing the return:
def is_power(n):
n = n/2
if n == 2:
return True
elif n > 2:
return is_power(n)
else:
return False
thus, the "first" level of is_power returns nothing (or None, depending on how you check), which leads to output of no.
#kaveman correctly pointed out is_power(2) yields the wrong result.
You can fix that by halving 2 in the elif clause:
def is_power(n):
if not n == int(n):
return False
n = int(n)
if n == 1:
return True
elif n > 2:
return is_power(n/2.0)
else:
return False
EDIT: #will pointed out that I was mixing up python2 with python3 division. Using /2.0 fixes that. Also, in comments to the question he pointed out that 1 is a power of 2. Checking against ==1 instead of ==2 fixes that issue. Also, I added an int cast, which is not necessary for the power of 2 check (since well, IEEE754 floats are base 2 after all, so powers of 2 are exactly representable), but for non-2 bases, this will make the code portable.
The answer provided above is wrong.
Yes it will work for powers of two, but it will also give many false positives - as you are using integer division - because you are using python 2.7.
It would work if you were using from __future__ import division, which changes the behaviour of / - but this changes its behaviour throughout the program, which may not be what you want.
for example:
print 33/2 # 16
print 32/2 # 16
however, with from __future__ import division the outputs change to the correct (or at least more intuitive) results - to get the original integer math behaviour you need to use // instead (as in python3).
So the correct answer will be more like this:
def is_power(n):
n = n/2.0
if n == 2:
return True
elif n > 2:
return is_power(n)
else:
return False
Note the n= n/2.0 at the beginning.
You need to test your code works on several test cases, not just ones for which you want particular results.
Alternatively though, i would go with something like this:
def is_power(n):
if n == 2:
return True
elif n%2 != 0:
return False
else:
return is_power(n/2.0)
While this does not directly answer your question, the fastest way to implement this would be
def is_power(n):
return ((n & (n - 1)) == 0) and n != 0
While this has been covered in a previous post by Marcus, a 'bit' more explanation may help some. The binary representation of every number and the (number-1) share at least a single 1 bit, except if the number is a power of two. Further, all negative numbers share the leading bit, so are excluded by this method.
The only exception is the number 0, which doesn't share bits with the previous number -1, and may not be viewed as a power of 2. Therefore this needs an explicit check.
The binary table for the numbers will make this clear.
> Dcml Binary 5bit
> -15 10001
> -14 10010
> -13 10011
> -12 10100
> -11 10101
> -10 10110
> -9 10111
> -8 11000
> -7 11001
> -6 11010
> -5 11011
> -4 11100
> -3 11101
> -2 11110
> -1 11111
> 0 00000
> 1 00001
> 2 00010
> 3 00011
> 4 00100
> 5 00101
> 6 00110
> 7 00111
> 8 01000
> 9 01001
> 10 01010
> 11 01011
> 12 01100
> 13 01101
> 14 01110
> 15 01111
> 16 10000
No negative numbers in this signed number notation would satisfy the condition as they all share the most significant bit as 1. number 0 would satisfy the condition as 0&(any_other_number) == 0. If you need to implement this for very large numbers you may be better off using bitarrays or numpy with changed dtype. Also, this discussion may be helpful for speed of bitwise operations for on large arrays/numbers.
"""
Power check if a number is a power of 2
Negative numbers are not allowed
"""
import math
def is_power_of_two(num):
"""
:type num: integer
"""
try:
x=0
x = math.log10(num)/math.log10(2)
return 2 ** x == num
except ValueError:
exit()
You can just use the power of the math library
import math
def isPowerOfTwo(n):
if n <= 0:
return False
res = int(math.log(n) / math.log(2))
return 2 ** res == n
This was my solution for a function which checks which number is a base of another:
def is_power_of(number, base):
# when number is smaller than base.
if base <= 1:
return False
elif number < base:
return False
elif number > base:
# keep dividing number by base.
return is_power_of(number/base, base)
else:
return True
This will be bit informative,
counter = 0
def powoftwo(n):
global counter
counter+=1
if n%2 != 0:
return "Given Number %s is not Power of 2!"%g
else:
if n==2:
return "yes give number %s = 2**%s is power of 2!"%(g, counter)
return powoftwo(n/2)
g = 1024
print powoftwo(g)
yes give number 1024 = 2**10 is power of 2!
Late to the party, though yet, another way:
import math
def is_power_of_2(x):
n = math.log(abs(x), 2)
return n == int(n)
Disclosure: This question is from codewars.
Write a method that returns true if a given parameter is a power of 4, and false if it's not. If parameter is not an Integer (eg String, Array) method should return false as well.
I cannot for the life of me figure out what edge case I'm missing. Both code samples produce the same error that 'True should equal False' for some test. (I tried it two ways when the first didn't work, since I was positive the second would.)
def powerof4(n):
if n <= 0 or not isinstance(n, int): return False
else:
while (n != 1):
if (n%4 != 0): return False
else: n = n/4
return True
and
import math
def powerof4(n):
if ((not isinstance(n, int)) or n&(n-1) != 0 or n == 0):
return False
#Now, I cheat, since 4^n = (2^n)^2
reduce_to_2 = math.sqrt(n)
if math.floor(reduce_to_2) != reduce_to_2:
return False
else:
reduce_to_2 = int(reduce_to_2)
return reduce_to_2&(reduce_to_2 - 1) == 0
Your first problem is that you are checking if the type of the argument is int but starting with numbers larger than 2^32 thats not true for Python 2 which codewars is using.
The next error is if you print the value at codewars at which the test fails you see it's for the call powerof4(True). isinstance(True, (int,long)) is True because bool is a subclass of int.
In your first code change your typecheck to
if n <= 0 or type(n) not in (int,long): return False
To add another variation on the problem. When I solved this problem initially some time ago I did it with some bit fiddling :)
def powerof4(n):
if type(n) not in (int, long):
return False
bin_repr = bin(n)[2:]
return bin_repr[0]=="1" and bin_repr.count("0")%2==0 and bin_repr.count("1")==1
There's an easier way.
import math
def powerof4(n):
return math.log(n, 4) % 1 == 0
There is one less obvious gotcha. In Python 2 the number could be too big to fit in an int and it would be a long instead:
>>> isinstance(1000000000000000000000000000000, int)
False
whereas Python 3 would return
>>> isinstance(1000000000000000000000000000000, int)
True
The easiest algorithm on any CPython (*except for the isinstance check) could be
def powerof4(n):
if n <= 0 or not isinstance(n, (int, long)):
return False
return hex(n).rstrip('0') in ('0x1', '0x4')
This converts the number into hex, and removes trailing zeroes; a number is a power of 4 if and only if the hex representation is 1 or 4 followed by any number of zeroes. (hint: it would be a power of 16 if it were 1 followed by zeroes).
With bitwise logic:
test = 1
while n < test:
test <<= 2
return n == test
In Python 2.7 and 3.3+ this is even easier, no loop needed:
b = n.bit_length()
return bool(b & 1) and 1 << (b - 1) == n
Like this?
def isPowerOf4(n):
try:
while n:
if n==1:
return True
if ((n>>2)<<2) != n:
return False
n >>= 2
except:
return False
return False