1

I understand the basics of this problem however I need help on how I can do this the most efficient way possible (taking the least amount of time for the programmer however not substituting stability of the code or efficiency).

Let's say we have a string:

grades=str(input("Enter a string"))

in my code, I would join a space between all characters in the string above and then split the characters into separate items in the same list:

grades=" ".join(grades)
grades.split(" ")

I then want to use loops of some sort to search the list for repeating items. However, I want to learn how I can do this the most efficient way possible:

x=len(grades)
for i in range(0, x):
    if grades[i] ==  # here is were I'm having trouble

I want to know how I can search whether 1 item in the list is equal to any item in the whole list itself. Kind regards.

1 Answer 1

4

I make an example:

from collections import Counter

a =[1,2,3,4,1,2]
c = Counter(a)
for k,v in c.items():
    if v>1:
        print(k,'repeated more than once')

Here the c will be a Counter object like this Counter({1: 2, 2: 2, 3: 1, 4: 1}). the keys are the array values and values are the count of them. So I write the for for your understanding. You can do anything with c, it acts like a dict.

 >> [k for k,v in c.items() if v>1]
 [1, 2]
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you however once tested I found an error, it is much easier if you do not use both k and v in the 4th line of code. You can just use k or v, not both.
I get TypeError: 'int' object is not iterable for the line: for k,v in c:.
sorry I forgot .items(). it is fixed now.@quamrana

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.