Check the duplicate element in an array using set in python - python

Scan and check the numbers in an array if it is repeated, if true print yes, else print no
So what I'm trying to do is convert them into a set (and list)
a = [int(v) for v in input().split()]
b = set(a)
and check if the occurrence of an element in list a is equal to that is set b, but currently, there's no such function to count the occurrence in set b, isn't it? I'm dumb so pls help
for i in range(len(a)):
if a.count(a[i]) == ..occurrence in set b..:
print("NO")
else:
print("YES")
example input:
1 2 3 2 3 4
output:
NO
NO
NO
YES
YES
NO

Given the problem description you need a code that identifies if an item of a list appears in it more than once. Here's one way you can do it,
from collections import Counter
# Input list with duplicates
numbers = [1, 2, 3, 2, 3, 4]
# Count of each list element
counted_numbers = Counter(numbers)
# Chech occurrence of each list element
for el in numbers:
if counted_numbers[el] > 1:
print('YES')
else:
print('NO')
The code uses Counter to create a dictionary with number of occurrences of each list element. In other words, counted_numbers are a dictionary where the keys are unique elements of the list numbers and the values are the number of times they appear in the list.
The second part of the code loops through the original list and checks how many times it appears as reported by Counter. If its more than one, it prints YES.
Temporary note: the output is different than in your example, let me know if this is not what you're looking for.

I think this is what you're looking for:
for i in range(len(a)):
if a[i] in a[:i]:
print("YES")
else:
print("NO")
If the number at index is appeared on the left hand side of the current index, it is printed YES, otherwise NO.

count = set()
for num in nums:
if num in count:
print("YES")
else:
print("NO")
count.add(num)

Related

How to count numbers less than a given number including duplicates

I have a task to count numbers less than a given number. I understand this for most cases except ones with duplicates. So for example a list [1,2,2,3,4] I want the out put of this to be a count of 2 since it not including the middle one
One way I’ve tried this target is the number is the given number to find the less than to
count=0
for i in list:
if i< target:
count=count+1
return count
I know if I put = it will count both twos how can I fix this with what I have now and it still being a list
I would first remove duplicates like this:
res = []
[res.append(x) for x in list if x not in res]
and then you could get the number of values in the list without duplicates with the len function: len(res) or check each value to make sure it meets criteria before counting like being less then a number:
count = 0
for i in res:
if i < target: count += 1
return count
Although it might be faster to create a list of numbers that are both not duplicates and meet the criteria, and then just take the length of that list:
res = []
[res.append(x) for x in list if x not in res and x < target]
return len(res)
Put all the list items into a set and then count the number of elements less than target:
>>> a_list = [1, 2, 2, 3, 4]
>>> target = 3
>>> sum(i < target for i in set(a_list))
2
You can just change list to a set. That is, loop through a set of the list. This way you will go through each unique element once. See the code below:
count = 0
for element in set(list):
if element < target:
count += 1
print(count)
You can simply use a list comprehension:
target = 3 # can be any other number
len([x for x in set(myList) if x < target])

How to check how many of the last elements in a list are equal in python?

I am appending integers to a list one by one (using a loop) as so:
A.append(x) where x is an integer, which eventually gives for example:
A = [4, 8, 2, 4, 3, 7, 7, 7]
During every loop, i.e. just after each integer is added to the end of the array, I would like to check whether the same integer has been added a certain number of times (say, 3, in the example below) and throw an exception if so.
Pseudo code:
if somewayofcheckingA == 3:
raise Exception("Lots of the latest integers are similar")
I could just do the below, but if I wanted to check for say, 100 repeats, then obviously the code would become a mess.
if A[-1] == A[-2] and A[-2] == A[-3]:
raise Exception("Lots of the latest integers are similar")
Thanks!
Passing a list to set() will return a set with all unique values in the list. You can use slice notation to get a list of the last n values using the following
n = 3
if len(A) >= n and len(set(A[-n:])) == 1:
raise Exception("Lots of the latest integers are similar")
if you just want to check just last 3 then this would do it.
limit = 3
if len(set(A[-limit:])) == 1:
raise Exception("Lots of the latest integers are similar")
You could use collections.Counter() to count how many times the last element appears.
For example:
occurrences = collections.Counter(A)
if occurrences[A[-1]] >= 3:
raise Exception("Lots of the latest integers are similar")
Or an even simpler way
if A.count(A[-1]) >= 3:
raise Exception("Lots of the latest integers are similar")
**THIS CODE CHECK FOR OCCURRENCES OF THE LAST ELEMENT AT ANY OTHER INDEX OF THE LIST
I did this for you. And I think this is some kind of pythonic.
class CustomList(list):
def __init__(self, seq=()):
self.last_equal_items = []
super().__init__(seq)
def append(self, some_item):
if self.last_equal_items and some_item != self.last_equal_items[-1]:
self.last_equal_items = []
self.last_equal_items.append(some_item)
if len(self.last_equal_items) >= 3:
raise ValueError("Last equal items larger that 3")
else:
super(CustomList, self).append(some_item)
test = CustomList([])
test.append(1)
test.append(1)
test.append(1)
test.append(2)
test.append(1)
print(test)
You can just use CustomList like list. And it will alert when you insert the third equal value.
lists = [1,4,3,3];
def somewayofcheckingA(lists, a):
lists.reverse()
i = 0
k = lists[0]
count = 0
while i < a:
if(lists[i] == k):
count= count+1
i = i+1
return count
print(test(lists, 3))
where lists is the list and a is the number of times you want to check
This answer is easy to follow and utilizes basic looping and conditional statements, which I think you should master before venturing into the other proposed solutions, which are more pythonic, but where you might get lost in the mix.

How to find elements in one arbitrary list that occur in another list (preserving their order)?

I need to create an algorithm which would read user input of lists A and B and determine whether elements from list B occur in list A (if they occur, program needs to print 'Yes', and 'No' otherwise').
I have come up with the following code which should can be a starting point:
n=int(input('Enter the length of list A '))
A=[]
for i in range (0,n):
InpEl=int(input('Enter the elements '))
A.append(InpEl)
print(A)
n=int(input('Enter the length of list B '))
B=[]
for i in range (0,n):
InpEl2=int(input('Enter the elements '))
B.append(InpEl2)
print(B)
checklist=B
for each in A:
if each in checklist:
print('YES')
else:
print('NO')
Although in any case, I get 'No'. What is the mistake here?
Also, later I may need to modify the list so the program could determine if elements of B occur in A in the order they appear in B, but not necessarily consecutively.
For example, let M be the length of B and N be the length of A.
Then the program should return yes if there are indices i0, i1...im+1 such that 0<= i0 < i1...< im-1 < N such that A[i0] = B[0];A[i1] = B[1]...A[im-1] =
B[m-1].
Is there a simpler way to build the loop which would satisfy this kind of request?
P.S.: is it possible to make user input read not only integers, but strings? I am not sure if raw_input would be useful in Python 3.5.
P.S.S:
sorry, I made a minor mistake inputting the code here, I fixed it now.
Another question: I get the output of multiple yes' and no's for each element:
Enter the length of list A 3
Enter the elements 1
Enter the elements 2
Enter the elements 3
[1, 2, 3]
Enter the length of list B 3
Enter the elements 5
Enter the elements 4
Enter the elements 3
[5, 4, 3]
NO
NO
YES
How can I modify the code so it would print only one yes and no only once in case of any occurencies happen?
Here's one solution. Keep in mind there are many that have asked this type of question before and that best practice is to search around before asking.
a = input('enter list A with comma between each element: ')
b = input('enter list B with comma between each element: ')
a = a.split(',')
b = b.split(',')
contained_in_b = [element in b for element in a]
for i, in_b in enumerate(contained_in_b):
print('element {} contained in list B: {}'.format(a[i], in_b))
Better to take the raw input all together and use Python to split it into lists. This way, no need for the user to give the length of the list beforehand. Also, no need to convert to int - string comparisons work fine.
contained_in_b uses a list comprehension - a handy feature of Python that applies the boolean element in b to each element in a. Now you have a list of True/False values that you can enumerate through to print out the desired output.
One weapon you get is the all operator, which just checks that all of the items in the iterable are True:
A = [1, 4, 6, 8, 13]
B = [4, 6, 13, 8]
C = [3, 8, 25]
master = [i for i in range(20)]
print all(i in master for i in A)
print all(i in master for i in B)
print all(i in master for i in C)
Output:
True
True
False
To get the order as well, you'll need to drop back to an iterative method, stepping through the first list with a loop, while you maintain an index to know where you are in the second. For each value in the first list, go through the rest of the second list, until you either find the item (temporary success) or hit the end (failure).
Reading in number names and converting them to integers is a separate problem, and longer code.

How do I write the index for a list of lists

I have a list of 3 lists each containing a random integer between 1 and 9:
lists= [[1,3,5],[2,4,6],[7,8,9]]
I ask the user to select any single digit number. I am making a program that finds the number one less than the user inputs and then decides if the next number in the list (assuming it is not the end of the list) is bigger or smaller.
for x in lists:
for i in x:
if i= user_choice-1:
Here I am stuck.
Lets say the user_choice is 3. I want the program to find the number 3-1=2 in the nested lists and then compare the number following 2 (in this case 4) to the user_choice.
if your list is
lists= [[1,3,5],[2,4,6],[7,8,9]]
to access the "1" you would type: lists[0][0]
to access the "8" you would type: lists[2][1]
*remember lists start their index at 0!!! :)
I am a little confused by what you are trying to achieve but you can get the index along with the element in a for loop by using:
for index, value in enumerate(my_list):
# Do stuff here
Or you can find the index of any element in a list with:
index = my_list.index(value)
Don't forget to change you = to a == in your if statement, by the way.
If I understand correctly, you want:
for x in lists:
for i in range(len(x)):
if x[i] == user_choice-1 and i < len(x)-1:
if x[i+1] > x[i]:
#Next value is bigger...
else:
#Next value is smaller...
lists= [[1,3,5],[2,4,6],[7,8,9]]
for x in lists:
index = 0
for i in x:
index += 1
if i == user_choice - 1:
print(x[index])
else:
(...)

List index out of range while counting Python

I have a little problem - I need to iterate through a list of lists (lines in a file) and count how many times the lines begin with six or seven. It was no problem, but I also need to remove the items which repeat themselves, e.g. if I have this: [6,6,7,7,6], I need to do this out of it: [6,7,6] - it is the number of switches that counts. But somehow the list index is always out of range. Why?
Thank you!
def number_of_switches(list):
counter = []
for element in li:
if int(element[0]) == 6 or int(element[0]) == 7: counter.append(element[0])
else: pass
i = 0
for i in (0, len(counter)):
if counter[i] == counter[i+1]: counter.remove(counter[i+1])
print 'number of switches is', len(counter)-1 #the first number doesn't count as switch, hence '-1'
for i in (0, len(counter)) only iterates over two elements: 0, and the length of counter. It does not count up from 0 to the length. For that you need range:
for i in range(len(counter))
However, you should not do that either. Think about what happens each time you remove an element: the list is now one shorter, but you are iterating until the end of the original list. So you will quickly get an IndexError. You need to append the non-matching elements to a new list, rather than removing from the current one.
When you write:
for i in (0, len(counter)):
That means for in those two values: 0 and len(counter) and, len(counter) is the index out of range.
I think you meant:
for i in range(0, len(counter)):
You should be doing for i in range(len(counter)): and also if counter[i] == counter[i+1]: will give an error in this range. You need to handle the end case.
This might be a better solution:
def number_of_switches(list):
counter = []
prev = li[0]
for element in range(1, len(li)):
if int(li[element][0]) != prev:
count.append(int(li[element][0]))
print 'number of switches is', len(counter)-1 #the first number doesn't count as switch, hence '-1'

Categories