How to apply some operation to each element of a tuple - python

I have a tuple like (p1, p2) (for example (5,3) or (2,1))
I want to apply the same operation to each element of the tuple. (Incidentally this operation will give for each element another tuple, so I will have a tuple of tuples but this is not a necessary condition)
First I thought something like
for element in (3,2):
res=function(element)
but first, this doesn't seem a elegant solution and two, I would still have to form a tuple from each res to get a (function(3),function(2)) solution
How can I apply a function (with several arguments) to each element of the tuple once and get a tuple of returned values?

If I understand you question correctly, map should to the job as well:
tuple(map(func, tpl))
where func is a one-argument function you defined.
Now, if you have a function with several arguments you would like to apply to each element, like:
def func(x, y, z): return x*y+z
I assume that 2 elements (let's take y and z) are fixed, while x will be determined by the value in the tuple.
There are two approaches in my view:
Either you define a new function with 2 fixed arguments and map:
def func1(x): return func(x, 3, 2)
tuple(map(func1, tpl))
Or map as follows (I think it is less elegant, but it is a matter of tastes, maybe):
tuple(map(lambda x: func(x, 3, 2), tpl))

One approach uses a list comprehension:
def add_one(x):
return x + 1
tpl = (5, 3)
output = tuple([add_one(x) for x in tpl])
print(output) # (6, 4)

You may consider using the generator comprehension then convert it to tuple:
>>> data = (3, 5, 7, 9)
>>> tuple((function(x) for x in data))

Related

A way for iterable zip like single element for Python

Hi guys I just want to know if there's a way to iterate over a tuple that behaves like zip.
For example:
zipper = zip(['aye', 'bee'], ['ex', 'why'])
for x, y in zipper:
print(x, y)
aye ex
bee why
tupl = 3, 2
for x, y in tupl:
print(x, y)
# 'int' object is not iterable.
What I knew now is that it can't be zip-ed:
tupl = zip(3, 2)
# zip argument #1 must support iteration
I am trying to pass zipper into a function, I also hope to pass the tuple or a single set of zip.
def processthis(zipper):
for x, y in zipper:
# do something with x and y
With a loop of for x, y in tupl: you are expecting tupl to be a sequence of tuples, rather than a tuple.
If you want your loop to process only one tuple you should assign tupl with [(3, 2)] instead of (3, 2).
Parenthesis are missing.
When passing a tuple to function, it needs to be wrapped by parenthesis.
In your case,
zip((3, 2), (4, 5)) # zipping 2 tuples
Otherwise, zip will sees 3 and 2 as two positional arguments.

Python: evaluating a function with the argument taking multiple values

Asssume I have a function in python which returns the power of 2 of its input
def f(x):
return x**2
Assume also I have a vector of integers 1,2,3,4,5
I = asarray(list(range(1,6)))
Now I want to evaluate the function f with all inputs from I and the results should be in a vector of dimensions 5 (A 1x5 array in Python). My desired result is then: [1,4,9,16,25].
Can I get this result WITHOUT the use of a for or any other loop?
I have used array package
directly from the pythontips website...
use the map function!
squared = list(map(lambda x: x**2, I))
if you want to use your function inside the map-function, just do squared = list(map(f, I)).
There are generally two classical ways to apply a function to all elements of an iterable and store the results in a list. The more flexible one is a list comprehension:
result = [f(x) for x in range(1, 6)] # the upper bound is exclusive!
The other option is map which allows a more concise notation, in particular if you have a named function available and do not need to use a lambda or the like:
result = map(f, range(1, 6)) # Python2: returns list
result = list(map(f, range(1, 6))) # Python3: return iterator, so cast

Python. How to optimize search functions

There any way to optimize these two functions ?
first function:
def searchList(list_, element):
for i in range (0,len(list_)):
if(list_[i] == element):
return True
return False
second function:
return_list=[]
for x in list_search:
if searchList(list_users,x)==False:
return_list.append(x)
Yes:
return_list = [x for x in list_search if x not in list_users]
The first function basically checks for membership, in which case you could use the in keyword. The second function can be reduced to a list comprehension to filter out elements from list_search list based on your condition.
For first function
def searchList(list, element):
return element in list
You can make it in 1 line
searchList = lambda x,y: y in x
For 2nd, use a list comp like shown in the other answer
What you are doing with your two functions is building the complement as ozgur pointed out.
Using sets is the most easy thing here
>>> set([2,2,2,3,3,4])- set([1,2,2,4,5])
set([3])
your list_search would be the first list and your list_users the second list.
The only difference is that your new user is only once in the result no matter how often it is in the list_search
Disclaimer: I assumed list_search has no duplicate elements. Otherwise, use this solution.
What you want is exactly the set complement of list_users in list_search.
As an alternative approach, you can use sets to get the difference between two lists and I think it should be much more performant than the naive look up which takes 0(n^2).
>>> list_search = [1, 2, 3, 4]
>>> list_users = [4, 5, 1, 6]
>>> print set(list_search).difference(list_users)
>>> {2, 3}

How to write a program for multiplying list of numbers in shortest line?

I come to this point when I was making a simple calculator. I did a simple program to sum the list of numbers as follows, But the program for multiplication is a little bit long.
So can anybody have any idea how to make short program to multiple list of numbers in python. Here is my code what looks like.
def calculate(oper,*nm):
return oper(nm)
add=lambda x:sum(x)
def mult(lst):
tmp=1
for i in lst:
tmp*=i
return tmp
calculate(add,2,34,2)
calculate(mult,8,5,7)
Really, you do not need to define calculate because Python already has a name for it: reduce.
def calculate(oper, *nm):
return reduce(oper, nm)
In [6]: import operator
In [7]: calculate(operator.add, 2, 34, 2)
Out[7]: 38
In [8]: calculate(operator.mul, 8, 5, 7)
Out[9]: 280
Note: In Python3, reduce has been moved to the functools module. (Thanks to #ErikRoper for pointing this out.)
You can use the in-built reduce function, which takes a callable, a list and an optional starting element. It calls callable with a tuple (elem, result) where element is the ith element from the list and result is the result so far.
reduce(lambda item,prod: item * prod, range(1, 5), 1)
Out[2]: 24
So the above would call the lambda function first with (1,1), then with (2,1*1) then (3,2*1) and finally (4,3*2)
So you'd define add and mult and replace your calculate with the built-in reduce
add = lambda item,cumul_sum: item + cumul_sum
mult = lambda item,product: item * product
reduce(add, range(1,5), 0)
Out[5]: 10
reduce(mult, range(1,5), 1)
Out[6]: 24
http://docs.python.org/2.7/library/functions.html?highlight=reduce#reduce

Reversing a nested tuple in Python using the function reversed

I have a tuple and would like to reverse it in Python.
The tuple looks like this : (2, (4, (1, (10, None)))).
I tried reversing in Python by:
a = (2, (4, (1, (10, None))))
b = reversed(a)
It returns me this:
<reversed object at 0x02C73270>
How do I get the reverse of a? Or must I write a function to do this?
The result should look like this:
((((None, 10), 1), 4), 2)
def my_reverser(x):
try:
x_ = x[::-1]
except TypeError:
return x
else:
return x if len(x) == 1 else tuple(my_reverser(e) for e in x_)
Try this deep-reverse function:
def deep_reverse(t):
return tuple(deep_reverse(x) if isinstance(x, tuple) else x
for x in reversed(t))
This will handle arbitrarily nested tuples, not just two-tuples.
As explained in the documentation, the reversed function returns an iterator (hence the <reversed at ...>). If you want to get a list or a tuple out of it, just use list(reversed(...)) or tuple(reversed(...)).
However, it's only part of our problem: you'll be reversing the initial object (2, (...)) as (...,2), while the ... stays the same. You have to implement a recursive reverse: if one element of your input tuple is an iterable, you need to reverse it to.
It does not make sense to do this with reversed, sorry. But a simple recursive function would return what you want:
def reversedLinkedTuple(t):
if t is None:
return t
a, b = t
return reversedLinkedTuple(b), a
reversed is usable only on reversible iterable objects like lists, tuples and the like. What you are using (a linked list) isn't iterable in the sense of the Python built-in iter.
You could write a wrapping class for your linked list which implements this and then offers a reverse iterator, but I think that would be overkill and would not really suit your needs.
def reverse(x):
while x >= 0:
print(x)
x = x = 1
reverse(x)

Categories