Is there a way to make it so my function prints pi with only two decimal places if the user chooses to input no argument? The below function takes one argument (namely 'n') which in turn returns an error if the user chooses to leave the field blank:
def pi(n):
pi_input = round(math.pi, n)
# None is unfruitful here, I just wanna emphasize my desired objective
if n <= 1 or n == None:
return pi(2)
elif n > 15:
print("Too many decimal places.")
return math.pi
else:
return pi_input
The desired outcome should be as follows:
>>> pi()
3.14
I was wondering if there was a way to somehow short-circuit the function so the function does not necessarily require an input. If not, I wouldn't mind a more intelligent rewriting of the code. I greatly appreciate all help in advance!
Simply add a default argument to your function so that the n variable is set to 2 if nothing is provided.
def pi(n: int = 2):
pi_input = round(math.pi, n)
if n > 15:
print("Too many decimal places.")
return math.pi
else:
return pi_input
Or simply:
def pi(n: int = 2):
return round(math.pi, n)
Which would produce:
>> result = pi()
>> print(result)
3.14
The problem is formulated as follows:
Write a recursive function that, given a string, checks if the string
is formed by two halves equal to each other (i.e. s = s1 + s2, with s1
= s2), imposing the constraint that the equality operator == can only be applied to strings of length ≤1. If the length of the string is
odd, return an error.
I wrote this code in Python 2.7 that is correct (it gives me the right answer every time) but does not enter that recursive loop at all. So can I omit that call here?
def recursiveHalfString(s):
##param s: string
##return bool
if (len(s))%2==0: #verify if the rest of the division by 2 = 0 (even number)
if len(s)<=1: # case in which I can use the == operator
if s[0]==s[1]:
return True
else:
return False
if len(s)>1:
if s[0:len(s)/2] != s[len(s)/2:len(s)]: # here I used != instead of ==
if s!=0:
return False
else:
return recursiveHalfString(s[0:(len(s)/2)-1]+s[(len(s)/2)+1:len(s)]) # broken call
return True
else:
return "Error: odd string"
The expected results are True if the string is like "abbaabba"
or False when it's like anything else not similat to the pattern ("wordword")
This is a much simplified recursive version that actually uses the single char comparison to reduce the problem size:
def rhs(s):
half, rest = divmod(len(s), 2)
if rest: # odd length
raise ValueError # return 'error'
if half == 0: # simplest base case: empty string
return True
return s[0] == s[half] and rhs(s[1:half] + s[half+1:])
It has to be said though that, algorithmically, this problem does not lend itself well to a recursive approach, given the constraints.
Here is another recursive solution. A good rule of thumb when taking a recursive approach is to first think about your base case.
def recursiveHalfString(s):
# base case, if string is empty
if s == '':
return True
if (len(s))%2==0:
if s[0] != s[(len(s)/2)]:
return False
else:
left = s[1:len(s)/2] # the left half of the string without first char
right = s[(len(s)/2)+1: len(s)] # the right half without first char
return recursiveHalfString(left + right)
else:
return "Error: odd string"
print(recursiveHalfString('abbaabba')) # True
print(recursiveHalfString('fail')) # False
print(recursiveHalfString('oddstring')) # Error: odd string
This function will split the string into two halves, compare the first characters and recursively call itself with the two halves concatenated together without the leading characters.
However like stated in another answer, recursion is not necessarily an efficient solution in this case. This approach creates a lot of new strings and is in no way an optimal way to do this. It is for demonstration purposes only.
Another recursive solution that doesn't involve creating a bunch of new strings might look like:
def recursiveHalfString(s, offset=0):
half, odd = divmod(len(s), 2)
assert(not odd)
if not s or offset > half:
return True
if s[offset] != s[half + offset]:
return False
return recursiveHalfString(s, offset + 1)
However, as #schwobaseggl suggested, a recursive approach here is a bit clunkier than a simple iterative approach:
def recursiveHalfString(s, offset=0):
half, odd = divmod(len(s), 2)
assert(not odd)
for offset in range(half):
if s[offset] != s[half + offset]:
return False
return True
The webpage to test the code is here:
https://leetcode.com/problems/sqrtx/description/
I handed in these code and passed:
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x==1:
return 1
lowest=0.0
uppest=x*1.0
count=1
middle=(lowest+uppest)*0.5
while (abs(middle*middle-x)>0.001) and (count<=10000):
if middle*middle>x:
uppest=middle
else:
lowest=middle
middle=(lowest+uppest)*0.5
count=count+1
return int(middle)
but when I change
while (abs(middle*middle-x)>0.001) and (count<=10000):
into
while (abs(middle*middle-x)>0.0001) and (count<=10000):
or add more '0' like 0.00000000001 and use '9' as an input to test, it gets wrong
The output should be 3, but I got 2
How can I solve this kind of problem while using the Bisection Method?
I don't want to use the library (I know that using library is the easiest way but I want to learn more)
It is more like a math problem rather than python, just insert
print(middle,middle**2>x)
for debugging purposes.
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x==1:
return 1
lowest=0.0
uppest=x*1.0
count=1
middle=(lowest+uppest)*0.5
while (abs(middle*middle-x)>0.0001) and (count<=10000):
if middle*middle>x:
uppest=middle
else:
lowest=middle
middle=(lowest+uppest)*0.5
count=count+1
print(middle,middle**2>x)
return int(middle)
sol=Solution()
print(sol.mySqrt(9))
The output
2.25 False
3.375 True
2.8125 False
3.09375 True
2.953125 False
3.0234375 True
2.98828125 False
3.005859375 True
2.9970703125 False
3.00146484375 True
2.999267578125 False
3.0003662109375 True
2.99981689453125 False
3.000091552734375 True
2.9999542236328125 False
3.0000228881835938 True
2.999988555908203 False
2
You can see the reason already.
Also I wonder why cannot you just use
round(middle)
The culprit is
return int(middle)
The reason you obtain 2 is because your are casting a number such as 2.99998855591 into int, which is the equivalent of floor(x)
After a number of iteration n0, the error sqrt(x) - middle between the target value and the value of middle follow a damped oscillation.
Just round to the closest integer instead
return round(middle)
See other answers for what is happening. The solution is:
return int(middle + 0.5)
which is rounding towards the nearest integer.
A bigger problem is of course that you're converting intermediate values to float when calculating an integer square root. Floats have a very limited range compared to Python ints. Try something like this instead:
def int_sqrt(n):
"""Return integer square root of integer ``n``.
"""
x = n
y = (x + 1) >> 1
while y < x:
x = y
y = (x + n // x) >> 1
return x
and e.g. run it on int_sqrt(2**12345-1) which should return a 1858 digit number.
I have tried several different variations of this code and it keeps telling me is something is wrong with the syntax and I might just need some fresh eyes to see it.
def hasRealSolution(a,b,c):
if b**2 - (4*a*c) <0:
return False
else:
return True
First, fix your indentation.
Second, the comparison already returns a boolean value; you do not need the if:
def has_real_solution(a, b, c):
return b*b - 4*a*c >= 0
I'm currently using singpath.com to practice on my python, but I face an issue with a problem:
A number, a, is a power of b if it is divisible by b and a/b is a power of b.
Write a function called is_power that takes parameters a and b and returns True if a is a power of b.
def is_power(a,b):
c = a/b
if (((a%b) == 0) and ((c%b) == 0)):
return True
else:
return False
Above is my solution but the system prompt me to generalize my solution.
Can anyone tell me whats wrong with my solution?
The reason why your original code does not work is the following: You just check (c%b) == 0) aka (a/b) is divisible by b, which is much weaker than the a/b is a power of b part of the definition.
When you want to solve a problem such as this you should always start with the trivial cases. In this case there are two such cases: is_power(x,x) and is_power(1,x) - in both the answer is True, because x**1==x and x**0==1.
Once you have these cases covered you just need to write down the rest of the definition. Write code for (a is divisible by b) and (a/b is a power of b) and put it all together.
The final function will look like this:
def is_power(a,b):
if <trivial case 1> or <trivial case 2>:
return True
# its a recursive definition so you have to use `is_power` here
return <a is divisible by b> and <a/b is a power of b>
The only question left is how to answer <a/b is a power of b>. The easiest way to do this is using the function is_power itself - this is called recursion.
def is_power(a,b):
'''this program checks if number1 is a power of number2'''
if (a<b): # lesser number isn't a power of a greater number
return False
elif (b==0) or (b==1) : # Exception cases
return False
elif a%b == 0 and is_power(a/b, b) == True: # Condition check for is_power (Recursion!)
return True
else:
return False
You are only checking the first two powers: a divides b and a/b divides b. It could be that a = b ** 3 or b ** 4 (or b ** n in general), so the actual solution will have to involve recursion or a loop.
Here is my solution.
def is_power(a,b):
if a == 1: # base case for recursion
return True
elif b == 0 or a%b !=0 or a<b: # exception cases.
return False
return is_power(a//b,b) # recursion
I tested with several cases (16,2),(6,2),(1,2),(0,0),(0,1) and it works well.
A much simpler solution is:
def is_power(a, b):
while a % b == 0:
a //= b
return a == 1
Recursion is really not needed for this problem. Moreover recusion may cause a recursion limit error if a = b ** 1001.
def is_power(a,b):
if a == b:
return True
if a % b == 0 and is_power(a/b,b):
return True
return False
The end condition which is a == b is crucial here which stops when both numbers are equal. If this is not included the function could show False for even legitimate numbers by dividing a/b in the next iteration which gives 1 where 1 % b = 1 which in turn returns False instead of True.
I wouldn't say to generalize it. I would say to correct it as it's incorrect. Using your solution is_power(12,2) returns True as does is_power(18,3).
I think that the reason that the system says to generalize it is that it's probably working correctly for some of their test cases, but not others. It's likely that the test cases for which it is working are coincidentally those for which it would work if it were hard-coded in a certain way (only checking powers of 2, for example).
You're checking whether a/b is divisible by b (in the expression (c%b) == 0), rather than whether a/b is a power of b. Hint: What function would you call to see whether something is a power of b?
To understand recursion, you need first to understand recursion.
def is_power(a, b):
if a < b: # 3 is never a power of 10, right?
return False # prevent recursion
if a == b: # a is always a**1, right?
return True # prevent recursion
else:
return is_power(a / b, b) # recursion!
Note that for integers a / b will give you rounding errors. Make sure you pass floats.
I don't think you have the right implementation. Based on the problem, the is_power function should look something like this:
def is_power(a,b):
if a%b == 0 and is_power(float(a)/float(b), b):
return True
else:
return False
You are answering to the first constraint but not to the second,
You check to see that (a/b)%b == 0 which is a special case of "(a/b) is a power of b".
Therefor the generalization error (try to think of generalizing that specific case.
What you wrote is not a solution to is power of for example you will indicate 12 as a power of 2 since:
12%2 = 0,
(12/2)%2 = 0
But that is clearly wrong.
As others said, think of recursion (or the less preferable looping solution).
I was just working on this question myself, and this is what I came up with.
To write this as a recursive function, you need the recursive part and the trivial part. For the recursive part, a number is the power of another number if:
((a%b)==0) and (is_power(a/b, b) # a is evenly divisible by b and a/b is also a power of b.
For the trivial case, b is a power of a if a=b.
However, we're not done. Because we are dividing by b, we have to make an exception for when b is zero.
And the other exception is when b = 1. Since when b=1, a/b is a, we will end up with infinite recursion.
So, putting it all together:
def is_power(a,b):
# trivial case
if (a==b): return True
# Exception Handling
if (b==0) or (b==1): return False # unless a==b==0 or a==b==1, which are handled by the trivial case above
# recursive case
return ((a%b)==0) and (is_power(a/b,b))
This example should fix your problem :
def is_power(a,b):
if a == 1:
return True
elif a%b == 0 and is_power(a/b, b) == True:
return True
else:
return False
You can use log.
import math
def is_power(a, b):
return math.log(a, b) % 1 == 0
I hope that this works, this one worked fine for me.
import math # I will use the math module for the next function
def is_power (a, b):
if b == 1 and a!= 1:
return False
if b == 1 and a == 1:
return True
if b == 0 and a!= 1:
return False
power = int (math.log(a, b) + 0.5)
return b ** power == a
Your solution is correct however you just need to remove ALL of the parenthesis in your if statement.
def ab(a, b):
c = b/a
if a%b == 0 and c%b == 0:
return True
else:
return False
print (ab(32, 2))