Jump To Right Section
Show
In this article, you will learn how to find the longest substring in ascending order and compute the average with python. To understand this program, you should have knowledge of the following Python Programming
topics:
- Python if…else Statement
- Python for Loop
- Python User-defined Functions
Problem Definition
Assume s is a string. Write a program that prints a substring of numbers, 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 = ‘56aaww1984sktr235270aYmn145ss785fsq31D0‘, then your program should print. Keep in mind – you need to accept the string from the user.
1 2 3 4 5 |
String of numbers: '561984235270145785310' Longest substring in numeric ascending order is: 014578 Average: 4.167 |
In the case of ties, print the first substring. For example, if s = ’14erq72lkm79′, then your program should print
1 2 3 4 5 |
String of numbers: '147279' Longest substring in numeric ascending order is: 147 Average: 4 |
Algorithm
- Take input from the user and store them in variables
- Remove all non-numerical character
- Print the final number
- Find and Print the longest sub-string number from the number
- Calculate and Print the average of the longest substring number
- End
Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
s = input("Enter string: ") string_of_numbers = "" for num in s: if(num.isnumeric()): string_of_numbers = string_of_numbers + num print("String of numbers: ", string_of_numbers) max_digit = "" max_length = 0 max_number = 0 cur_max_digit = "" cur_max_length = 0 total_number = 0 ini_number = 0 for cur_number in string_of_numbers: if int(ini_number) < int(cur_number): ini_number = cur_number cur_max_digit = cur_max_digit + cur_number cur_max_length = cur_max_length + 1 total_number += int(cur_number) else: ini_number = cur_number cur_max_digit = cur_number cur_max_length = 1 total_number = int(cur_number) if max_length < cur_max_length: max_digit = cur_max_digit max_length = cur_max_length max_number = total_number avg = float(max_number) / float(max_length) print("Longest substring in numeric ascending order is: ", max_digit) print("Average: ", avg) |
Leave a Comment