Longest Common Prefix - getting runtime error - python

Question:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lowercase English letters.
My Code
def longestCommonPrefix(self, s: List[str]) -> str:
st=''
for i in range(len(s[0])):
ch = s[0][i]
match = True
for j in range(1,len(s)):
lj= len(s[j])
if lj<i or ch != s[j][i]:
match = False
break
if match == False:
break
else:
st+=ch
return st
Runtime Error for following Input :
Input
["ab", "a"]

Take the first element, iterate over subsequent elements and determine the longest prefix
def solution( strs):
if not strs:
return ""
res = strs[0]
i = 1
while i < len(strs):
while strs[i].find(res) != 0:
res = res[0:len(res) - 1]
i += 1
return res
# OUTPUT:
print(solution(["flower","flow","flight"])) # fl
print(solution(["dog","racecar","car"])) #
print(solution( ["ab", "a"])) # a

first, you can get all occurrences; add in dict & then can work upon that dict
You can try:
strs = ["flower","flow","flight"]
collect_dict = {}
for data in strs:
for d_index, d_data in enumerate(data):
# import pdb;pdb.set_trace()
inner_data = data[0:d_index + 1]
if inner_data not in collect_dict:
collect_dict[inner_data] = len([item for item in strs if item.startswith(inner_data)])
print(collect_dict)
keymax = max(zip(collect_dict.values(), collect_dict.keys()))[1]
print("max: " + keymax)
Output:
{'f': 3, 'fl': 3, 'flo': 2, 'flow': 2, 'flowe': 1, 'flower': 1, 'fli': 1, 'flig': 1, 'fligh': 1, 'flight': 1}
max: fl

Related

Sorting keys in a map

Program gets an input at the beginning. That inputed string can contain capital letters or any other ascii letters. We don't difference between them, so we just use lower() method. Also any letters other than letters from alphabet (numbers etc.) are used as spaces between strings. Function is supposed to analyse the input, sort it and count it.
Output:
{'idk': 2, 'idc': 1, 'idf': 1}
Input:
print(word_frequency("Idk, Idc, Idk, Idf"))
I tried this and It's sorting the input, but I can't find a way to separate strings. This is what I did:
def word_frequency(text):
f = {}
pendens = ""
for s in text:
if s.isalpha():
pendens += s
else:
pendens = pendens.lower()
if pendens != " ":
if f.get(pendens, -1) != -1:
f[pendens] += 1
else:
f[pendens] = 1
pendens = pendens.lower()
if pendens != " ":
if f.get(pendens, -1) != -1:
f[pendens] += 1
else:
f[pendens] = 1
return f
print(word_frequency("Idk, Idc, Idk, Idf"))
print(word_frequency("Idk,+Idc,Idk;;-;Idf"))
print(word_frequency("help me please"))
I'm trying to get better at coding so any form of help will be appreciated :)
The easiest solution would involve regex and Counter, which is a type of dictionary specifically tailored to counting occurrences of values like this:
>>> import re
>>> from collections import Counter
>>> words = 'Idk, Idc, Idk, Idf'
>>> re.findall('[a-z]+', words.lower())
['idk', 'idc', 'idk', 'idf']
>>> Counter(re.findall('[a-z]+', words.lower()))
Counter({'idk': 2, 'idc': 1, 'idf': 1})
If you cannot use Counter, then a plain dictionary would also work. We can use dict.get to handle words that both are and are not in the dict yet:
def count_words(words):
counts = {}
for word in re.findall('[a-z]+', words.lower()):
counts[word] = counts.get(word, 0) + 1
return counts
Results in:
>>> count_words('Idk, Idc, Idk, Idf')
{'idk': 2, 'idc': 1, 'idf': 1}
If you cannot use regex, then the problem becomes more complicated, but still doable. A generator like the following would work:
def split_words(words):
word = ''
for c in words.lower():
if 97 <= ord(c) <= 122: # ord('a') thru ord('z')
word += c
elif word:
yield word
word = ''
if word:
yield word
def count_words(words):
counts = {}
for word in split_words(words):
counts[word] = counts.get(word, 0) + 1
return counts
Results in:
>>> count_words('Idk, Idc, Idk, Idf')
{'idk': 2, 'idc': 1, 'idf': 1}

How to move element around element in a string

I want a function that moves the last element in str_a around the string until the end. (In this case: 'adbefc') and then the second last element in str_1 moves one, then the last element moves till the end again. I want to move all the elements in str_a except for the first element.
def arrange(str_a, str_b): #You don't need to use this variable
#TODO
>>> arrange('abc', 'def') #Example 1
['abcdef', 'abdcef', 'abdecf', 'abdefc', 'adbcef', 'adbecf', 'adbefc', 'adebcf', 'adebfc', 'adefbc']
>>> arrange('OXY', 'OOO') #Example 1a (Better insight)
['OXYOOO', 'OXOYOO', 'OXOOYO', 'OXOOOY', 'OOXYOO', 'OOXOYO', 'OOXOOY', 'OOOXYO', 'OOOXOY', 'OOOOXY']
>>> arrange('ab', 'cd') #Example 2
['abcd', 'acbd', 'acdb']
Here's what I have done, it only works with a 2 character string. Hopefully, this will give some idea of what I'm trying to accomplish
def arrange(str_a, str_b, idx = 0, lst = []):
idx += 1
length = len(str_a + str_b)
if idx == length - 1:
return lst
str_full = str_a + str_b
list_full = list(str_full)
elem = list_full[idx]
list_full[idx] = list_full[idx + 1]
list_full[idx + 1] = elem
lst.append(''.join(list_full))
middle_index = int(length/2)
str_a = ''.join(list_full[:middle_index])
str_b = ''.join(list_full[middle_index:])
return arrange(str_a, str_b, original, idx, rev,lst)
if __name__ == '__main__':
result = arrange('ab', 'cd')
print(result)```
itertools.combinations is your friend.
import itertools
def arrange_helper(str1, str2):
m, n = len(str1), len(str2)
for indices in itertools.combinations(range(1, m+n), m-1):
characters = [None] * (m+n)
characters[0] = str1[0]
for index, character in zip(indices, str1[1:]):
characters[index] = character
it = iter(str2)
for index, character in enumerate(characters):
if character is None:
characters[index] = next(it)
yield ''.join(characters)
def arrange(str1, str2):
return list(arrange_helper(str1, str2))
Examples:
>>> arrange('123', '456')
['123456', '124356', '124536', '124563', '142356', '142536', '142563', '145236', '145263', '145623']
>>> arrange('OXY', 'OOO')
['OXYOOO', 'OXOYOO', 'OXOOYO', 'OXOOOY', 'OOXYOO', 'OOXOYO', 'OOXOOY', 'OOOXYO', 'OOOXOY', 'OOOOXY']

find multiple pattern from a string and return even pattern

I see one coding question as following. what will be a better solution for it? I have tried using two while loop and wondering if there is better/ clean way to do it?
One message system contains two device type message that each message is formatted with device type identifier with device id and message count. Write a function to parse the message based on device type and message count and return a list with each device id in even message frequency
rule: input string: message
device identifier
1:iOS device ID identifier: start with 'I' following with 3 character, total length is 4 character
2:Android device ID identifier: start with 'A' following with 2 character, total length is 3 character
3:message count is following by device id until next device ID
ex: input: Asq2: {'Asq': 2} Asq with 2 message count
output: ['Asq', 'Asq']
input: Akb2IAld3: ID: {'Akb': 2, 'IAld': 3} Akb with 2 message count, IAld with 3 message count
output: ['Akb', 'IAld', 'Akb', 'IAld', 'IAld']
input: Aqp1Iasd10Aqp4IAbd1Iasd2: {'Aqp': 5, 'Iasd': 12, 'IAbd': 1}
output: ['Aqp', 'Iasd', 'IAbd', 'Aqp', 'Iasd', 'Aqp', 'Aqp', 'Aqp', 'Iasd', 'Iasd', 'Iasd', 'Iasd', 'Iasd', 'Iasd'..., 'Iasd']
def parse_message(string) -> List:
i, j, ids_map, n, ids = 0, 0, dict(), len(string), ''
while i < n:
if string[i] in ('I', 'A') or i == n - 1:
if ids:
if i == n - 1:
ids_map[ids] = ids_map.get(ids, 0) + int(string[j:])
else:
ids_map[ids] = ids_map.get(ids, 0) + int(string[j:i])
j = i + 4 if string[i] == 'I' else i + 3
ids = string[i:j]
i = j - 1
i += 1
res = []
while any(i > 0 for i in ids_map.values()):
for k, v in ids_map.items():
if v > 0:
res.append(k)
ids_map[k] -= 1
return res
try this one. are you referring to this:
import re
def parse_message(string):
res = list()
data = re.findall('\d+|\D+', string)
for i in range(0, len(data), 2):
for j in range(0, int(data[i+1])):
res.append(data[i])
return res
print(parse_message("Aqp1Iasd10Aqp4IAbd1Iasd2"))
i use regex to split the string into letters and numbers list, then loop every 2 items ( for string and repition count).

Longest substring without repeating characters in python

This is a pretty standard interview question. Find the longest substring without repeating characters. Here are the test cases,
abcabcbb -> 3
bbbbb -> 1
pwwkew -> 3
bpfbhmipx -> 7
tmmzuxt -> 5
Here's my code which uses a pretty simple approach with 2 pointers.
def lengthOfLongestSubstring(s):
checklist = {}
starting_index_of_current_substring = 0
length_of_longest_substring = 0
for i, v in enumerate(s):
if v in checklist:
starting_index_of_current_substring = checklist[v] + 1
else:
length_of_current_substring = i - starting_index_of_current_substring + 1
length_of_longest_substring = max(length_of_current_substring, length_of_longest_substring)
checklist[v] = i
return length_of_longest_substring
My code passes all the test cases except the last one (actual 4, expected 5). Can someone help me modify the code to take care of the last test case. I don't wish to reinvent the algorithm.
Here is a simple tweak in your code with 2 pointers to find the longest sub-string without repeating characters.
Change in your code is instead of calculating the length of longest substring when v is not present in checklist, I am calculating length of longest substring for all cases.
def lengthOfLongestSubstring(s):
checklist = {}
starting_index_of_current_substring = 0
length_of_longest_substring = 0
for i, v in enumerate(s):
if v in checklist:
starting_index_of_current_substring = max(starting_index_of_current_substring, checklist[v] + 1)
checklist[v] = i
length_of_longest_substring = max(length_of_longest_substring, i - starting_index_of_current_substring + 1)
return length_of_longest_substring
## Main
result = {}
for string in ['abcabcbb', 'bbbbb', 'ppwwkew', 'wcabcdeghi', 'bpfbhmipx', 'tmmzuxt', 'AABGAKGIMN', 'stackoverflow']:
result[string] = lengthOfLongestSubstring(string)
print(result)
Sample run:
{'abcabcbb': 3, 'bbbbb': 1, 'ppwwkew': 3, 'wcabcdeghi': 8, 'bpfbhmipx': 7, 'tmmzuxt': 5, 'AABGAKGIMN': 6, 'stackoverflow': 11}
This post is pretty old, but I think my solution fixes the bug in the original code.
def lengthOfLongestSubstring(s):
checklist = {}
starting_index_of_current_substring = 0
length_of_longest_substring = 0
for i, v in enumerate(s):
if v in checklist:
if checklist[v] >= starting_index_of_current_substring:
starting_index_of_current_substring = checklist[v] + 1
length_of_current_substring = i - starting_index_of_current_substring + 1
length_of_longest_substring = max(length_of_current_substring, length_of_longest_substring)
checklist[v] = i
return length_of_longest_substring
This doesnt really iterate upon your solution, but it's a bit simpler approach, just to give you an idea how it could be also solved.
def longest_substr(s):
longest = 0
for start_index in range(len(s)):
contains = set()
for letter in s[start_index:]:
if letter in contains:
break
contains.add(letter)
longest = max(longest, len(contains))
return longest
0
I would prefer this solution>>
Time and Space Management Optimised:
def lengthOfLongestSubstring(self, s: str) -> int:
curlen = maxlen = 0 # curlen saves the max len of substrings ending with current num
for i, num in enumerate(s):
curlen -= s[i-curlen:i].find(num)
maxlen = max(maxlen, curlen)
return maxlen
Find Longest Substring in the string without repeating characters.
def find_non_repeating_substring(input_str):
output_length = 0
longest_sub_str = ''
len_str = len(input_str)
index = 0
while len_str != 1:
l_str = ''
for i in range(index, len(input_str)):
if input_str[i] not in l_str:
l_str = l_str + input_str[i]
else:
break
sub_str_length = len(l_str)
if sub_str_length > output_length:
output_length = sub_str_length
longest_sub_str = l_str
len_str = len_str -1
index = index + 1
return output_length,longest_sub_str
if __name__ == '__main__':
input_str = raw_input("Please enter the string: ")
sub_str_length, sub_str = find_non_repeating_substring(input_str)
print ('Longest Substing lenght is "{0}" and the sub string is "{1}"'.format(sub_str_length, sub_str))```

Create a compress function in Python?

I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. My function should return the shortened version of the string. I've been able to count the first character but not any others.
Ex:
>>> compress("ddaaaff")
'd2a3f2'
def compress(s):
count=0
for i in range(0,len(s)):
if s[i] == s[i-1]:
count += 1
c = s.count(s[i])
return str(s[i]) + str(c)
Here is a short python implementation of a compression function:
def compress(string):
res = ""
count = 1
#Add in first character
res += string[0]
#Iterate through loop, skipping last one
for i in range(len(string)-1):
if(string[i] == string[i+1]):
count+=1
else:
if(count > 1):
#Ignore if no repeats
res += str(count)
res += string[i+1]
count = 1
#print last one
if(count > 1):
res += str(count)
return res
Here are a few examples:
>>> compress("ddaaaff")
'd2a3f2'
>>> compress("daaaafffyy")
'da4f3y2'
>>> compress("mississippi")
'mis2is2ip2i'
Short version with generators:
from itertools import groupby
import re
def compress(string):
return re.sub(r'(?<![0-9])[1](?![0-9])', '', ''.join('%s%s' % (char, sum(1 for _ in group)) for char, group in groupby(string)))
(1) Grouping by chars with groupby(string)
(2) Counting length of group with sum(1 for _ in group) (because no len on group is possible)
(3) Joining into proper format
(4) Removing 1 chars for single items when there is a no digit before and after 1
There are several reasons why this doesn't work. You really need to try debugging this yourself first. Put in a few print statements to trace the execution. For instance:
def compress(s):
count=0
for i in range(0, len(s)):
print "Checking character", i, s[i]
if s[i] == s[i-1]:
count += 1
c = s.count(s[i])
print "Found", s[i], c, "times"
return str(s[i]) + str(c)
print compress("ddaaaff")
Here's the output:
Checking character 0 d
Found d 2 times
Checking character 1 d
Found d 2 times
Checking character 2 a
Found a 3 times
Checking character 3 a
Found a 3 times
Checking character 4 a
Found a 3 times
Checking character 5 f
Found f 2 times
Checking character 6 f
Found f 2 times
f2
Process finished with exit code 0
(1) You throw away the results of all but the last letter's search.
(2) You count all occurrences, not merely the consecutive ones.
(3) You cast a string to a string -- redundant.
Try working through this example with pencil and paper. Write down the steps you use, as a human being, to parse the string. Work on translating those to Python.
x="mississippi"
res = ""
count = 0
while (len(x) > 0):
count = 1
res= ""
for j in range(1, len(x)):
if x[0]==x[j]:
count= count + 1
else:
res = res + x[j]
print(x[0], count, end=" ")
x=res
Just another simplest way to perform this:
def compress(str1):
output = ''
initial = str1[0]
output = output + initial
count = 1
for item in str1[1:]:
if item == initial:
count = count + 1
else:
if count == 1:
count = ''
output = output + str(count)
count = 1
initial = item
output = output + item
print (output)
Which gives the output as required, examples:
>> compress("aaaaaaaccddddeehhyiiiuuo")
a7c2d4e2h2yi3u2o
>> compress("lllhhjuuuirrdtt")
l3h2ju3ir2dt
>> compress("mississippi")
mis2is2ip2i
from collections import Counter
def string_compression(string):
counter = Counter(string)
result = ''
for k, v in counter.items():
result = result + k + str(v)
print(result)
input = "mississippi"
count = 1
for i in range(1, len(input) + 1):
if i == len(input):
print(input[i - 1] + str(count), end="")
break
else:
if input[i - 1] == input[i]:
count += 1
else:
print(input[i - 1] + str(count), end="")
count = 1
Output : m1i1s2i1s2i1p2i1
s=input("Enter the string:")
temp={}
result=" "
for x in s:
if x in temp:
temp[x]=temp[x]+1
else:
temp[x]=1
for key,value in temp.items():
result+=str(key)+str(value)
print(result)
Here is something I wrote.
def stringCompression(str1):
counter=0
prevChar = str1[0]
str2=""
charChanged = False
loopCounter = 0
for char in str1:
if(char==prevChar):
counter+=1
charChanged = False
else:
str2 += prevChar + str(counter)
counter=1
prevChar = char
if(loopCounter == len(str1) - 1):
str2 += prevChar + str(counter)
charChanged = True
loopCounter+=1
if(not charChanged):
str2+= prevChar + str(counter)
return str2
Not the best code I guess. But works well.
a -> a1
aaabbbccc -> a3b3c3
This is a solution to the problem. But keep in mind that this method only effectively works if there's a lot of repetition, specifically if consecutive characters are repetitive. Otherwise, it will only worsen the situation.
e.g.,
AABCD --> A2B1C1D1
BcDG ---> B1c1D1G1
def compress_string(s):
result = [""] * len(s)
visited = None
index = 0
count = 1
for c in s:
if c == visited:
count += 1
result[index] = f"{c}{count}"
else:
count = 1
index += 1
result[index] = f"{c}{count}"
visited = c
return "".join(result)
You can simply achieve that by:
gstr="aaabbccccdddee"
last=gstr[0]
count=0
rstr=""
for i in gstr:
if i==last:
count=count+1
elif i!=last:
rstr=rstr+last+str(count)
count=1
last=i
rstr=rstr+last+str(count)
print ("Required string for given string {} after conversion is {}.".format(gstr,rstr))
Here is a short python implementation of a compression function:
#d=compress('xxcccdex')
#print(d)
def compress(word):
list1=[]
for i in range(len(word)):
list1.append(word[i].lower())
num=0
dict1={}
for i in range(len(list1)):
if(list1[i] in list(dict1.keys())):
dict1[list1[i]]=dict1[list1[i]]+1
else:
dict1[list1[i]]=1
s=list(dict1.keys())
v=list(dict1.values())
word=''
for i in range(len(s)):
word=word+s[i]+str(v[i])
return word
Below logic will work irrespective of
Data structure
Group By OR Set or any sort of compression logic
Capital or non-capital characters
Character repeat if not sequential
def fstrComp_1(stng):
sRes = ""
cont = 1
for i in range(len(stng)):
if not stng[i] in sRes:
stng = stng.lower()
n = stng.count(stng[i])
if n > 1:
cont = n
sRes += stng[i] + str(cont)
else:
sRes += stng[i]
print(sRes)
fstrComp_1("aB*b?cC&")
I wanted to do it by partitioning the string.
So aabbcc would become: ['aa', 'bb', 'cc']
This is how I did it:
def compression(string):
# Creating a partitioned list
alist = list(string)
master = []
n = len(alist)
for i in range(n):
if alist[i] == alist[i-1]:
master[-1] += alist[i]
else:
master += alist[i]
# Adding the partitions together in a new string
newString = ""
for i in master:
newString += i[0] + str(len(i))
# If the newString is longer than the old string, return old string (you've not
# compressed it in length)
if len(newString) > n:
return string
return newString
string = 'aabbcc'
print(compression(string))
string = 'aabccccd'
output = '2a3b4c4d'
new_string = " "
count = 1
for i in range(len(string)-1):
if string[i] == string[i+1]:
count = count + 1
else:
new_string = new_string + str(count) + string[i]
count = 1
new_string = new_string + str(count) + string[i+1]
print(new_string)
For a coding interview, where it was about the algorithm, and not about my knowledge of Python, its internal representation of data structures, or the time complexity of operations such as string concatenation:
def compress(message: str) -> str:
output = ""
length = 0
previous: str = None
for char in message:
if previous is None or char == previous:
length += 1
else:
output += previous
if length > 1:
output += str(length)
length = 1
previous = char
if previous is not None:
output += previous
if length > 1:
output += str(length)
return output
For code I'd actually use in production, not reinventing any wheels, being more testable, using iterators until the last step for space efficiency, and using join() instead of string concatenation for time efficiency:
from itertools import groupby
from typing import Iterator
def compressed_groups(message: str) -> Iterator[str]:
for char, group in groupby(message):
length = sum(1 for _ in group)
yield char + (str(length) if length > 1 else "")
def compress(message: str) -> str:
return "".join(compressed_groups(message))
Taking things a step further, for even more testability:
from itertools import groupby
from typing import Iterator
from collections import namedtuple
class Segment(namedtuple('Segment', ['char', 'length'])):
def __str__(self) -> str:
return self.char + (str(self.length) if self.length > 1 else "")
def segments(message: str) -> Iterator[Segment]:
for char, group in groupby(message):
yield Segment(char, sum(1 for _ in group))
def compress(message: str) -> str:
return "".join(str(s) for s in segments(message))
Going all-out and providing a Value Object CompressedString:
from itertools import groupby
from typing import Iterator
from collections import namedtuple
class Segment(namedtuple('Segment', ['char', 'length'])):
def __str__(self) -> str:
return self.char + (str(self.length) if self.length > 1 else "")
class CompressedString(str):
#classmethod
def compress(cls, message: str) -> "CompressedString":
return cls("".join(str(s) for s in cls._segments(message)))
#staticmethod
def _segments(message: str) -> Iterator[Segment]:
for char, group in groupby(message):
yield Segment(char, sum(1 for _ in group))
def compress(message: str) -> str:
return CompressedString.compress(message)
def compress(val):
print(len(val))
end=0
count=1
result=""
for i in range(0,len(val)-1):
#print(val[i],val[i+1])
if val[i]==val[i+1]:
count=count+1
#print(count,val[i])
elif val[i]!=val[i+1]:
#print(end,i)
result=result+val[end]+str(count)
end=i+1
count=1
result=result+val[-1]+str(count)
return result
res=compress("I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. My function should return the shortened version of the string. I've been able to count the first character but not any others.")
print(len(res))
Use python's standard library re.
def compress(string):
import re
p=r'(\w+?)\1+' # non greedy, group1 1
sub_str=string
for m in re.finditer(p,string):
num=m[0].count(m[1])
sub_str=re.sub(m[0],f'{m[1]}{num}',sub_str)
return sub_str
string='aaaaaaaabbbbbbbbbcccccccckkkkkkkkkkkppp'
string2='ababcdcd'
string3='abcdabcd'
string4='ababcdabcdefabcdcd'
print(compress(string))
print(compress(string2))
print(compress(string3))
print(compress(string4))
Resut:
a8b9c8k11p3
ab2cd2
abcd2
ab2cdabcdefabcd2
Using generators:
input = "aaaddddffwwqqaattttttteeeeeee"
from itertools import groupby
print(''.join(([char+str(len(list(group))) for char, group in groupby(input)])))
def compress(string):
# taking out unique characters from the string
unique_chars = []
for c in string:
if not c in unique_chars:
unique_chars.append(c)
# Now count the characters
res = ""
for i in range(len(unique_chars)):
count = string.count(unique_chars[i])
res += unique_chars[i]+str(count)
return res
string = 'aabccccd'
compress(string)
from collections import Counter
def char_count(input_str):
my_dict = Counter(input_str)
print(my_dict)
output_str = ""
for i in input_str:
if i not in output_str:
output_str += i
output_str += str(my_dict[i])
return output_str
result = char_count("zddaaaffccc")
print(result)
This is the modification of Patrick Yu's code. It code fails for the below test cases.
SAMPLE INPUT:
c
aaaaaaaaaabcdefgh
EXPECTED OUTPUT:
c1
a10b1c1d1e1f1g1h1
OUPUT OF Patrick's Code:
c
a10bcdefgh
Below is the modified code:
def Compress(S):
Ans = S[0]
count = 1
for i in range(len(S)-1):
if S[i] == S[i+1]:
count += 1
else:
if count >= 1:
Ans += str(count)
Ans += S[i+1]
count = 1
if count>=1:
Ans += str(count)
return Ans
Just the condition must be changed from greater(">") to greater than equal to(">=") when comparing the count with 1.

Categories

Resources