Related
I'm trying to write a higher order function that will take 2 lambda expressions and a list and will return the result. I have my code below.
#Square
square = lambda x:x ** 2
#Mod_2
mod_2 = lambda x:x % 2
def map(f,x):
return f(x)
It looks very simple, and should be. This is the error I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "main.py", line 8, in map
return f(x)
File "main.py", line 2, in <lambda>
square = lambda x:x ** 2
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
Here's what the results should be:
>>> map(square, [1, 2, 3, 4])
[1, 4, 9, 16]
>>> map(square, [])
[]
>>> map(mod_2, range(1, 11))
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
This is NOT homework, and is simply and way to understand higher order functions better. Also, this is not a repeat of any other submission because this is fixing MY code, not how to do the problem itself. If it needs rethinking, please reply and tell me how. Thank you!
Use a list comprehension:
def map(f,x):
return [f(i) for i in x]
You can use a lambda here too:
map = lambda f, x: [f(i) for i in x]
Or just use the map() built-in.
map() is a built-in function. Why are you redefining it? Delete def map().
#Square
square = lambda x: x**2
#Mod_2
mod_2 = lambda x:x % 2
r1 = list(map(square, [1, 2, 3, 4]))
r2 = list(map(mod_2, range(1, 11)))
I am learning python3 list comprehensions. I understand how to format a list comprehension: [equation, for loop, if statement for filtering], but I cannot figure out how to condense three lines of code into a single equation for the 'equation' part.
I am taking a number and adding it to itself and then taking the result and adding it to itself and so on to create a sequence of numbers in the list.
I can accomplish this by declaring x = 1 and then looping the following:
y = x + x
x = y
Can anybody help me to turn this into a single-lined equation and if possible, resources that I might study to help me with this in the future?
Your algorithm is equivalent to multiplying by powers of 2:
x = 3
res = [x * 2**i for i in range(10)]
# [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]
To see why this is the case, note you are multiplying your starting number by 2 in each iteration of your for loop:
x = 3
res = [x]
for _ in range(9):
y = x + x
x = y
res.append(y)
print(res)
# [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]
As #timgeb mentions, you can't refer to elements of your list comprehension as you go along, as they are not available until the comprehension is complete.
I want to know what's happening with that part of the code. Why I have that output? Thank you in advance!
n = 10
powersOfThree = (3**x for x in range(n))
print(powersOfThree)
The output is: <generator object <genexpr> at 0x055BEF90>
Using parenthesis ( ) around your comprehension, that gives you a generator as introduced by Python here https://wiki.python.org/moin/Generators
If you want a list, you can replace your parenthesis by [ and ]
>>> n = 10
>>> powersOfThree = [3**x for x in range(n)]
>>> powersOfThree
[1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
If you really wanted a tuple as output, then you can use tuple() :
>>> tuple(3**x for x in range(n))
(1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683)
I believe this is what you are trying to do. Your mistake was using '(' instead of '['.
n = 10
powersOfThree=[3**i for i in range(0,n)]
print(powersOfThree)
l = [x**0.5 for x in range(101)]
print l
This code outputs:
[0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0, 3.162277660168379, 3.3166247903554, 3.4641016151377544, 3.605551275463989, 3.7416573867739413, 3.872983346207417, 4.0, 4.123105625617661, 4.242640687119285, 4.358898943540674, 4.47213595499958, 4.58257569495584, 4.69041575982343, 4.795831523312719, 4.898979485566356, 5.0, 5.0990195135927845, 5.196152422706632, 5.291502622129181, 5.385164807134504, 5.477225575051661, 5.567764362830022, 5.656854249492381, 5.744562646538029, 5.830951894845301, 5.916079783099616, 6.0, 6.082762530298219, 6.164414002968977, 6.244997998398398, 6.324555320336758, 6.4031242374328485, 6.48074069840786, 6.557438524302, 6.6332495807108, 6.708203932499369, 6.782329983125268, 6.855654600401044, 6.928203230275509, 7.0, 7.0710678118654755, 7.14142842854285, 7.211102550927978, 7.280109889280518, 7.3484692283495345, 7.416198487095663, 7.483314773547883, 7.54983443527075, 7.615773105863909, 7.681145747868608, 7.745966692414834, 7.810249675906654, 7.874007874011811, 7.937253933193772, 8.0, 8.06225774829855, 8.12403840463596, 8.18535277187245, 8.246211251235321, 8.306623862918075, 8.366600265340756, 8.426149773176359, 8.48528137423857, 8.54400374531753, 8.602325267042627, 8.660254037844387, 8.717797887081348, 8.774964387392123, 8.831760866327848, 8.888194417315589, 8.94427190999916, 9.0, 9.055385138137417, 9.1104335791443, 9.16515138991168, 9.219544457292887, 9.273618495495704, 9.327379053088816, 9.38083151964686, 9.433981132056603, 9.486832980505138, 9.539392014169456, 9.591663046625438, 9.643650760992955, 9.695359714832659, 9.746794344808963, 9.797958971132712, 9.848857801796104, 9.899494936611665, 9.9498743710662, 10.0]
I only want to print perfect squares. What do I need to add to code?
how about this?:
[num for num in l if num == int(num)]
since simple list comprehension looks ugly we can define utility function like
import math
def is_perfect_square(number):
square_root = math.sqrt(number)
square_root_floor = int(square_root)
return square_root_floor * square_root_floor == number
then using built-in filter function like
perfect_squares = filter(is_perfect_square, range(101))
on Python 2 perfect_squares will be a list of desired objects,
on Python 3 filter returns iterator and we need to convert it to list manually:
perfect_squares = list(filter(is_perfect_square, range(101)))
finally:
>>> perfect_squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
True
add a condition to the list comprehension, to make a one liner (without creating the list first, and then checking it)
l = [x for x in range(101) if int(x**0.5) == x**0.5]
This will also do the trick:
[x**0.5 for x in range(101) if x**0.5 % 1 == 0]
Output I wanted to get was [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
and I specifically wanted to do it using Lambda Function. I was going through old posts to improve and saw that best answer is suggested by #Holle van though I didn't like this int(x**0.5) == x**0.5 part so combining few answers I came up with a new solution.
>>> [x for x in range(101) if x**0.5 % 1 == 0]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Given a list of numbers, I am trying to write a code that finds the difference between consecutive elements. For instance, A = [1, 10, 100, 50, 40] so the output of the function should be [0, 9, 90, 50, 10]. Here is what I have so far trying to use recursion:
def deviation(A):
if len(A) < 2:
return
else:
return [abs(A[0]-A[1])] + [deviation(A[1: ])]
The output I get, however, (using the above example of A as the input) is [9, [90, [50, [10, None]]]]. How do I properly format my brackets? (I've tried guessing and checking but I this is the closest I have gotten) And how do I write this where it subtracts the current element from the previous element without getting an index error for the first element? I still want the first element of the output list to be zero but I do not know how to go about this using recursion and for some reason that seems the best route to me.
You can do:
[y-x for x, y in zip(A[:-1], A[1:])]
>>> A = [1, 10, 100, 50, 40]
>>> [y-x for x, y in zip(A[:-1], A[1:])]
[9, 90, -50, -10]
Note that the difference will be negative if the right side is smaller, you can easily fix this (If you consider this wrong), I'll leave the solution for you.
Explanation:
The best explanation you can get is simply printing each part of the list comprehension.
A[:-1] returns the list without the last element: [1, 10, 100, 50]
A[1:] returns the list without the first element: [10, 100, 50, 40]
zip(A[:-1], A[1:]) returns [(1, 10), (10, 100), (100, 50), (50, 40)]
The last step is simply returning the difference in each tuple.
The simplest (laziest) solution is to use the numpy function diff:
>>> A = [1, 10, 100, 50, 40]
>>> np.diff(A)
array([ 9, 90, -50, -10])
If you want the absolute value of the differences (as you've implied by your question), then take the absolute value of the array.
[abs(j-A[i+1]) for i,j in enumerate(A[:-1])]
You can do a list comprehension:
>>> A = [1, 10, 100, 50, 40]
>>> l=[A[0]]+A
>>> [abs(l[i-1]-l[i]) for i in range(1,len(l))]
[0, 9, 90, 50, 10]
For a longer recursive solution more in line with your original approach:
def deviation(A) :
if len(A) < 2 :
return []
else :
return [abs(A[0]-A[1])] + deviation(A[1:])
Your bracket issue is with your recursive call. Since you have your [deviation(a[1: ])] in its own [] brackets, with every recursive call you're going to be creating a new list, resulting in your many lists within lists.
In order to fix the None issue, just change your base case to an empty list []. Now your function will add 'nothing' to the end of your recursively made list, as opposed to the inherent None that comes with a blank return'
Actually recursion is an overkill:
def deviation(A):
yield 0
for i in range(len(A) - 1):
yield abs(A[i+1] - A[i])
Example:
>>> A = [3, 5, 2]
>>> list(deviation(A))
[0, 2, 3]
EDIT: Yet, another, even simplier and more efficient solution would be this:
def deviation(A):
prev = A[0]
for el in A:
yield abs(el - prev)
prev = el