简体   繁体   中英

How to check if a string contains 2 of the same character

Using for loops, while loops, and/or if statements. How can you find number pairs in a string where the numbers are even indexes

I used if statements which works for a 6 character string but this would take forever if given a large string. So how can I make this code more efficient?

string = '8h8s9c'
if string[0] == string[2] or string[0] == string[4] :
   print('pair')
if string[2] == string[0] or string[2] == string[4] :
   print('pair')
else:
   print('This string contains no pair')

8h8s9c should print pair

5s7a5k should print pair

Since we're only worried about even indexes, we can right away cut out all the other characters.

string = string[::2]

Then check each character we care about (decimal digits) and see if it's in there twice.

if any(string.count(x)>1 for x in '0123456789'):print('pair')
else:print('This string contains no pair')

Super simple answer in python:

string = '8h8s9c'

string = string[::2]; #string = "889", this basically splices the string

string1 = list(string) #string1 = ['8','8','9'], separates into digits

string2 = set(string1) #string2 = {'9','8'} basically all duplicates get eliminated if any. therefore IF there are duplicates, number of elements WILL reduce.

print(len(string1) == len(string2)) # false as 3 != 2
 def func(s):
      l  = list(s)
      for i in s:
           if l.count(i)>1:
                return True
      return False

s = "8h8s9c"
if func(s):
     print("pair")
else:
     print("not pair")

output

pair

this will give you a dictionary with all pairs and # of occurrences:

from collections import Counter
counts = Counter(string)
out = {key:counts[key] for key in counts.keys() if counts[key] > 1}
if out:
    print('Pair')

output:

{'8': 2} #output of out
Pair

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM