Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - Write a function to return the first element to appear an odd number of times in a string

I would like to write a function that would return the first element that appears odd of times in a string.

I am aware that there is code to return an element an odd number of times and I tried to apply it to a string, but to not much success:

def getOddOccurrence(arr, arr_size): 
    for i in range(0,arr_size): 
        count = 0
        for j in range(0, arr_size): 
            if arr[i] == arr[j]: 
                count+=1
              
        if (count % 2 != 0): 
            return arr[i] 
          
    return -1

driver code:

arr = ["Hello world!"] 
n = len(arr) 
print(getOddOccurrence(arr, n))
# Output: "Hello world!

If the given string "Hello world!", how would I return the first element that appears an odd number of times?

question from:https://stackoverflow.com/questions/65908192/write-a-function-to-return-the-first-element-to-appear-an-odd-number-of-times-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since there was some discussion to provide an optimized solution, here it is: This build's on @SowjanyaRBhat 's code and optimizes it. Pretty much what @OneCriketeer mentioned.

Space Complexity : O(N)
Time Complexity : O(N)

Approach 1: without collections.Counter

from collections import defaultdict


def getOddOccurrence(myString):
    count = defaultdict(int)
    for letter in myString:
        count[letter] += 1
    for letter in myString:
        if count[letter] % 2 != 0:
            return letter

Approach 2: with collections.Counter

(check the cool one-liner in @Alain.T's answer)

from collections import Counter


def getOddOccurrence(myString):
    count = Counter(myString)
    for letter in myString:
        if count[letter] % 2 != 0:
            return letter


# driver code
myString = "llo world!"
print(getOddOccurrence(myString))

# Output: "l"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...