How to dynamically assign an unknown number of list elements? - python

I have this code which works but it's a big function block of IF..ELIF..ELSE. Is there a way to unpack or dynamically assign two lists. The thing is, sometimes mylist could have less elements than 4.
Input:
mylist=['1','2','3','4']
flag=['a','b','c','d']
Output:
A string object like 'a=1/b=2/c=3/d=4/' OR 'a=1/b=2/c=3/' if mylist only has 3 elements.
My current method is just like:
def myoutput(mylist, flag):
if flag=='3':
out = f'a={mylist[0]}/b={mylist[1]}/c={mylist[2]}/'
else:
out = f'a={mylist[0]}/b={mylist[1]}/c={mylist[2]}/d={mylist[3]}/'
return out
I tried to zip the two list, but I do not know the next steps and it doesn't really work:
tag_vars={}
for i in range((zip(mylist,flag))):
tag_vars[f"mylist{i}"] = flag[i]
print(tag_vars)

I would use zip for this task following way
mylist=['1','2','3','4']
flag=['a','b','c','d']
out = ''.join(f'{f}={m}/' for f,m in zip(flag,mylist))
print(out)
output
a=1/b=2/c=3/d=4/
Note that I used f,m with zip so f and m are corresponding elements from flag and mylist. Disclaimer: this solution assumes flag and mylist have always equal lengths.

You can use zip like this:
for a, b in zip(alist, blist): ...
I modified myoutput function to return your desired output
mylist=['1','2','3','4']
flag=['a','b','c','d']
def myoutput(mylist, flag):
result = []
for elem, f in zip(mylist, flag):
result.append(f"{f}={elem}")
return "/".join(result)
print(myoutput(mylist, flag)) # a=1/b=2/c=3/d=4
print(myoutput(mylist[:3], flag)) # a=1/b=2/c=3

Related

Apply map on *args in Python where *args are lists

I want to get a list of lists consisting of only 0 and 1 and map the first element of the first list with the first element of the second list and so on.
My mapping function is this:
def intersect(*values):
result = values[0]
for idx in range(1, len(values)):
result = result << 1
result = result | values[idx]
return result
I'm trying to do this but it does not work:
def intersect_vectors(*vectors):
return list(map(intersect, zip(vectors)))
It would work if I would knew the number of vectors and would have a function like this:
def intersect_vectors(v1, v2, v3):
return list(map(intersect, v1,v2,v3))
Example:
intersect_vectors([1,1],[1,0],[0,1]) would return [6,5] which is [b110, b101]
You can explode your vectors with * and it will work the same:
def intersect_vectors(*vectors):
return list(map(intersect, *vectors))
The simplest solution is probably to delegate the functionality of transforming between a list and 'arguments' to a lambda:
return [list(map((lambda v: intersect(*v)), zip(vectors)))]

To return elements of a list from a function

I want to define a function that takes a list as its argument and then returns the elements in order.
For example:
def iterator(lis):
for e in range(len(lis)):
return lis[e]
l=input("Enter list elements:").split()
x=iterator(l)
print(x)
But this just returns the first value of the list as:
Enter list elements:12 23 34
12
How can I print all the values in successive lines?
You can use yield in order to build a generator, here's the official documentation about Generators
What is a generator in Python?
A Python generator is a function which returns a generator iterator
(just an object we can iterate over) by calling yield. yield may be
called with a value, in which case that value is treated as the
"generated" value.
I also want to share an example, be sure to read the comments:
def iterator(lis):
for e in range(len(lis)):
yield lis[e]
l=input("Enter list elements:").split()
# A generator returns an Iterable so you should
# loop to print
for number in iterator(l):
print(number)
# Or use list
result = list(iterator(l))
print(result)
Output
1
2
3
['1', '2', '3']
You probably want yield, as return causes the function call to end immediately. But yield just produces another iterator; you still need to iterate over the result to print them all, rather than simply printing the iterator itself.
def iterator(lis):
for e in range(len(lis)):
yield lis[e]
...
for element in x:
print(element)
Of course, you are pretty much just reimplementing the existing list iterator here; an equivalent definition would be
def iterator(lis):
yield from lis
What you might want instead is to do something like
x = '\n'.join(l)
print(x)
which creates a string by iterating over l and joining the elements using \n. The resulting multiline string can then be printed.
It will print only one element if you do return
def iterator(lis):
for e in range(len(lis)):
return lis[e]
l=input("Enter list elements:").split()
x=iterator(l)
for y in x: print(y)
Use:
def iterator(list):
for e in range(len(list)):
a= list[e]
print(a)
l=a,b,c=input().split()
a=iterator(l)
Use:
[print(i) for i in input("Enter list elements:").split(" ")]
return causes the function to stop after it hits the statement. So your for loop only ever runs once.
You could use yield as mentioned in the other answers, but I really don't think you need a function in this situation. Because the function is just going to return the list that it took as an argument. What you should do is something like this:
i = input("Enter list elements: ").split()
for x in i:
print(x)
It's that simple.
def iterator(lis):
for e in range(len(lis)):
print( lis[e])
l=input("Enter list elements:").split()
iterator(l)
if you want to do some operations for each item in the list, then you should accomodate those within the function.
Use of print instead of return will give you the expected output..try it once

List-Then-Eliminate implementation in Python

I'm trying to implement the List-Then-Eliminate algorithm using a dataset. However, I am getting the wrong vector space at the end. I am unable to figure out what the issue is.
Basically, I iterate through all the training instances. For each hypothesis, I use the last 5 bits to check if the training instance, x is the same and then compare the c(x)
Any assistance would be appreciated. Below is my code.
def gen_vector_space(k):
return [''.join(x) for x in itertools.product('01', repeat=k)]
#basically values from 0-65536 in binary
vector_space = gen_vector_space(pow(2,4))
for train_inst in train_data:
result = train_inst[-1]
d = train_inst[:-1]
for h in vector_space:
if h[-5:-1] == d:
if (h[-1] != result):
vector_space.remove(h)
print(len(vector_space))
I'd suggest an edit to the function that creates your vector space. Starting with your original function:
def create_space(k):
return [''.join(x) for x in itertools.product('01', repeat=k)]
When you call that function, you are completely iterating over that range to build the list, then iterating the list again to filter out values. Two approaches to fix that:
If statements in function
# Redefine your function to only return values that matter to you
def create_space(k, d, result):
"""
This will filter out your limits, takes result and d as params
"""
vector_space = []
for x in itertools.product('01', repeat=k):
if x[-5:-1]==d and x[-1]!= result:
vector_space.append(x)
return vector_space
# define k, d, and result here
vector_space = create_space(k, d, result)
Generator Approach
Or, the yield keyword will calculate values one at a time, so you are only iterating once:
def create_space(k):
for x in itertools.product('01', repeat=k):
yield x
vector_space = []
# define d and result here
for x in create_space(k):
if x[-5:-1]==d and x[-1]!= result:
vector_space.append(x)
The thing to note with either of these approaches is that I'm not editing an already established object while iterating over it. Instead, I've put the filtering on before the space is created, that way you get exactly what you want on the first go.

Using simple Recursion to create a list

I want every element in l(which is a list) to be added to a.
When I run the function, it gives me '[]' every time. How can I fix this?
def sim(l):
a = []
if len(l)>0:
a = a.append(l.pop())
l.pop()
return sim(l)
return a
Several things are wrong:
You shouldn't use lowercase L for a variable name - it looks like one
At the top of the function you assign an empty list to a - ultimately sim will be called with an empty list, then a will be assigned an empty list, the conditional statement will fail and sim will return an empty list.
Inside the conditional statement you assign the return value of list.append() to a. The return value is None so whatever a was before, it gets wiped out.
Inside the conditional statement you pop() two items out of your control list
An empty list has a boolean value of false so there is no need to explicitly check its length,
def sim(el, a = None):
if el:
a.append(el.pop())
return sim(el, a)
return a
I was taught to write the base case of a recursive function as the first statement:
def sim(el, a = None):
if not el:
return a
a.append(el.pop())
return sim(el, a)
append() doesn't return anything but does update the existing list. In other words, by trying to assign the result of the append() method, you're setting a to nothing after you have already appended the item.
Your Code :def sim(l):
a = []
when you call Function recursively return sim(l) every time it is call sim(l) and a=[] is empty.
Try This :
def sim(l,a):
if len(l)>0:
a.append(l.pop())
print a
return sim(l,a)
return a
Is this a homework assignment where you're required to do it in a certain (overly complicated) way? Because if not, you can add one list to another in Python like so:
>>> l = [1, 2, 3]
>>> a = []
>>> a.extend(l)
>>> a
[1, 2, 3]

(Python 2.7) Use a list as an argument in a function?

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.

Categories