In: Computer Science
def longest(string):
start=0;end=1;i=0;
while i<len(string):
j=i+1
while j<len(string) and string[j]>string[j-1]:
j+=1
if end-start<j-i:
#update if current string has greater length than
#max start and end
end=j
start=i
i=j;
avg=0
for i in string[start:end]:
avg+=int(i)
print('The longest string in ascending order is',string[start:end])
print('Teh average is',avg/(end-start))
s=input('Enter a string')
longest(s)
i need a definition and explanation of this code that how it works?
DEFINITION: This function will give you the longest substring which will be an increasing number.
I will explain with some examples below.

PLEASE FOLLOW THE COMMENTS IN THE CODE TO UNDERSTAND HOW EACH LINE WORKS,
def longest(string):
# Let the starting and ending indices that are largest number is 0 and 1
start = 0
end = 1
i = 0
# Start from 0 to end of the string
while i < len(string):
j = i + 1
# Again take a loop j=i+1 to end of string or
# if it violates the condition of increasing order, break out of the loop
while j < len(string) and string[j] > string[j - 1]:
j += 1
if end - start < j - i:
# update if current string has greater length than
# max start and end
end = j
start = i
i = j
# Here we have the start and end indices of the longest possible number
avg = 0
# So, calculate the average here.
# First sum all the numbers and divide it by (end-start)
for i in string[start:end]:
avg += int(i)
print('The longest string in ascending order is', string[start:end])
print('The average is', avg / (end - start))
# Read Input
s = input('Enter a string')
# Call the function and pass the user-entered string
longest(s)
=========================

sample OUTPUTS


