In: Computer Science
Assume s is a string of numbers. Write a program that prints the longest substring of s in which the numbers occur in ascending order and compute the average of the numbers found. For example, if s = '561984235272145785310', then your program should print Longest substring in numeric ascending order is: 14578 Average: 5 In the case of ties, print the first substring. For example, if s = '147279', then your program should print Longest substring in numeric ascending order is: 147 Average: 4
I need python code for this one?
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly indented for better understanding.
def satisfies(num):
for i in range(1,len(num)):
if num[i-1] > num[i]:
return False
return True
def find_longest_substr(s):
#Initialise the longest substring as ''
longest_substr=''
#Loop through each substring
for i in range(len(s)):
for j in range(i,len(s)):
#Get the substring
sub_str = s[i:j]
#If satisfies and larger, then it is longest_substr
if satisfies(sub_str) and
len(longest_substr)<len(sub_str):
longest_substr = sub_str
sum_of_numbers =sum(int(x) for x in longest_substr)
return longest_substr, sum_of_numbers/len(longest_substr)
#TEST 1
s= '561984235272145785310'
longest_substr, average = find_longest_substr(s)
print('Longest Increasing Substring: ',longest_substr)
print('Average of digits: ',average)
#TEST 2
s= '147279'
longest_substr, average = find_longest_substr(s)
print('Longest Increasing Substring: ',longest_substr)
print('Average of digits: ',average)
================================
SCREENSHOT: