I have done some writing like below
new_list = ["000","122","121","230"]
for item in new_list:
r = [np.matrix([[0.5,0.5],[0,1]]),
np.matrix([[0.5,0.25],[0,1]]),
np.matrix([[0.5,0.25],[0,1]]),
np.matrix([[0.5,0],[0,1]])]
(W0,W1,W2,W3) = r
for i in item:
i == 0
if item[i] == 0:
return W0
elif item[i] == 1:
return W1
elif item[i] == 2:
return W2
else:
return W3
i = i + 1
list_new = [np.matrix([1,0]) * new_list * np.matrix([0.5],[1])]
print(list_new)
I want to create a program for example when the input from the list is "122", it will multiply each element inside "122" as matrix W1*W2*W2.
The final result should be like
np.matrix([1,0]) * new_list2 * np.matrix([0.5],[1])
The
new_list2
here should be all multiplication result from the new_list. Meaning
new_list2 = [W0*W0*W0,W1*W2*W2,...]
I run this code and keep getting a syntax error saying
"return" outside function
I want to ask did I missed something here or there is other function/way to make it done using python. I am using Python 3.5
Thank you for the answer.
As the error message says, you are using "return" outside a function, which just doesn't make sense since "return" means "exit the function now and pass this value (or None if you don't specify a value) to the caller". If you're not inside function there is no caller to returns to...
Something like this?
import numpy as np
from functools import reduce
new_list = ["000", "122", "121", "230"]
matrices = [
np.matrix([[0.5,0.50],[0,1]]),
np.matrix([[0.5,0.25],[0,1]]),
np.matrix([[0.5,0.25],[0,1]]),
np.matrix([[0.5,0.00],[0,1]])
]
def multiply(s):
mt_seq = (matrices[i] for i in map(int, item))
return reduce(np.multiply, mt_seq) # or reversed(mt_seq)
for item in new_list:
print(multiply(item))
You can just convert each digit in the string with int(digit), e.g. int('2'), and do it for every element of the string with map(int, '01234').
Then, it's just a matter of taking those matrices and multiplying them. (Sorry, I am not familiar with np.multiply and np.matrix and maybe you need to reverse the order of multplication)
reduce(fun, seq) applies fun to seq, like this: fun(fun(fun(seq[0], seq[1]), seq[2]), ...)
Related
i have a function to append a list, something like this:
def append_func(element):
if xxxx:
new_list.append(element)
else:
[]
I have another function that uses append_func():
def second_func(item):
for i in item:
append_func(i)
if i run :
new_list = []
second _func(item)
new_list
This will return the list i want, but i can't do new_list = second _func(item) because in this case new_list will be a None.
I understand that append() will return a None type, but i'd like to return the appended list so I can use in other places result = second _func(xxx), what i have missed? Thanks.
According to the clarification you did in the comments you might want something like this. (I changed some of your placeholders so we have running code and a reproducible example)
The list is created by second_func so we get rid of the global list.
def append_func(data, element):
if 2 < element < 7:
data.append(element ** 2)
def second_func(items):
new_list = []
for i in items:
append_func(new_list, i)
return new_list
items = list(range(10))
result = second_func(items)
print(result)
The result is [9, 16, 25, 36].
simply tell python what to return:
def append_func(element):
if xxxx:
new_list.append(element)
else:
[]
return new_list # here, return whatever you want to return
if there is no "return" statement in the function, then the function returns None
The new_list you define before calling second_func is a global variable. Every time you call second_func() it will append the argument to the global variable. But the new_list is not restricted to the namespace of either function, so setting it as a return value doesn't make sense.
I'm attempting to generate all n choose k combinations of a list (not checking for uniqueness) recursively by following the strategy of either include or not include an element for each recursive call. I can definitely print out the combinations but I for the life of me cannot figure out how to return the correct list in Python. Here are some attempts below:
class getCombinationsClass:
def __init__(self,array,k):
#initialize empty array
self.new_array = []
for i in xrange(k):
self.new_array.append(0)
self.final = []
self.combinationUtil(array,0,self.new_array,0,k)
def combinationUtil(self,array,array_index,current_combo, current_combo_index,k):
if current_combo_index == k:
self.final.append(current_combo)
return
if array_index >= len(array):
return
current_combo[current_combo_index] = array[array_index]
#if current item included
self.combinationUtil(array,array_index+1,current_combo,current_combo_index+1,k)
#if current item not included
self.combinationUtil(array,array_index+1,current_combo,current_combo_index,k)
In the above example I tried to append the result to an external list which didn't seem to work. I also tried implementing this by recursively constructing a list which is finally returned:
def getCombinations(array,k):
#initialize empty array
new_array = []
for i in xrange(k):
new_array.append(0)
return getCombinationsUtil(array,0,new_array,0,k)
def getCombinationsUtil(array,array_index,current_combo, current_combo_index,k):
if current_combo_index == k:
return [current_combo]
if array_index >= len(array):
return []
current_combo[current_combo_index] = array[array_index]
#if current item included & not included
return getCombinationsUtil(array,array_index+1,current_combo,current_combo_index+1,k) + getCombinationsUtil(array,array_index+1,current_combo,current_combo_index,k)
When I tested this out for the list [1,2,3] and k = 2, for both implementations, I kept getting back the result [[3,3],[3,3],[3,3]]. However, if I actually print out the 'current_combo' variable within the inner (current_combo_index == k) if statement, the correct combinations print out. What gives? I am misunderstanding something to do with variable scope or Python lists?
The second method goes wrong because the line
return [current_combo]
returns a reference to current_combo. At the end of the program, all the combinations returned are references to the same current_combo.
You can fix this by making a copy of the current_combo by changing the line to:
return [current_combo[:]]
The first method fails for the same reason, you need to change:
self.final.append(current_combo)
to
self.final.append(current_combo[:])
Check this out: itertools.combinations. You can take a look at the implementation as well.
I'm trying to create a function that multiplies each item in a list and returns the total. The function doesn't stop running until memory runs out.
Can someone please explain to me why this isn't working?
items = [1,2,3,4,10]
def mult2(items):
if not items:
return 0
return mult2(items[0]) * mult2(items[1:])
mult2(items)
Couple of mistakes here
Your base case is wrong. The Base case has to be when the list is reduced to a single element and you need to return 1 and not 0.
You need to send a list with a single element and not the single element alone to meet your base case.
Corrected code
def mult2(items):
if len(items)==1:
return items[0]
return mult2([items[0]]) * mult2(items[1:])
Demo
>>> items = [1,2,3,4,10]
>>>
>>> def mult2(items):
... if len(items)==1:
... return items[0]
... return mult2([items[0]]) * mult2(items[1:])
...
>>> print(mult2(items))
240
There are two issues:
Single element is passed to mult2, but sequence is expected. That's why TypeError: 'int' object has no attribute '__getitem__' is raised, due to trying to subscripting int (code being executed resolves to 1[1:] which is simply not possible).
Your exit condition is broken. Neutral multiplier is 1, not 0.
After fixes your code would look like this:
def mult2(seq):
if not seq:
return 1
return seq[0] * mult2(seq[1:])
items = [1,2,3,4,10]
assert 240 == mult2(items)
You don't have a base case for your recursion that works properly.
Consider calling mult2 with [1,2,3] this gets to the return statement which called mult2 with 1 and with [1,2].
The problem is in the call to mult2 with the parameter 1 which is just an integer. When you get to the recursive part there's no indexing available because items is just an int at this point, so items[0] and items[1:] don't make sense at this point.
Fixed the errors in the OP, and this works:
items = [1,2,3,4,10]
def mult2(items):
if len(items) == 1:
return items[0]
return items[0] * mult2(items[1:])
print "sum:",mult2(items)
my code consists of me recreating the function 'filter()' and using it with a function to filter words longer than 5 characters. It worked with the actual function filter when I tried it btw...I'm using python 3+
def filter1(fn, a):
i = 0
while i != len(a):
u = i - 1
a[i] = fn(a[i], a[u])
i += 1
return a
def filter_long_words(l):
if len[l] > 5:
return [l]
listered = ['blue', 'hdfdhsf', 'dsfjbdsf', 'jole']
print(list(filter1(filter_long_words, listered)))
getting error
TypeError: filter_long_words() takes 1 positional argument but 2 were given
You are passing two parameters to fn (which refers to filter_long_words) here:
a[i] = fn(a[i], a[u])
But filter_long_words only accepts one parameter.
Notes:
You can loop through lists using for item in my_list, or if you want index as well for index, item in enumerate(my_list).
I think you might get an IndexError since u will be -1 in the first round of your loop.
The filter function can also be expressed as a list comprehension: (item for item in listered if filter_long_words(item))
My version of filter would look like this, if I have to use a for loop:
def my_filter(fn, sequence):
if fn is None:
fn = lambda x: x
for item in sequence:
if fn(item):
yield item
Since you have stated that you are using Python 3, this returns a generator instead of a list. If you want it to return a list:
def my_filter(fn, sequence):
if fn is None:
fn = lambda x: x
acc = []
for item in sequence:
if fn(item):
acc.append(item)
return acc
If you don't need to use a for loop:
def my_filter(fn, sequence):
if fn is None:
fn = lambda x: x
return (item for item in sequence if fn(item))
Your're calling fn with 2 parameters in filter1(fn, a), and since you've passed filter_long_words() to filter1 as fn, that triggers the error.
But there's more weird stuff:
I don't understand the magick of filter1 or what you were trying to
accomplish, but it seems to me that you don't have a clear idea what to do.
But if you want to mimic (somehow) how filter works, you have to return a
list which contains only items for which the fn function returns true. When
you know this, you can rewrite it - here are a few suggestions for rewrite
# explicit, inefficient and long, but straightforward version:
def filter1(fn, a):
new_list = []
for item in a:
if fn(item):
new_list.append(item):
return new_list
# shorter version using list comprehensions:
def filter1(fn, a):
return [item for item in a if fn(item)]
The filter_long_words function is wrong too - it should return True or
False. The only reason why it could work is because any non-empty list is
treated as True by python and default return value of a function is None,
which translates to False. But it's confusing and syntactically wrong to use
len[l] - the proper usage is len(l).
There are a few suggestions for rewrite, which all returns explicit boolean
values:
# unnecessary long, but self-explanatory:
def filter_long_words(l):
if len(l) > 5:
return True
else
return False
# short variant
def filter_long_words(l):
return len(l) > 5
You are calling "filter_long_words" with 2 parameter => fn(a[i], a[u]) also there is an error
def filter_long_words(l):
if **len[l]** > 5:
return [l]
len is builtin method it should be len(l)
So I'm trying to learn Python using codecademy but I'm stuck. It's asking me to define a function that takes a list as an argument. This is the code I have:
# Write your function below!
def fizz_count(*x):
count = 0
for x in fizz_count:
if x == "fizz":
count += 1
return count
It's probably something stupid I've done wrong, but it keeps telling me to make sure the function only takes one parameter, "x". def fizz_count(x): doesn't work either though. What am I supposed to do here?
Edit: Thanks for the help everyone, I see what I was doing wrong now.
There are a handful of problems here:
You're trying to iterate over fizz_count. But fizz_count is your function. x is your passed-in argument. So it should be for x in x: (but see #3).
You're accepting one argument with *x. The * causes x to be a tuple of all arguments. If you only pass one, a list, then the list is x[0] and items of the list are x[0][0], x[0][1] and so on. Easier to just accept x.
You're using your argument, x, as the placeholder for items in your list when you iterate over it, which means after the loop, x no longer refers to the passed-in list, but to the last item of it. This would actually work in this case because you don't use x afterward, but for clarity it's better to use a different variable name.
Some of your variable names could be more descriptive.
Putting these together we get something like this:
def fizz_count(sequence):
count = 0
for item in sequence:
if item == "fizz":
count += 1
return count
I assume you're taking the long way 'round for learning porpoises, which don't swim so fast. A better way to write this might be:
def fizz_count(sequence):
return sum(item == "fizz" for item in sequence)
But in fact list has a count() method, as does tuple, so if you know for sure that your argument is a list or tuple (and not some other kind of sequence), you can just do:
def fizz_count(sequence):
return sequence.count("fizz")
In fact, that's so simple, you hardly need to write a function for it!
when you pass *x to a function, then x is a list. Do either
def function(x):
# x is a variable
...
function('foo') # pass a single variable
funciton(['foo', 'bar']) # pass a list, explicitly
or
def function(*args):
# args is a list of unspecified size
...
function('foo') # x is list of 1 element
function('foo', 'bar') # x is list with two elements
Your function isn't taking a list as an argument. *x expands to consume your passed arguments, so your function is expecting to be called like this:
f(1, 2, 3)
Not like this:
f([1, 2, 3])
Notice the lack of a list object in your first example. Get rid of the *, as you don't need it:
# Write your function below!
def fizz_count(lst):
count = 0
for elem in lst:
if elem == "fizz":
count += 1
return count
You can also just use list.count:
# Write your function below!
def fizz_count(lst):
return lst.count('fizz')
It must be a typo. You're trying to iterate over the function name.
try this:
def fizz_count(x):
counter = 0
for element in x:
if element == "fizz":
counter += 1
return counter
Try this:
# Write your function below!
def fizz_count(x):
count = 0
for i in x:
if i == "fizz":
count += 1
return count
Sample :
>>> fizz_count(['test','fizz','buzz'])
1
for i in x: will iterate through every elements of list x. Suggest you to read more here.