I've written a function to find the standard deviation of a list:
def avg(L):
return sum(L)/len(L)
def stdDev(L):
for i in range(len(L)-1):
return sqrt((sum(L[i]-avg(L)))**2)/len(L))
If I run this and give the Shell the input [20,10,30] it says "float object is not iterable". Where is the issue, and can I solve it without settling for integer results of either of these functions?
sum(L[i]-avg(L)) - here you have a sum of float.
You also have return statement every pass of the loop, that's clearly wrong.
Formula for standard deviation also is not right, as you misplaced the braces.
What I believe you wanted:
def stdDev(L):
s = 0
for i in range(len(L)):
s += (L[i] - avg(L))**2
return sqrt(s/len(L))
Better to iterate through elements than their indices:
for x in L:
s += (x - avg(L))**2
or
def stdDev(L):
ave = avg(L)
s = sum((x - ave)**2 for x in L)
return sqrt(s/len(L))
Related
def fibonaci(i,memo):
if i == 0 or i == 1:
return i
if memo[i]==-1:
memo[i] = fibonaci(i-1,memo) + fibonaci(i-2,memo)
return memo[i]
def fibo(n):
a = []
return fibonaci(n,a)
print(fibo(2))
I'm a Java programmer learning python. This algorithm computes the nth fibonacci number using recursion + memoization. I don't understand why I'm seeing this error "IndexError: list index out of range" when running the program in python. Can anybody help? Thanks a ton!
As suggested in the comments to your question, there is no way memo[i]==-1 could be true.
I understand your want to test something like "if the value for fibonacci(i) has not yet been memoized", but the way Python will tell you in index is not present is certainly not by returning some magic value (like -1), but instead by raising an exception.
Looking up "EAFP" (easier to ask for forgiveness than permission) on your favorite search engine might show you why exceptions are not to be understood as errors, in python.
In addition, memoization will be preferably implemented by a dictionary, rather than a list (because dictionaries allow to map a value to any possible key, not necessarily to the next integer index value).
Without changing too much to the structure of your program, I would suggest the following :
def fibonaci(i,memo):
if i == 0 or i == 1:
return i
try:
memo[i]
except KeyError:
memo[i] = fibonaci(i-1,memo) + fibonaci(i-2,memo)
return memo[i]
def fibo(n):
a = {}
return fibonaci(n,a)
print(fibo(2))
I made few changes in your code to get nth Fibonacci no.(there might be other way too)
def fibonaci(i,memo):
if i == 0 or i == 1:
return i
if memo[i] == -1:
memo[i] = fibonaci(i-1,memo) + fibonaci(i-2,memo)
return memo[i]
def fibo(n):
a = [-1] * n
return fibonaci(n-1,a)
print(fibo(5))
print(fibo(10))
print(fibo(13))
print(fibo(57))
And output is :-
3
34
144
225851433717
You are seeing the error because you create an empty list with a = [] and then you try to look into it. You need to create a list long enough to index from zero up to n-1.
That being said, an easy way to do memoisation in Python is using the cache function from functools. This code does the memoisation for you:
from functools import cache
#cache
def fib(n):
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2)
for n in range(10):
print(f"{fib(n) = }")
It isn't quite as efficient in running time, but in programmer time it is.
def binary(n):
if n>0:
return binary(n//2)*10 + (n%2)
else:
return 0
The answer is 10000000 but it have to be "10000000". How can I put str on the answer?
In python, to change the type of anything, the only thing you have to do is wrap that in str(), int(), float()... or whatever type you want to change it to.
more details: http://usingpython.com/python-casting/
edit: sorry, didn't realize the recursive problem, still, I don't see why you can't just change the type after the function returns, seems the easiest thing to do.
if you insist though:
def binary(n):
if int(n)>0:
return str( int(binary(str(int(n)//2)))*10 + (int(n)%2))
else:
return str(0)
I will suggest that you use nested/inner functions as shown below to solve you problem. This allows you to compute the result using integers, and then convert the result to a string, or any other type, before returning it.
def binary(n):
def inner(m):
if m>0:
return inner(m//2)*10 + (m%2)
else:
return 0
return str(inner(n))
Alternatively you can cast n to the correct type whenever you use it. This is, in my opinion, a horrible to solve the problem, but it should still do the trick.
def binary(n):
if int(n) > 0:
return str(int(binary(n//2))*10 + n%2)
else:
return "0"
The problem with simply wrapping your return in a cast to str(), is that the subsequent calls to binary() will be affected, not just the top-level call. After the deepest recursive call to binary has finished, it will return its result - which is a string - to the next deepest recursive call to the expression:
binary(n // 2) * 10 + (n % 2)
But since the return value is a string, it fails when used in the expression.
The obvious solution is to simply cast the return value of binary() to a string from wherever it's being called. However, if for some reason you cannot do this, you can make a second function nested under binary, call this function inside of binary(), and cast its result to a string:
>>> def binary(n):
def _binary(n):
if n > 0:
return _binary(n // 2) * 10 + (n % 2)
else:
return 0
return str(_binary(n))
>>> binary(128)
'10000000'
>>> binary(64)
'1000000'
>>> binary(32)
'100000'
>>> binary(16)
'10000'
>>> binary(8)
'1000'
>>> binary(4)
'100'
>>> binary(2)
'10'
>>>
As #StefanPochmann pointed out, this method would also work:
def binary(n):
return binary(n // 2) + str(n % 2) if n > 1 else str(n)
I need to write a function using recursion that accepts the following variables:
n: int
x: real
and returns the exponential sum function:
I can't use loops at all, only recursion.
I started by writing two recursive functions for sum and factorial but when I tried to combine the two of them I got the error message:
TypeError: 'int' object is not iterable
I don't quite understand what it means because I didn't use loops, only recursion. Here is my code:
def sum_exp(n):
if n == 0:
return 0
return n + sum(n - 1)
def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1)
def exp_n_x(n, x):
if n == 0:
return 1
else:
return sum_exp(x*(1/factorial(n)))
print(exp_n_x(10, 10))
I would love to get some help with this. Thanks a lot in advance.
you've made a typo in:
def sum_exp(n):
if n == 0:
return 0
return n + sum(n - 1)
^^^
where you use the global function sum() which takes an iterable and returns the sum of its elements. Thus:
>>> sum(42)
TypeError: 'int' object is not iterable
whereas
>>> sum([42])
42
so your fix is straightforward:
def sum_exp(n):
if n == 0:
return 0
return n + sum_exp(n - 1)
N.B.: This answer is only meant to fix your issue with the TypeError, and get you going to the next error you'll hit, which is an infinite recursion. As an advice you should double check your stop condition and recursion step.
There is a function that returns a sum of integers from list x that are greater than integer y. If there is none of the numbers greater than y the function returns 0.
def sum_greater(x, y):
result = 0
for i in range(len(x)):
if x[i] > y:
result = result + x[i]
return result
My question: is it possible (and if it is than how) to make a list comprehension from this function?
You can use the sum() function with a generator expression:
sum(i for i in x if i > y)
Since 0 is the natural result of the sum of nothing, that doesn't need any special handling. You can send a generator expression to the built-in sum:
def sum_greater(x, y):
return sum(i for i in x if i>y)
I am new to programming, and was trying to solve this problem on Project Euler using basic Python.
Essentially, I tried to use recursion based on the largest value chosen at every stage, and using a list to maintain possible options for future choices.
The code is short and is given below:
def func(n,l):
if n<0:
return 0
if l==[1] or n==0:
return 1
else:
j=0
while l != []:
j=j+func(n-l[0],l)
del l[0]
return j
print func(200,[200,100,50,20,10,5,2,1])
For instance, if we have
func(5,[5,2,1])
the recursion splits it into
func(0,[5,2,1]) + func(3,[2,1]) + func(4,[1])
But the code never seems to go through. Either it says that there is a list-index-out-of-range error, or a maximum-recursion-depth error (even for very small toy instances). I am unable to find the mistake. Any help will be much appreciated.
In Python lists are passed into functions by reference, but not by value. The simplest fix for your program is changing recursive call to func(n - l[0], l[:]). In this way list will be passed by value.
One thing you're failing to take into account is that the following:
j=j+func(n-l[0],l)
doesn't make a copy of l.
Therefore all recursive invocations of func operate on the same list. When the innermost invocation deletes the last element of l and returns, its caller will attempt to del l[0] and will get an IndexError.
At each recursion, make the following 2 decisions:
Take the first coin (say f) from available coin types, then check if we can made (n-f) from those coins. This results in a sub-problem func(n - f, l)
Ignore the first coin type, and check if we can make n from the remaining coin types. This results in a sub-problem func(n, l[1:])
The total number of combinations should be the sum of the two sub-problems. So the code goes:
def func(n, l):
if n == 0:
return 1
if n < 0 or len(l) == 0:
return 0
if l == [1] or n == 0:
return 1
return func(n - l[0], l) + func(n, l[1:])
Each recursion a copy of l is made by l[1:]. This can be omitted by pop element before next recursion and restore with append afterwards.
def func(n, l):
if n == 0:
return 1
if n < 0 or len(l) == 0:
return 0
if l == [1] or n == 0:
return 1
full = func(n - l[-1], l)
last = l.pop()
partial = func(n, l)
l.append(last)
return full + partial