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.
Related
This is the task:
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements
What is wrong with this code? Why is it not keeping boolean values while iterating through the list and removing zeros? Is it because False is equal to 0?
move_zeros([False,1,2,0,1,0,1,0,3,0,1])
def move_zeros(array):
count=0
for num in array:
if num == 0:
count +=1
array.remove(0)
return array +[0]*count
Yes, False == 0 will evaluate to True in Python which is why False values are being removed from your array.
In Python, True and False are implemented as singletons, meaning all False values point to the same instance. Therefore, you can use the is operator to check if a value is exactly equal to this singleton.
False is 0 will return False, while False == 0 will return True.
x = len(lis)
y = []
for i in range(len(lis)):
if lis[i]!=0:
y.append(lis[i])
if len(y)!=len(lis):
z = len(lis)-len(y)
for i in range(z):
y.append(0)
Seems like its a homework problem. Happy to help tho.
Edit: use print(y) and you'll get what you want
Yes, indeed False == 0. Actually, bool is a subtype of int. If you want to strictly compare if False is equal to 0, then another comparison should be added to the if statement.
Also, do not modify a list while you are iterating over itself. Create a new one instead.
def move_zeros(list_):
result = []
zeros = 0
for item in list_:
if item == 0 and type(item) == int:
zeros += 1
continue
result.append(item)
return result + [0] * zeros
Yes 0 evaluates to False and 1 evaluates to True, use this
def move_zeros(obj):
new_list = []
zeros_list = []
for item in obj:
if item != 0 or is False:
new_list.append(item)
else:
zeros_list.append(item)
new_list.extend(zero_list)
return new_list
This adds all non 0 to one list and all 0's to another, then returns the new_list after iterating over the zeros_list and adding them to the end of the new_list
There are 2 issues in your code:
You directly changed the list over which you iterate — it is always dangerous.
Other answers explained to you why False == 0 is True.
I made as few changes in your code as it was possible to fix these issues:
I created a new, empty array, and instead of removing “bad” elements from the original list, I appended the “good” ones to that new array.
I tested a current element for its type, too.
def move_zeros(array):
count=0
new_array = []
for num in array:
if num == 0 and type(num) is int:
count +=1
else:
new_array.append(num)
return new_array + [0]*count
Test:
move_zeros([False,1,2,0,1,0,1,0,3,0,1])
[False, 1, 2, 1, 1, 3, 1, 0, 0, 0, 0]
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
This question already has answers here:
Pythonic way of checking if a condition holds for any element of a list
(3 answers)
Closed 4 months ago.
Suppose I have n values in a list x = [1.2, -0.4, 3.5, ....]
I need to check if at least one of them is below zero.
So basically, if I had only two values, I'd have written
if x[0]< 0 or x[1] < 0
But now, I need to use the same or operator within a loop so as to check each one of the values in the list.
The command any(x) < 0 seems to return False every single time.
How would I have to go about it?
any is not vectorized. You'd have to apply it on each object in x:
any(n < 0 for n in x)
n < 0 for n in x creates a generator that yields one value at a time from x, and is quite efficient since it is short-circuited, meaning it will break (and return True) as soon as it finds the first n that is < 0.
You can also use numpy for vectorized operations
import numpy as np
x = np.array([1.2, -0.4, 3.5,0])
x<=0 # will return the array of boolean values
If you just need to check if the condition met or not then
any(x<=0) # will return true if array contains atleast one True
When using any() or all() the pc will check if the elements in the iterableare True or False. Thus, you need to add a list comprehension to create the iterable:
any([elt < 0 for elt in x])
Basically you need to do the following:
any(value < 0 for value in X)
You can find a detailed explanation here
I have a really basic if/else logic question for Python. An exercise in the book required me to write a function that takes a list of integers are returns True if the list contains all even numbers and False if it doesn't.
I wrote:
list1 = [8,0,-2,4,-6,10]
list2 = [8,0,-1,4,-6,10]
def allEven(list):
for x in list:
if x % 2 != 0:
return False
else:
return True
This code always returns True. Why is that? Doesn't the code see the -1 during the loop of all the values of the list and returns the False?
list1 = [8,0,-2,4,-6,10]
list2 = [8,0,-1,4,-6,10]
def allEven(list):
for x in list:
if x % 2 != 0:
return False
return True
The book gives the answer of this. Why does this work and mine doesn't?
Pay close attention to where that else is placed. Indentation and nesting matters here!
In your first example, it will return True on the first element that satisfies your condition because your first if check fails.
In your second example, it will return True after all elements have been iterated through and a return value hasn't been produced.
The first function checks the first number only, since it returns something as soon as the for loop starts.
By the way, you can but should not use list as an argument or a variable name, since it is a keyword.
I strongly recommend writing a print statement to output x before both of your return statements. It will help you understand the flow of the code.
The short answer is that only the first element is being checked by your code, and the function returns True or False based on that value.
In the book solution, any failure causes a return of False, but the loop simply continues otherwise. Only if all elements are checked without failure does the return True reached.
I'm a beginner in Python programming and I'm having some trouble with some list stuff.
So I want to write a function that returns a boolean value. The function will inform the user whether there is a duplicate consecutive pair of elements in the list he or she entered. By the way, I want to do this using only len(), range(), loops, if-statements, variables and arithmetic (no built in functions).
For example:
contains_consecutive_duplicates([1,3,3]) should return True
contains_consecutive_duplicates([3,2,3]) should return False
My code:
def contains_consecutive_duplicates(xs):
for i in xs:
if xs[i] == xs[i-1] or xs[i] == xs[i+1]:
return True
else:
return False
My logic to this was as follows: Each time the for loop would run, i would refer to some element in the list. If that element was such that the element before it or after it was equal to it, then the for loop would return true. If not, keep searching. If there are none, it would return false.
Now, I actually understand where the error is (I think). The problem is that I don't know how to solve it. I think the for loop is running into a problem at the beginning (when i is reffering to the 0th element). There is no element before the 0th element, hence the error:
"index out of range"
P.S: Is that how you return a boolean value?
Is there a better way to do this?
I would appreciate any help given! Thanks in advance!
#roeland pointed out the problem with assuming iterating the list directly would get you indices (if you want index and value, use enumerate). But in this case you don't actually need the index.
For the simple case (where it's known to be a container you can slice), you can just iterate with zip over offset slices:
def contains_consecutive_duplicates(xs):
return any(x == y for x, y in zip(xs, xs[1:]))
More general solutions can be made with itertools.groupby to handle the case where you can't slice, but this is simple and involves no imports.
Use of any in this case is just a short hand to slurp the generator expression and return True if any values are truthy. The long equivalent form is:
def contains_consecutive_duplicates(xs):
for x1, x2 in zip(xs, xs[1:]):
if x1 == x2:
return True
return False
Since your teacher apparently thinks built-ins are bad, but len and range aren't built-ins (they are), you can do this the dumb way:
def contains_consecutive_duplicates(xs):
for i in range(len(xs) - 1):
if xs[i] == xs[i+1]:
return True
return False
Which does the same work as ziping, just less efficiently (generating index integers and explicitly indexing is surprisingly expensive in Python relative to native iteration).
This should do:
>>> def contains_consecutive_duplicates(xs):
... for i, v in enumerate(xs[:-1]):
... if v == xs[i+1]:
... return True
... else:
... pass
... return False
>>> l1 = [1,3,3]
>>> l2 = [1,3,2]
>>> l3 = []
>>> l4 = [2]
>>> contains_consecutive_duplicates(l1)
True
>>> contains_consecutive_duplicates(l2)
False
>>> contains_consecutive_duplicates(l3)
False
>>> contains_consecutive_duplicates(l4)
False
>>>
By using only range, for and if statements, this can be done with:
def contains_consequtive_duplicates(xs):
for i in range(len(xs)-1):
if xs[i] == xs[i+1]: return True
return False
You access lists with their index and not by their value (which you are by using for i in list). Additionally, if you perform the check xs[i] == xs[i-1] this will not yield the result you want since x[-1] will check the end of the list so [3, 2, 3] will return True.
As a small demonstration:
if contains_consequtive_duplicates([1,3,3]): print "consecutive"
# Prints Consequtive
if contains_consequtive_duplicates([3, 2, 3]): print "consecutive"
# Prints nothing
Try this:
def contains_consecutive_duplicates(xs):
for i in xs:
if xs.indexOf(i)==len(xs):
break
if xs[i] == xs[i-1] or xs[i] == xs[i+1]:
return True
else:
return False
What you are doing is trying to do is evaluate xs[i+1], but that does not exist.
This should do the trick:
def contains_consecutive_duplicates(xs):
for i in range(1, len(xs) - 1):
if xs[i] == xs[i-1] or xs[i] == xs[i+1]:
return True
return False
It iterates through all values bar the first and last (created by the range function), returning (which ends the loop) if it finds a duplicate.
If it reaches the end and hasn't found a duplicate one must not exist, so it returns False.