How to check if elements of a list are alternating? - python

I have lists like this, and I want to know if their elements are alternating. For example:
list1 = ['A', 'C', 'A', 'C', 'A', 'C'] # result = True
list2 = ['A', 'A', 'A', 'C', 'A', 'C'] # result = False
list3 = ['A', 'C', 'C', 'C', 'A', 'C'] # result = False
list4 = ['A', 'C', 'A', 'C', 'A', 'A'] # result = False
Elements of the list will always be a string.
The length of this string is not fixed.
The list will always contain only two distinct values.
Now, How to check if elements of list are alternating in Python?

Try this Code:
a = ['A','C','A','C','A','C']
print((len(set(a[::2])) == 1) and (len(set(a[1::2])) == 1))
Example:
lists = [
['A','C','A','C','A','C'],
['A','A','A','C','A','C'],
['A','C','C','C','A','C'],
['A','C','A','C','A','A']
]
for i in lists:
print((len(set(i[::2])) == 1) and (len(set(i[1::2])) == 1))
Edit: based on Daniel Hao's commments:
for sub in lists:
print(all(x!= y for x, y in zip(sub, sub[1:])))
Output:
True
False
False
False
Tell me if its not working...

Related

Iterate and combine iteratively elements in a list

I have a list:
li = ['a','b','c','d']
I want to iterate and combine iteratively the elements in the list such as the first one is combined to the 2nd one and go on.
The final output I want is:
['a'],['a','b'],['a','b','c'],['a','b','c','d']
I tried using this way:
for i in range(0, len(li),i):
output = li[:i+i]
print(output)
But I am getting only this result:
[]
['a', 'b', 'c', 'd']
Any idea where I am wrong and how to do this properly?
You could modify the start and stop arguments in your use of range:
li = ['a', 'b', 'c', 'd']
for i in range(1, len(li) + 1):
output = li[:i]
print(output)
Output:
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
Your range values are incorrect, and i is undefined. This is a much simpler loop:
li = ['a','b','c','d']
for i in range(len(li)):
output = li[:i+1]
print(i, output)
Output:
0 ['a']
1 ['a', 'b']
2 ['a', 'b', 'c']
3 ['a', 'b', 'c', 'd']

how to match value of 1st list with the indexes of 2nd list in python

I am trying to match the value of 1st list with the indexes of 2nd list and if value and indexes match then in the result it will produce matches of the index value.
A = [0,2,0,5,2,1,1] # value of list 1
B = ['A', 'B', 'C', 'D'] # value of 2nd list
the result should be,
res = ['A', 'C', 'A', 'C', 'B', 'B']
Try the code below,
A = [0, 2, 0, 5, 2, 1, 1] # values of list 1
B = ['A', 'B', 'C', 'D'] # values of list 2
res = [B[i] for i in A if i<len(B)]
res
Output
['A', 'C', 'A', 'C', 'B', 'B']
A = [0,2,0,5,2,1,1] # value of list 1
B = ["A", "B", "C", "D"] # value of 2nd list
new_list = []
for val in A:
if val < len(B) - 1:
new_list.append(B[val])
print(new_list)
Results:
['A', 'C', 'A', 'C', 'B', 'B']
A = [0,2,0,5,2,1,1] # value of list 1
B = ['A', 'B', 'C', 'D']
size_minus_1 = len(B) - 1
result = []
for i in A:
if i < size_minus_1:
result.append(B[i])
print(result)

Iterating over two lists A and B

I am trying to iterate over two lists A and B. Where the B is equal to A - A[i], where i = 1:
For E.g. listA = ['A', 'B', 'C', 'D'].
For first Item, 'A' in List A, I
want the List B to have ['B', 'C', 'D'] For second Item 'B' in List A,
I want the List B to have ['A', 'C', 'D']
What I have tried until now.
listA = ['A', 'B', 'C', 'D']
for term in listA:
listA.remove(term)
for item in listA:
print(listA)
If all you want is to print the sublists, it will be like:
for i in range(len(listA)):
print(listA[:i]+listA[i+1:])
Or,
for i in listA:
print(list(set(listA) - set(i)))
Try this,
>>> la = ['A', 'B', 'C', 'D']
>>> for i in la:
_temp = la.copy()
_temp.remove(i)
print(_temp)
Output:
['B', 'C', 'D']
['A', 'C', 'D']
['A', 'B', 'D']
['A', 'B', 'C']
*If you want to assign the print output to new variables, use a dictionary where the key will the name of list and value is printted output.
Is this what you want?
listA = ['A', 'B', 'C', 'D']
Bs = \
[listA[:idx] + listA[idx + 1:]
for idx
in range(len(listA))]
for B in Bs:
print(B)
Taking the above solutions a step further, you can store a reference to each of the resulting list in the corresponding variable using a dictionary comprehension:
keys_map = {x: [item for item in listA if item != x] for x in listA}
print(keys_map)
Output
{
'A': ['B', 'C', 'D'],
'B': ['A', 'C', 'D'],
'C': ['A', 'B', 'D'],
'D': ['A', 'B', 'C']
}
and access the desired key like so
keys_map.get('A')
# returns
['B', 'C', 'D']

Making dynamically sizing if statements

I want to check the columns of a dataframe inside a for loop by using a list, then perform some operations that change the contents of that list for the next iteration. Is it possible to dynamically size the if statement described here.
Example:
df =
a|b|c|d|e
1|2|3|4|5
6|7|8|9|0
check_list = ['a']
for i in range(10):
if check_list in df.columns:
do x
// variable check_list is now equal to ['a','b']
so in the first iteration the list only contains 'a' and in the second iteration it contains 'a' and 'b' and then in further iterations it will be changed further. I hope this adequately explains my question.
Working code that might help answer your question:
def add_column(l, all_columns):
""" Example of a function for adding new columns to the check list"""
if len(l) < len(all_columns):
return l + [all_columns[len(l)]]
else:
return l
all_columns = 'abcde'
df = pd.DataFrame([[1, 2, 3, 4, 5], [6, 7, 8, 9, 0]], columns=list(all_columns))
print(df)
check_list = ['a']
for i in range(10):
# issuperset() seems to be the best way to check that the list includes only column names from the dataframe
if set(df.columns).issuperset(set(check_list)):
check_list = add_column(check_list, all_columns)
print("checking list:", check_list)
# do other stuff
Output:
a b c d e
0 1 2 3 4 5
1 6 7 8 9 0
checking list: ['a', 'b']
checking list: ['a', 'b', 'c']
checking list: ['a', 'b', 'c', 'd']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
I hope this helps.

Find the same elements from two lists and print the elements from both lists

There are two lists:
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l = ['a', 'c', 'e']
I want to find the same elements from these two lists, that is:
['a', 'c', 'e']
then I want to print out the element we found, for example, 'a' from both lists, that is: ['a', 'a', 'a'].
The result I want is as follows:
['a', 'a', 'a', 'c', 'c', 'c', 'e', 'e']
I try to doing in this way:
c = []
for item_k in k:
for item_j in j:
if item_k== item_j:
c.append(item_k)
c.append(item_j)
However, the result is ['a', 'a', 'c', 'c', 'e', 'e']
Also in this way:
c=[]
for item_k in k:
if item_k in l:
c.append(item_k)
d=l.count(item_k)
c.append(item_k*d)
print c
But it do not works, can anybody tell me how to do it? really appreciate your help in advance
result = [x for x in sorted(k + l) if x in k and x in l]
print(result)
results:
['a', 'a', 'a', 'c', 'c', 'c', 'e', 'e']
Since you want to pick up elements from both lists, the most straight forward way is probably to iterate over both while checking the other one (this is highly optimizatiable if you depend on speed for doing this):
merged = []
for el in list1:
if el in list2:
merged.append(el)
for el in list2:
if el in list1:
merged.append(el)
.. if the order of the elements is important, you'll have to define an iteration order (in what order do you look at what element from what array?).
If the lists are sorted and you want the result to be sorted:
sorted([x for x in list1 if x in set(list2)] + [x for x in list2 if x in set(list1)] )
You can use set operations to intersect and then loop through, appending to a new list any that match the intersected list
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l = ['a', 'c', 'e']
common_list = list(set(k).intersection(set(l)))
all_results = []
for item in k:
if item in common_list:
all_results.append(item)
for item in l:
if item in common_list:
all_results.append(item)
print sorted(all_results)
output:
['a', 'a', 'a', 'c', 'c', 'c', 'e', 'e']
Here's a compact way. Readability might suffer a little, but what fun are comprehensions without a little deciphering?
import itertools
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l = ['a', 'c', 'e']
combined = [letter for letter in itertools.chain(k,l) if letter in l and letter in k]
Here is an implementation that matches your initial algorithm:
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l=['a', 'c', 'e']
c=[]
for x in l:
count = 0
for y in k:
if x == y:
count += 1
while count>=0:
c.append(x)
count = count -1
print c

Categories

Resources