I need help for this task. I have to write:
two assignment statements that respectively assigns to the variable SQUARE the lambda term that squares the argument , and assigns to the variable ODD the lambda term that tests if its argument is an odd number.
A python lambda function looks like the following:
double = lambda x: x*2
It is a quick way to write a one-line function and is just shorthand for:
def double(x):
return x*2
Google "python lambda" and you will find tutorials and more examples.
From what I understood I came up with the following code.Hope it helps
numbers = range(5) ## few range of numbers
for i in numbers:
square = lambda x: x*x ## returns the square of each value in numbers
print square(i) ## prints the square of each value in numbers
for j in numbers:
odd = lambda y: y%2 !=0 ## checks if odd or even
print odd(j) ## print True if divisible (meaning its even number) or False (meaning its odd)
Related
I recently had an idea of doing sigma(Σ) using python
So, I wrote this code.
def sigma(i,target,condition='i'):
if condition=='i':
a=0
for f in range(i,target+1): #the loop sums all the numbers from i to the target given
a+=f
print(a)
'''if user enters a condition than,
every number will follow condition and then be added to each other'''
else:
lis=list()
condition for i in range(i,target+1):
lis.append(i)
print(sum(lis))
but the code I wrote above just gives me a wrong output as it takes the variable condition as type 'string'.
The problem is actully to take the argument condition not as a string
for example, let's say user entered:
sigma(1,100,condition='i'*2)
so the code should run for loop like this:
i*2 for i in range(i, target+1)
but it runs like this:
'ii' for i in range(i, target+1)
For what I can understand, you should pass an anonymous function as argument to accomplish what you are looking for.
Consider that this is not a valid syntax: i*2 for i in range(i, target+1), so I consider it as a pseudo code explained by your comment.
You should change your method in this way:
def sigma(i, target, condition='i'):
if condition=='i':
a=0
for f in range(i,target+1):
a+=f
print(a)
else:
lis=list()
for i in range(i, target+1):
lis.append(i)
print(condition(sum(lis)))
So that if you call sigma(1,100,'i') #=> 5050 you fall in the true part of the statement.
For the false part of the statement you need to call the method passing a lambda expression as parameter:
sigma(1,100, lambda i: 2*i) #=> 10100
It happens that the argument condition when passed as lambda works as if it was defined as:
def condition(i):
return 2 * i
I would like to point out that the sum of the first n natural numbers is given by a math formula, so you don't need a loop:
n * (n + 1) // 2
Also should be better to return a value than to print.
I'd rewrite the method:
def sigma_2(i, target, condition=None):
sum_i_to_target = (target*(target+1)-(i-1)*i)//2
if condition is not None:
return condition(sum_i_to_target)
else: # need to check that condition is a lambda function
return sum_i_to_target
So call this way:
sigma_2(2, 20) #=> 209
sigma_2(2, 20, lambda i: 2*i) #=> 418
You've initialized i from what I can see from your code as a string.
If you would like for the compiler to read it as int then initialize i as int.
For example:
i=1
Write a lambda function called factorials_1_to_n that computes the factorials of the numbers from 1 to n. Hint: Use the function factorial you already created.
The only thing I can think of doing is writing a for loop within the lambda function like.... for i in range(1,len(n)+1): factorial(i)…. but for loops are not allowed within a lambda function.
def factorial(n):
product=n
while n!=1:
product=product*(n-1)
n=n-1
return(product)
y=factorial(4)
print(y)
factorials_1_to_n = lambda n: ????????
y=factorials_1_to_n(4)
print(y)
I assume that a list is an acceptable result type
factorials_1_to_n = lambda n: [factorial(i+1) for i in range(n)]
The i+1 is used to calculate it from 1 to n, instead of from 0 to n-1.
See list comprehension in python
I'm trying to get the minimum odd number using python. I used lambda, loops and other methods to get minimum odd number but i was not able to get that using functions. here is my code
z= [1,8,-4,-9]
def min_odd(x):
for i in x:
if (i%2!=0):
return min(i)
y = min_odd(z)
print (y)
Can some please tell me what i was missing here.
The min() function expects an iterable like a list which it will then yield the smallest element from.
E.g. min([1,0,3]) gives 0.
So if you want to use it, you must create a list (or other iterable) of the odd numbers that you can then pass into it:
def min_odd(x):
odds = []
for i in x:
if i % 2 != 0:
odds.append(i)
return min(odds)
note that we could also use a list-comprehension:
def min_odd(x):
return min([i for i in x if i % 2 != 0])
which both work.
An alternative method would be to store the current minimum odd value in a variable and update this variable if we come across a smaller odd value:
def min_odd(x):
min_v = float('inf')
for i in x:
if i % 2 != 0 and i < min_v:
min_v = i
return min_v
Try:
min([val for val in z if val % 2 != 0])
It seems your code logics are wrong. First off, you seem to have an indentation error in the return statement. Second off, the min() function requires a collection of items (like an array for example) or a series of arguments to determine the minimum in that series. You can try multiple things.
Use another variable to store a temporary minimum. Replace it every time you find a smaller odd value ( for every i in x... if the value is odd and is smaller than the previous odd value, replace it) and have it started with the first odd number you can find.
Take all the odd numbers and add them to another array on which you will apply the min function.
Hope this proves useful!
You could pass a generator into the min() function:
def min_odd(iterable):
return min(i for i in iterable if i % 2)
I didn't write i % 2 != 0 because any odd number will return 1 which has a Boolean value of True.
I added a parameter to the function that takes the iterable so it can be used for any iterable passed in.
min operates on an iterable. i is not an iterable in your code; it's the last element of the list.
You can achieve what you want with a filter, though:
min(filter(lambda e: e%2 != 0, x))
def largestNumber(self, num):
num = [str(x) for x in num]
num.sort(cmp=lambda x, y: cmp(y+x, x+y))
return ''.join(num).lstrip('0') or '0'
What I would like to know is what is exactly is happening in the num.sort line where the lambda function takes in an x and y and does this cmp() function. This is the specific question that the code is being used for if anyone wants to see this as well https://leetcode.com/problems/largest-number/#/description
I'd recommend you to use Visualize python with the following code:
class Solution:
def largestNumber(self, num):
num = [str(x) for x in num]
num.sort(cmp=lambda x, y: cmp(y+x, x+y))
return ''.join(num).lstrip('0') or '0'
print Solution().largestNumber([4,6,2,7,8,2,4,10])
To get the concept clear,
num = [str(x) for x in num]
This takes every element of list num as x and converts it to a string and the result list is stored as num
num.sort(cmp=lambda x, y: cmp(y+x, x+y))
cmp:
cmp(x, y)¶
Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and
strictly positive if x > y.
Lambda Expression:
Small anonymous functions can be created with the lambda keyword. This
function returns the sum of its two arguments: lambda a, b: a+b.
Hope this helps!
Yes, the lambda function does exactly the comparisons you suggest: "998" to "989", etc. This way, the list items are sorted into lexicographic order, largest first. You have to worry about the concatenated combinations to get the proper order for largest numbers: '9' vs '98' is a typical example of why you need concatenation, as you want "998" in the result.
I'm trying to create a program which checks if the number is a prime number. My idea was to use the function that the square root of the number, divided by all numbers up to the square root defines if the number is a prime or not. (I hope you understand)
Anyway, I'm trying to find a way to use modulus on every character in my list. As an example
Prime % List(2,sqrtPrime) =/ 0 #I know this doesnt work, just a hint how i want it to work.
As the error if I run this is that I cant use modulus on a list, so how do i do it?
And also, will this idea go through every character from 2-sqrtPrime?
Thanks
What seems the optimal way to me, would look like:
rng = xrange(2, int(math.sqrt(n)) + 1)
is_prime = all(n % i for i in rng)
Main points are:
rng is a generator, not a list
expression within (...) is a generator as well, so no unnecessary intermediate lists are created
all will stop iterating as soon as the first divisor is found, thus no extra iterations
You could write a function that returns True if its argument is Prime and otherwise False, then run filter on the list.
import math
def isPrime(x):
for factor in range(2,math.floor(x**0.5)+1):
if x % factor == 0:
# x divides evenly, so
return False
return True
lst = [some, numbers, go, here]
primes_in_lst = filter(isPrime, lst)
Or if you're against filter as a rule (some people contend it's unpythonic) then you can put it in a list comp.
primes_in_lst = [num for num in lst if isPrime(num)] # exactly equivalent
and technically that isPrime function could be a lambda:
primes_in_lst = filter(lambda x: all(x%factor for factor in range(2,math.floor(x**0.5)+1)), lst)
But jeebus that's ugly.