How to do slicing and use any() in python? - python

I am trying to find the numbers smaller than the number(here i) towards the right of a list
If here 1,2,3,4 for any number there is no number towards its right which is smaller than that.I want to implement with any() and slicing.
But when I did that in python with the following code I am getting True but it should be False where am I missing the logic? and why is the output as True?
num=[1,2,3,4]
for i in range(1,len(num)-1):
print (any(num[i+1:])<num[i])
Output:
True
True

You need to check what's actually happening here. You have:
any(num[i+1:]) < num[i]
any returns true if any of the elements of the list equivalent to true. Since all your numbers are non-zero, they are all equivalent to true. Then the right side compares to True to num[i], so you have True < 2 and True < 3. Since True is equivalent to 1 these both result in 1.
You probably want something like:
print( any(x < num[i] for x in num[i+1:]))

The any function should take a sequence of booleans, usually given by a generator expression. The reason your code outputs True is because num[i+1:] is a list of non-zero ints, which are considered "truthy", so the answer to "are any of them true?" is "yes".
You can write something like this:
num = [1,2,3,4]
for i in range(1, len(num) - 1):
print(any( x < num[i] for x in num[i+1:] ))
Output:
False
False

Related

Explain this if-else condition in Python

Code
def addition(num):
if num:
return num + addition(num - 1)
else:
return 0
res = addition(10)
print(res)
Explanation
I know what the function is doing:
it is a recursive function
I just don't know what if num: means or the else part.
I am guessing it means as long as the num is int do what is inside the if, else return 0.
Question
Can someone tell me what this code means?
if variable: and truthyiness
See the boolean values and Python's Truth Value Testing:
What is Truthy and Falsy? How is it different from True and False?
You can evaluate truthy and falsy values using the bool() conversion-function:
print('None:', bool(None))
print('zero:', bool(0))
print('negative:', bool(-1))
print('positive:', bool(1))
if num: mets if num is defined and unequal to 0:
is defined: num is not None
and is not zero: num != 0
bool(0) is False. The opposite condition is tested by if not num.
The role of if in a recursive function
It's a recursive function which calls itself until exit-condition num == 0 is met in the else branch. Then it simply returns 0. So, the role of if num: is the continue-condition opposed to an exit-condition.
You could also write it as exit-condition:
def addition(num):
if not num: # equivalent to: if num == 0 or num is None
return 0 # return 0 if exit-condition met
# default behavior: recurse until zero met
return num + addition(num - 1)
See also:
recursive factorial function
Basics of recursion in Python
Edge-cases for input
Note, how input of None and other falsy values return a zero.
Please also consider the edge-case of negative input, as Fred commented. Could (silently) return 0 to abort addition. Also might raise an error to warn about misuse, like:
if num < 0:
raise ValueError("Can not calculate the recursive-sum for negative values.")
What happens if a float like 10.5 is given as input?
It would step through each -1 decrease until 0.5. The next call of addition(-0.5) would jump over the num == 0 exit-condition and cause infinite recursion, even a stackoverflow.
Python and many other languages have a concept of "falsy", which roughly means "values that are treated as False when evaluated as a boolean". In Python, values that are falsy include empty collections such as empty lists, strings, sets, tuples, and dicts, the int or float 0, and None. I may be missing some here, and you may find that some classes are designed to be treated as falsy as well under certain conditions. There are also "truthy" values which evaluate to True is a boolean context. It's easy to find out if a value is truthy or falsy. Simply call bool() on it:
bool(0.0)
# False
In the context of your code, when 0 is reached, that will be evaluated as falsy, triggering the exit condition.
if num: means if num is different than 0 : if num!=0.
you better remove the else statement.
def addition(num): if num: return num + addition(num - 1) return 0
python already knows that return is an else statement.
here's a playlist of one of the bests on youtube by corey to learn & become at python : https://www.youtube.com/watch?v=YYXdXT2l-Gg&list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7
and also I recommend this book, automating the boring stuff with python. it's free : https://automatetheboringstuff.com/

Why can you not factor out the LCM variable in the code for conditional statement?

Having trouble understanding Boolean expression for factoring out 0.
x,y=24,36
LCM=1
counting=True
while counting:
if (LCM%x and LCM%y) == 0:
print('The LCM is {}'.format(LCM))
break
LCM+=1
LCM evaluates to 24, which is false
But this code gives the correct LCM:
x,y=24,36
LCM=1
counting=True
while counting:
if LCM%x==0 and LCM%y == 0:
print('The LCM is {}'.format(LCM))
break
LCM+=1
LCM is 72, this is correct
Now why can 0 not be factored out? Generally if I type something like 2 and 3 == 0, the expression evaluates to false, but shouldn't syntax work similarly in the example above. So I getting confused.
In python, 0 == False evaluates to True. So (LCM%x and LCM%y) == 0 evaluates to True when the condition (LCM%x and LCM%y) is False. When does that happen? Whenever either of the values LCM%x or LCM%y is zero.
In your second example, you have LCM%x==0 and LCM%y == 0 which evaluates to True only if both LCM%x and LCM%y are zero.
Because here' it's happening like a binary operation and not as a logical check statement
(0 and 1) = 0 when LCM = 24
if (LCM%x and LCM%y) == 0:
This is happening because the values are 0 and 1 here(Python mistook it for a binary operation but you wanted something else).
If it is like (24 and 36) then it would return the max of two! So be careful when you give conditions to Python/any language!
But here it is the value check like is LCM divisible by x like
if LCM%x==0 and LCM%y == 0:
is 24%24 == 0? and is 36%24 ==0 ?
PS : Use the default Python IDLE, it will give you a clearer view in such simple operations!

Python, check whether array elements are all same or not

I have an array, say [4 4 4 4 4], here the length is 5. In real case it could be 300. How to check whether all the elements are same, say in this case all are 4. If all elements have same value, the function return true, otherwise false. The element could be only interger and value could be either one of them: 0,1,2,3,4.
I could use a loop in Python as follows. But I am looking for a concise way or simple way to do that, say one line.
x= [4,4,4,4]
temp = x[0]
for ele in x:
if(temp != ele):
false
true
You can put elements into set() and then check if length of the set is equal to 1:
if len(set(x)) == 1:
print('All elements are same')
else:
print('Not same')
it might be more efficient not to iterate over the full list (as does the set constructor) but to stop at the first element that does not equal x0. all does that for you:
x = [4,4,4,4]
x0 = x[0]
print(all(item == x0 for item in x))
# True
this is basically the same version you had; only the loop will be much more efficient this way.
also note that true and false are not valid python identifiers. in python it is True and False.

Python any() function does not act as expected for list of negative numbers

I am trying to compare a list of numbers in an if statement with the any() function. I am using python 3.6 in Spyder. The code in question is:
if any(lst) >= 1:
do_some_stuff
lst is actually generated by list(map(my_func, other_lst)) but after diagnosing my problem I get two behaviors as shown below with my actual lst passed to the any() function:
any([1.535, 1.535, 1.535]) >= 1
>>True
Which is expected.
any([-0.676, -0.676, -0.676]) >= 1
>>True
Which is not expected.
I've delved deeper and found that any number I can put in lst that is less than 0 yields True in my if statement. Also, converting the 1 to a float doesn't help. After reading "truth value testing", this post, and extensive time trying to learn the behavior within my program, I am at a loss. Please help, I am pretty new to python. Thanks!
You are comparing the wrong thing. You are comparing the result of any to 1.
any(mylist) will return true if any element of the list is nonzero. True is greater than or equal to 1.
So this
any(mylist)>=1
is equivalent to just
any(mylist)
What you mean is
any(x>=1 for x in mylist)
Please read the documentation:
any(iterable)
Return True if any element of the iterable is true. If
the iterable is empty, return False. Equivalent to:
def any(iterable):
for element in iterable:
if element:
return True
return False
All your any() expression listed will return True, and you are comparing True with 1, that is True.

If shorten, python recursion

i try to write a short golf code without using letters "eiou" and i found that (a,b)[conditions] is equal to if statement, but i have no idea why it doesn't work.
a_factaral=lambda x:(a_factaral(x-1)*x,1)[x==0]
Please for some tips
bool is a subclass of int. False is 0 and True is 1.
>>> True+True
2
Logical predicates like x==0 return a boolean value.
>>> x=0
>>> x==0
True
The logical predicate can act as an index of 0 or 1. If the predicate is False, the index is 0. Otherwise, it's 1.
>>> (1, 2)[x!=0]
1
>>> (1, 2)[x==0]
2
Your function returns a_factaral(x-1)*x if x is anything other than 0, or 1 when x has reached 0 (the stopping point for the recursion).
You could ungolf this as follows:
def a_factaral(num):
if num == 0:
return 1
else:
return a_factaral(num-1) * num
(a_factaral(x-1)*x,1)[x==0] will calculate the first value first, then decide which value to take out depends on the result of x==0.
a_factaral=lambda x:((x!=0 and a_factaral(x-1)*x) or 1) will work for the same function. But in the case you cannot use 'eiou', I have no idea for alternative solution.

Categories

Resources