Related
I wrote a python code to find root of 2*x-4 using bisection method
def func(x):
return 2*x-4
def bisection(a,b):
if (func(a) * func(b) >= 0):
print("You have not assumed right a and b\n")
return
c = a
while ((b-a) >= 0.01):
c = (a+b)/2
if (func(c) == 0.0):
break
if (func(c)*func(a) < 0):
b = c
else:
a = c
print("The value of root is : ","%.0f"%c)
a =-2
b = 4
bisection(a, b)
Now i want that the function input should be given by the user in the form of mx+n where m and n are integers. Can anyone help how can i do that ?
m, n = list(map(int, input("Please enter the value of [m] [n] for f(x) = mx +n: ").split()))
def Input():
a, b = list(map(int, input("Enter values of [a] [b]: ").split()))
if f(a)*f(b)<0:
Bisection(a, b)
else:
print("Oops! The root of function doesn't belong to the above domain\nPlease try to again:")
Input()
def f(x):
return m*x + n
def Bisection(a, b):
c = (a+b)/2
if f(c)*f(b)<0:
Bisection(c, b)
elif f(c)*f(a)<0:
Bisection(c, a)
elif f(c)==0:
print(c)
Input()
See we know that Bisection, Newton-Raphson, or most of all Numerical methods are the iteration processes so better we use function inside of function: f(f(f(f.....) Of course! by checking the conditions.
Here, I have used elif f(c)==0 this is something which we can't use for quadratic/cubic or higher-order polynomials because getting the exact root will not be possible for all the types of equations say like f(x) = mx^2 - n where m, n > 0 However, we can define the iterations to be performed.
By asking like Please enter the number of iterations to be performed:
Define a function that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
For example, given 6,7,8, the function that I defined should return 113
When I gave my code, it solves most of the problems but apparently there is some possibility that I haven't tried?? I think my code is flawed but not sure what other possibilities are there. Would really appreciate some help thank you so much!
def bigger_sum(a,b,c):
if(a+b>b+c):
return(a*a+b*b)
if(a+c>b+c):
return(a*a+c*c)
if(b+c>a+c):
return(b*b+c*c)
You can use min for this problem:
def big2_sqrsum(a,b,c):
x = min(a,b,c)
return (a*a + b*b + c*c) - (x*x)
print(big2_sqrsum(6,7,8))
Output:
113
Alternate solution with if-else
def big2_sqrsum2(a,b,c):
if a < b and a <c:
return b*b + c*c
elif b < a and b < c:
return a*a + c*c
elif c < a and c < b:
return a*a + b*b
Just check for the smallest number. That known, assign the values to two new variables that will hold the largest and second largest value and sum their squares.
Something like this :
big1 = 0
big2 = 0
if ([a is smallest]):
big1 = b
big2 = c
elif ([b is smallest]):
big1 = a
big2 = c
elif ([c is smallest]):
big1 = a
big2 = b
allows you to have only one place to calculate your formula :
return big1 * big1 + big2 * big2
Let's take a look at why your code is flawed. Given a comparison like if a + b > b + c:, the implication that both a and b are both greater than c is false. b can be the smallest number. All you know is that a > c, since you can subtract b from both sides of the inequality.
You need to find and discard the smallest number. The simplest way is to compute the minimum with min and subtract it off, as #Sociopath's answer suggests.
If you want to keep your if-elsestructure, you have to compare numbers individually:
if a > b:
n1= a
n2 = b if b > c else c
elif a > c:
n1, n2 = a, b
else:
n1, n2 = b, c
You can Simply Define Function With Using min()
def two_bigger_sum(num1,num2,num3):
min_num = min(num1,num2,num3) # it returns minimum number
return ((num1**2 + num2**2 + num3**2)-(min_num**2)) # num**2 = square of num
print(two_bigger_sum(6,7,8))
Output = 113
Sociopath's answer works, but is inefficient since it requires two extra floating point multiplies. If you're doing this for a large number of items, it will take twice as long! Instead, you can find the two largest numbers directly. Basically, we're sorting the list and taking the two largest, this can be directly as follows:
def sumsquare(a,b,c):
# Strategy: swap, and make sure c is the smallest by the end
if c > b:
b, c = c, b
if c > a:
a, c = c, a
return a**2 + b**2
# Test:
print(sumsquare(3,1,2))
print(sumsquare(3,2,1))
print(sumsquare(1,2,3))
print(sumsquare(1,3,2))
print(sumsquare(2,1,3))
print(sumsquare(2,3,2))
I have tried to use list comprehension & list slicing with sorting method.
def b2(l):
return sum([x**2 for x in sorted(l)[1:]])
print(b2([1,2,3]))
OP:-
13
This is my code:
def sum_even(a, b):
count = 0
for i in range(a, b, 1):
if(i % 2 == 0):
count += [i]
return count
An example I put was print(sum_even(3,7)) and the output is 0. I cannot figure out what is wrong.
Your indentation is off, it should be:
def sum_even(a, b):
count = 0
for i in range(a, b, 1):
if(i % 2 == 0):
count += i
return count
so that return count doesn't get scoped to your for loop (in which case it would return on the 1st iteration, causing it to return 0)
(And change [i] to i)
NOTE: another problem - you should be careful about using range:
>>> range(3,7)
[3, 4, 5, 6]
so if you were to do calls to:
sum_even(3,7)
sum_even(3,8)
right now, they would both output 10, which is incorrect for sum of even integers between 3 and 8, inclusive.
What you really want is probably this instead:
def sum_even(a, b):
return sum(i for i in range(a, b + 1) if i % 2 == 0)
Move the return statement out of the scope of the for loop (otherwise you will return on the first loop iteration).
Change count += [i] to count += i.
Also (not sure if you knew this), range(a, b, 1) will contain all the numbers from a to b - 1 (not b). Moreover, you don't need the 1 argument: range(a,b) will have the same effect. So to contain all the numbers from a to b you should use range(a, b+1).
Probably the quickest way to add all the even numbers from a to b is
sum(i for i in xrange(a, b + 1) if not i % 2)
You can make it far simpler than that, by properly using the step argument to the range function.
def sum_even(a, b):
return sum(range(a + a%2, b + 1, 2))
You don't need the loop; you can use simple algebra:
def sum_even(a, b):
if (a % 2 == 1):
a += 1
if (b % 2 == 1):
b -= 1
return a * (0.5 - 0.25 * a) + b * (0.25 * b + 0.5)
Edit:
As NPE pointed out, my original solution above uses floating-point maths. I wasn't too concerned, since the overhead of floating-point maths is negligible compared with the removal of the looping (e.g. if calling sum_even(10, 10000)). Furthermore, the calculations use (negative) powers of two, so shouldn't be subject by rounding errors.
Anyhow, with the simple trick of multiplying everything by 4 and then dividing again at the end we can use integers throughout, which is preferable.
def sum_even(a, b):
if (a % 2 == 1):
a += 1
if (b % 2 == 1):
b -= 1
return (a * (2 - a) + b * (2 + b)) // 4
I'd like you see how your loops work if b is close to 2^32 ;-)
As Matthew said there is no loop needed but he does not explain why.
The problem is just simple arithmetic sequence wiki. Sum of all items in such sequence is:
(a+b)
Sn = ------- * n
2
where 'a' is a first item, 'b' is last and 'n' is number if items.
If we make 'a' and b' even numbers we can easily solve given problem.
So making 'a' and 'b' even is just:
if ((a & 1)==1):
a = a + 1
if ((b & 1)==1):
b = b - 1
Now think how many items do we have between two even numbers - it is:
b-a
n = --- + 1
2
Put it into equation and you get:
a+b b-a
Sn = ----- * ( ------ + 1)
2 2
so your code looks like:
def sum_even(a,b):
if ((a & 1)==1):
a = a + 1
if ((b & 1)==1):
b = b - 1
return ((a+b)/2) * (1+((b-a)/2))
Of course you may add some code to prevent a be equal or bigger than b etc.
Indentation matters in Python. The code you write returns after the first item processed.
This might be a simple way of doing it using the range function.
the third number in range is a step number, i.e, 0, 2, 4, 6...100
sum = 0
for even_number in range(0,102,2):
sum += even_number
print (sum)
def sum_even(a,b):
count = 0
for i in range(a, b):
if(i % 2 == 0):
count += i
return count
Two mistakes here :
add i instead of [i]
you return the value directly at the first iteration. Move the return count out of the for loop
The sum of all the even numbers between the start and end number (inclusive).
def addEvenNumbers(start,end):
total = 0
if end%2==0:
for x in range(start,end):
if x%2==0:
total+=x
return total+end
else:
for x in range(start,end):
if x%2==0:
total+=x
return total
print addEvenNumbers(4,12)
little bit more fancy with advanced python feature.
def sum(a,b):
return a + b
def evensum(a,b):
a = reduce(sum,[x for x in range(a,b) if x %2 ==0])
return a
SUM of even numbers including min and max numbers:
def sum_evens(minimum, maximum):
sum=0
for i in range(minimum, maximum+1):
if i%2==0:
sum = sum +i
i= i+1
return sum
print(sum_evens(2, 6))
OUTPUT is : 12
sum_evens(2, 6) -> 12 (2 + 4 + 6 = 12)
List based approach,
Use b+1 if you want to include last value.
def sum_even(a, b):
even = [x for x in range (a, b) if x%2 ==0 ]
return sum(even)
print(sum_even(3,6))
4
[Program finished]
This will add up all your even values between 1 and 10 and output the answer which is stored in the variable x
x = 0
for i in range (1,10):
if i %2 == 0:
x = x+1
print(x)
I can't seem to get my function to work. When I type in 3 for a, 2 for b, and 3.61 for c. That works. However, when I try those values in a different order (Ex: 3.61 for a, 3 for b and 2 for c) It returns as false. I can't figure out what the problem is. Thanks in advance!
a = input("Enter a ")
b = input("Enter b ")
c = input("Enter c ")
def isright_angled():
if abs((a**2+b**2)-(c**2)) < 0.1 or abs((c**2-a**2)-(b**2)) < 0.1 or abs((c**2-b**2)-(a**2)) < 0.1:
return True
else:
return False
print isright_angled()
The hypotenuse, if the triangle is right-angled, will be the largest of a, b and c. You can use that to avoid duplicating the test 3 times (this is the "don't repeat yourself" principle). A second thing to avoid is that if something: return True else: return False. It's usually better expressed as simply return something. Thirdly, functions can take arguments rather than relying on global variables: this makes things easier to understand and there's then less chance of functions interfering with each other. I find a * a easier to understand than a ** 2 but that's personal taste. Putting all that together:
def is_approximately_right_angled(a, b, c):
a, b, c = sorted([a, b, c])
return abs(a * a + b * b - c * c) < 0.1
a = input('enter a ')
b = input('enter b ')
c = input('enter c ')
print is_approximately_right_angled(a, b, c)
If it's not working, you can speed up your development by adding some checks. If you were writing a big program you can write unit tests, but here just some asserts in the module will avoid you having to type a, b, c in each time to test.
I'd add something like this (before the a = input... line):
assert is_approximately_right_angled(3, 4, 5)
assert is_approximately_right_angled(3, 5, 4)
assert is_approximately_right_angled(3, 2, 3.61)
assert not is_approximately_right_angled(3, 5, 5)
With these lines in place, you can have some confidence in the code before you get to type numbers in. When you find cases where the code doesn't work you can add them as additional checks.
a = int(input("Enter the side length" ))
b = int(input("Enter the side length" ))
c = int(input("Enter the side length" ))
def is_right_triangle(a,b,c):
'''
is_right_triangle(a,b,c) -> bool
returns True if a,b,c is a right triangle with hypotenuse c
'''
a, b, c = sorted([a, b, c])
return a*a + b*b == c*c
print(is_right_triangle(a,b,c))
for more accuracy you can use
return abs(a * a + b * b - c * c) < 0.001
I am attempting to script a short code to figure out the number of days it takes to reach a given principal in the bank due to daily interest. Using my code below does not yield any errors when run in IDLE, but the counter returns 0. Any ideas what I missed?
def main():
# irrelevant code elided by msw, Bal, Int and Tar are numeric
counter = 0
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
print counter
I'm not sure what you're getting at with this loop:
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
range(0) is an empty list, so the loop won't execute at all.
counter + 1 simply calculates one more than counter, it won't increment counter, you probably mean counter += 1
There's nothing in the loop that changes at each iteration, so if you ever get into it, it will be an infinite loop.
I believe the formula to calculate final balance with interest is:
Final = Principal * ( 1 + interest ) ** interest_period
Assuming I got this correct, then you can find out how many interest periods it will take by:
def how_long(start_money, interest_rate, final_money):
day = 0
money = start_money
while True:
if money >= final_money:
break
day += 1
money = start_money * (1 + interest_rate)**day
return day, money
In [5]: def test():
...: for i in range(0):
...: return '1'
...:
...:
In [6]: x = test()
In [7]: print x
------> print(x)
None
See the return value is 'None'.
I don't know what are you trying to do. But The basic mistake is the Argument of range(x) function. The range(0) always return empty list.
That's because you put range(0) which is an empty loop. Perhaps you could consider a while loop?
Your loop for i in range(0) doesn't actually execute. range(0) returns an empty list [] which will skip the body of your for loop.
Please explain what you think this does? Please update your question with an English-language explanation of how many times you think this look will work.
counter = 0
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
Hint. The answer is zero. The question is "why?" and "what were you trying to do?"
You have been told the three or more problems with your code. If there's no particular reason to use a loop, it's better calculated with a formula:
future_value = present_value * (1 + interest_rate_per_period) ** number_of periods
or, for short,
f = p * (1 + i) ** n
f / p = (1 + i) ** n
log(f / p) = n * log(1 + i)
n = log(f / p) / log(i + i)
Example: I have $5000; how many years will it take to grow to $10000 at 10% per annum?
>>> from math import log
>>> f = 10000.0
>>> p = 5000.0
>>> i = 0.1
>>> n = log(f / p) / log(1 + i)
>>> n
7.272540897341713
>>>