wrong answer for large input - python

I am trying to determine whether an integer can be expressed in the form of a^b where b>1 and the given integer is greater than 0. My code runs fine for all test cases except for one.
It gives wrong answer for the following input:
536870912
I cant understand why.
def isPower(self, A):
if(A==1):
return (1)
for i in range(2,int(A**0.5)+1):
val=log(A,i)
if(int(val)-val==0):
return (1)
else:
return (0)

This will solve:
from math import log
def isPower(A):
if(A==1):
return (1)
if (A&-A)==(A):
return (1)
for i in range(2,int(A**0.5)+1):
val=log(A,i)
if(int(val)-val==0):
return (1)
else:
return (0)
If you are looking for reason on why it is not working please refer the below link:
Dealing with accuracy in Python math operations

Related

Python Recursion Issue; I Can’t Change My Hard Code Into a Recursive Function

beside(picture,picture) #beside takes two pictures as arguments and prints them side by side in a 1:1 ratio.
stackn(n,picture) #stackn takes a number and a picture as arguments and prints n number of shapes in a vertical row.
show(picture) #show takes a picture as an argument and shows it on the canvas
In this case picture is the parameter heart_bb:
(n=2)# show(beside((stackn(1,heart_bb)),(stackn(2,heart_bb))))
(n=3)# show(beside((stackn(1,heart_bb)),(beside((stackn(2,heart_bb)),(stackn(4,heart_bb))))))
(n=4)# show(beside((stackn(1,heart_bb)),(beside((stackn(2,heart_bb)),(beside((stackn(4,heart_bb)),(stackn(8,heart_bb))))))))
My task is to come up with a recursive function(I’m going to call it test):
def test(n, picture):
I need this function to return the corresponding line of code shown above. For example, test(3,heart_bb) should return the line of code for n=3. Likewise, test(4,heart_bb) will return the line of code for n=4.
It has to work for any n>1, but after n=5 coding it gets really tedious.
def fractal(picture,n):
if n==1:
return(picture)
else:
return(beside((fractal(picture,(n-1))),(stackn((2**(n-1)), (picture)))))
I suppose you mainly need an idea of how you can do it and not a way to find someone that writes the code for you.
I would suggest to use a n-ary beside operation in place of your one, in such a way to simplify the code for n=2,3,4,... Since I cannot modify it I will define a new one in terms of your binary operation in this way:
def beside_pictures(pictures):
assert len(pictures) > 0
result = pictures[-1]
for tmp in pictures[:-1:-1]: # reverse order, starting from -1
result = beside(tmp, result)
return result
Now we are ready to transform your test function in a one line function:
def test(n, picture):
assert n > 0
show(beside_pictures([stackn(2**i,picture) for i in range(n)]))
UPDATE: If the requirement to have a recursive function is strict, one possible solution is the following one:
def test(n, picture):
if n == 1:
return stackn(1,picture)
return beside(test(n-1, picture), stackn(2**(n-1),picture))

Trying to calculate factorial but I am having a type error [python]

I am trying to write a program asking users to input a positive integer and calculate factorial.
This is what I did
def main():
getN()
fact()
print (n,"! is ",num)
def fact():
num=1
while n>=1:
num=num*n
n=n-1
return num
def getN():
n=input("Enter a positive integer: ")
if not n%1==0:
print("Enter a positive integer: ")
return n
main()
But when I run this code, I got the error saying type error: not all arguments converted during string formatting.
I have to get a postivie integer and want to use getN function to guarantee that it is a positive.
Please help me.
Thank you in advance.
When you get an error message, it's always a good idea to post the whole error message including the stack trace. Your question should be self explaining without code if possible. So provide the error message but also analyze the error message yourself.
Traceback (most recent call last):
File "/home/labbi/git/sandkasten/sandkasten.py", line 21, in <module>
main()
File "/home/labbi/git/sandkasten/sandkasten.py", line 2, in main
n1 = getN()
File "/home/labbi/git/sandkasten/sandkasten.py", line 17, in getN
if not n%1==0:
TypeError: not all arguments converted during string formatting
The error message says the TypeError occurred on line 17 which is the operation in your if statement. The only string can be contained in the variable n.
Your problem is that input() on line 16 returns a string so you can't use it for numeric operations. You can convert strings with int() as bellow.
When you have fixed it you will also notice a few mistakes in your main function. You're calling fact() and getN(). Both return values but you don't store them even though you're trying to use the returned values.
def main():
n_result = getN()
num_result = fact(n_result)
print (n_result,"! is ",num_result)
def fact(n):
num=1
while n>=1:
num=num*n
n=n-1
return num
def getN():
n = int(input("Enter a positive integer: "))
if not n%1==0:
print("Enter a positive integer: ")
return n
main()
Furthermore for readability reasons I would also like to point you to the python style guide, especially to the chapter about whitespace.
Bit of a tricky error message, but if not n%1 == 0: is an attempt to perform mod division, however n is still a string. You need to cast the input to int with
n=int(input("Enter a positive integer: "))
Your code still won't work however, because you are referencing variables everywhere before their assignment, and in functions for which they are not defined. I would consider re-arranging the order of your functions, and ensuring that all relevant parameters necessary for each function are passed - currently you don't use function parameters at all.
As an aside, you got that error message because % is also used in string formatting operations to mark the start of a conversion specifier. See the docs.
Use this code
def factorial():
i = int(input())
mul = list(range(1, int(i)))
for eve in mul:
i = i * eve
return i
print(factorial())

Python input datatype handling

I spent a good hour or more looking for the answer on here. I have found a few things that help, but do not answer my question specifically. I am using Python 3.3.3. I am a novice so please be gentle.
I am trying to create a program that takes a user input, but then I need to do a check to see what datatype that input is, and then based on that datatype take a certain course of action.
Any string besides those found in this list:
valid_help_string_list = ['\'help\'', '\'HELP\'', 'help', 'HELP']
should result in the printing of:
'please enter a valid entry' or something to that effect.
Any integer (over 0 but under 500) should have float() used on it to make the rows line up.
Any float (over 0.0 but under 500.0) is valid.
For the sake of this project I am assuming nobody using this will weigh under 100 lbs or over 500.
Anything not falling within those categories should also yield the same "please enter a valid response" error message to the user.
I think it's simple enough of a project to take on for a novice. The program is meant to allow you to input your weight and then creates a pictogram based on that weight and saves it all on the next open line of the .txt file I have set up for it. Or if you want to see the legend for the pictogram, you should be able to type help in any variation found in that list.
Any help would be much appreciated.
The user input will be a string by default, so we need to check whether it could become an integer or float. As you want to turn the integers in floats anyway, there's no need to do anything complex:
def validate_input(val, min_v=100, max_v=500):
try:
val = float(val)
except ValueError:
print("Not a valid entry")
else:
if not min_v < val <= max_v:
print("Value should be between {} and {}".format(min_v, max_v))
else:
return val
return False
Now your calling loop can read:
while True:
val = input("...")
if val in valid_help_string_list:
# print help
else:
val = validate_input(val)
if val:
break
# use val
Note that this relies on the return from validate_input being either False or a number larger than 0; Python will interpret a zero return as False and not reach the break, so I recommend keeping min_v >= 0.

Square root function in Python - what's wrong with it?

I literally just started learning Python this week. (I will be a computer science fresher in a month!)
Here's a function I wrote to compute the square root of x.
#square root function
def sqrt(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x>=0:
while ans*ans <x:
ans = ans + 1
if ans*ans == x:
print(x, 'is a perfect square.')
return ans
else:
print(x, 'is not a perfect square.')
return None
else: print(x, 'is a negative number.')
But when I save it and type sqrt(16) into the Python shell, I get an error message.
NameError: name 'sqrt' is not defined
I'm using Python 3.1.1.
Is there something wrong with my code?
Any help would be appreciated.
Thanks
UPDATE
Okay, thanks to you guys I realized I hadn't imported the function.
And when I tried to import it, I got an error because I saved it in a generic My Documents file instead of C:\Python31. So after saving the script as C:\Python31\squareroot.py, I typed into the shell (having restarted it):
import squareroot
And got a NEW error!
>>> import squareroot
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import squareroot
File "C:\Python31\squareroot.py", line 13
return ans
SyntaxError: 'return' outside function
Meaning there WAS a bug in my original code! I'm going to look at some of the suggested corrections below right now. If you've spotted anything else, say. Thanks :)
UPDATE 2 - IT WORKED!!!!!!!!!!
Here's what I did.
First, I used a cleaned up version of code kindly posted by IamChuckB. I made a new script with this in it (changed the function name from sqrt to sqrta to differentiate):
def sqrta(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x>=0:
while ans*ans <x:
ans = ans + 1
if ans*ans == x:
print(x, 'is a perfect square.')
return ans
else:
print(x, 'is not a perfect square.')
return None
else:
print(x, 'is a negative number.')
And, importantly, saved it as C:\Python31\squareroota.py (Again, added an "a" at the end to differentiate between this the other, failed, file.)
Then I reopened Python shell and did this:
>>> import squareroota
Nothing happened, no error, great! Then I did this:
>>> squareroota.sqrta(16)
And got this!
16 is a perfect square.
4
Wow. I know this might seem like playing with ABC blocks in school but it honestly blew my mind. Thank you very much everyone!
Yes I believe you have to actually import your function into the shell.
from yourfile import sqrt
Be careful. I think if you're in the shell and you make changes, you have to reimport your function for those changes to show up. As delnan mentions below you can reload
your file after changeing it..
Firstly, your loop will always end on its first iteration since you essentially have if (...) return else return. Try this instead:
def sqrt(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x >= 0:
while ans * ans <= x:
if ans * ans == x:
print(x, 'is a perfect square.')
return ans
ans = ans + 1
print(x, 'is not a perfect square.')
return None
else: print(x, 'is a negative number.')
But note that Python offers a built-in power operator:
def sqrt(x):
return x ** 0.5
To answer your question specifically, you will have to import your function. If the file in which this is written is sqrt.py, to use this function in another file you would need from sqrt import sqrt.
The NameError means that your python shell does not recognize the function. You probably forgot to import the script.
Assuming that you saved your file as myscript.py (in the same directory as where you start your python shell), you have to use:
import myscript
for the functions defined inside to be available. Note that you'll have to call myscript.sqrt in order to run your function sqrt: it is only available in the myscript namespace.
An alternative is to type from myscript import sqrt: in that case, you make your myscript.sqrt available in the namespace as sqrt. Be careful that you don't overwrite a builtin function with this from ... import ......
Here's your original code, just cleaned up so it will run. The problem with it as originally formatted was with indentation.
The while block should be indented one level (4 spaces) deep to denote it is in the def block for the function sqrt.
Having the if/else blocks inside of the while statements means that check is done each pass through the loop; therefore, the first time through when ans is only equal to one, that test will be done, your output with be printed and a value returned. We need to change this. Several of the other answers give more straight-forward ways to phrase this in python but, in keeping as close to the code you've written as possible, all you actually have to do is move the if block and the else block out of the while block. Code is shown below:
def sqrt(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x>=0:
while ans*ans <x:
ans = ans + 1
if ans*ans == x:
print(x, 'is a perfect square.')
return ans
else:
print(x, 'is not a perfect square.')
return None
else:
print(x, 'is a negative number.')
Sample input and output are shown:
In:
sqrt(9)
Out:
9 is a perfect square.
In:
sqrt(8)
Out:
8 is not a perfect square.
EDIT: In my opinion, Python is a great first language. When I was first starting off with it, I found the MIT OpenCourseWare class very useful. One very important note: the class is taught using Python 2.x instead of 3.x so some of the given code won't work right for you. Even if you don't watch all the video lectures, the assignments they give are of a reasonable difficulty and the reading assignments reference some excellent python learning materials.
The Udacity CS101 class also offers a good, directed introduction to programming in Python (and also uses Python 2.x) but I only worked through about half of the assignments there. I'd still recommend taking a look at it, however.

python, how to write an iterative function

I am quering a database for some paramaters which depend on a attribute called count! count can be incremented incase the 1st query does not return anything. Here is a sample code
sls = {(213.243, 55.556): {}, (217.193, 55.793): {}, (213.403, 55.369): {}}
for key in sls.keys:
if not sls[key]:
ra, dec = key[0], key[1]
search_from_sourcelist(sl, ra,dec)
count = 1
def search_from_sourcelist(sl, ra,dec):
dist = count/3600.0
sls[(ra,dec)] = sl.sources.area_search(Area=(ra,dec,dist))
return
Incase i run the method search_from_sourcelist, and it doesnt return anything, i would like to increment count, and do the query again. This is to be done for all keys in sls dictionary, untill all the keys have a value!!
Here is the most fundamental recursive function
def countdown(n):
if n == 0:
return "Blastoff"
else:
print "T minus %s" % n
return countdown(n-1)
You will notice that countdown returns itself with a modified argument, in this case n but -1, so if you actually followed this all the way through you would get
(-> indicates a call)
countdown(5) -> countdown(4) -> countdown(3) -> countdown(2) -> countdown(1) -> countdown(0) #stop
So now you understand what a recursive function looks like you realize you never actually return a call of your own function, thus your code is not recursive
We use recursion because we want to boil a task down to its simplest form then work from there, so a good example of this would be the mcnuggets problem. So you need to tell us what you are trying to achieve and how it can be made a smaller problem (or more importantly why.) Are you sure you cannot do this iteratively? remember you don't want to blow your stack depth because python is NOT tail recursive by standard
Recursion is useful when you find a way to reduce the initial problem to a "smaller version of itself".
The standard example is the factorial function
def fac(n):
return n * fac(n-1) if n > 1 else 1
Here you reduce the problem of calculating the factorial of n to calculating the factorial of n-1.
In your code there is no such "reduction". You just increment a value and start the same problem over again. Thus, I recommend you solve it iteratively.
I'm not sure that you need a recursive algorithm for this.
Incase i run the method search_from_sourcelist, and it doesnt return anything, i would like to increment count, and do the query again. This can be done with a while loop as follows:
for key, value in sls.iteritems():
if not value:
ra, dec = key[0], key[1]
count = 1
while not search_from_sourcelist(sls, ra, dec):
count += 1
But if you really do want to do this recursively, you can do it as follows, leave a comment and I'll write it up.
Further, you should look into your search_from_sourcelist function, as it always returns None

Categories