Home > Software engineering >  More elegant way to compare char 1 against char in a string
More elegant way to compare char 1 against char in a string

Time:02-26

For my code below, seeking input on a more concise way to compare the char and char 1 in a string without running into an "index out of range" error.

i have run into two coding competition problems that require me to take a string, and keep track of a tally based on if a value repeats itself twice within the string. as of now, my solution is to create a string w/o the first char, compare the two strings in a for loop at the length of the shorter string, and then compare the last two characters outside of the for loop.

n = int(input())
unique = ""

for i in range(n):
    p = input()
    unique  = p

ahead = unique[1::]
sum = 1

for i in range(len(ahead)):
    if unique[i] == ahead[i]:
        sum  = 0
    else:
        sum  = 1

if unique[-1] == unique[-2]:
    sum  = 1
else:
    sum  = 1

print(sum)

CodePudding user response:

Here's a much simpler approach to the problem it seems like you're trying to solve:

In [1]: s = "hello abbey, nonplussed to see you"

In [2]: sum(s.count(char*2) for char in set(s))
Out[2]: 4

It works by iterating over the unique characters of a string (found by simply casting to set), and counting the number of occurrences of that character doubled. E.g., on the first iteration with that example string, char is 'h' and so we compute how many times 'hh' occurs in the string (zero times).

If you insist on comparing pairs of characters, use zip():

In [3]: s = "hello"
   ...: for t in zip(s, s[1:]):
   ...:     print(t)
   ...:
('h', 'e')
('e', 'l')
('l', 'l')
('l', 'o')
  • Related