Question

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...

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?

Solutions

Expert Solution

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


Related Solutions

def anagramSolution1(s1,s2): alist = list(s2) pos1 = 0 stillOK = True while pos1 < len(s1) and...
def anagramSolution1(s1,s2): alist = list(s2) pos1 = 0 stillOK = True while pos1 < len(s1) and stillOK: pos2 = 0 found = False while pos2 < len(alist) and not found: if s1[pos1] == alist[pos2]: found = True else: pos2 = pos2 + 1 if found: alist[pos2] = None else: stillOK = False pos1 = pos1 + 1 return stillOK include all operations and calculate the Big-O and the values for c and n0.
int f2 (int n) j = 0; while (j <n) {for (int i = 0; i...
int f2 (int n) j = 0; while (j <n) {for (int i = 0; i <n; ++ i) {cout << "j =" + j; j = j + 5; }}
The functions are tested in the following main(): def recSum1(somelist): if len(somelist) == 1: return somelist[0]...
The functions are tested in the following main(): def recSum1(somelist): if len(somelist) == 1: return somelist[0] else: a = recSum1(somelist[:len(somelist)//2]) b = recSum1(somelist[len(somelist)//2:]) return a + b def recSum2(somelist): if len(somelist) == 1: return somelist[0] else: return somelist[0] + recSum2(somelist[1:]) import random def main(): N = 100 myList = [random.randint(-500, 500) for i in range(N)] print(myList) print("The sum of the numbers is: " + str(sum(myList))) print("The sum of the numbers using recSum1 is: " + str(recSum1(myList))) print("The sum of the...
def myLength(mylist):    count = 0    for index in range(len(myList)):        print(myList[index])       ...
def myLength(mylist):    count = 0    for index in range(len(myList)):        print(myList[index])        count = count + 1    return count def myLength2(mylist):    count = 0    for element in myList:        print(element)        count = count + 1    return count       Use these two functions as examples to write your Python function below! Function 1: Write a function called myCount that takes in two parameters (a list and an item) like...
def check(s): #Conditions applied 1,5,6 if len(s)=9 and s[0].isupper() and s[-1].isdigit(): upper_count = sum(1 for c...
def check(s): #Conditions applied 1,5,6 if len(s)=9 and s[0].isupper() and s[-1].isdigit(): upper_count = sum(1 for c in s if c.isupper()) lower_count = sum(1 for c in s if c.islower()) number_count = sum(1 for c in s if c.isdigit()) #Conditions 2,3,4 if upper_count=3 and lower_count==3 and number_count==3: #Condition 7 { Two consecutive alphabets can’t be small } for i in range(1,len(s)): if s[i-1].islower() and s[i].islower() : return 'reject' else: return 'reject' #All conditions satisfies here, so accept return 'accept' else: return...
class Board: def __init__(self): self.pieces = [[None for i in range(8)] for j in range(8)] def...
class Board: def __init__(self): self.pieces = [[None for i in range(8)] for j in range(8)] def __str__(self): s = "" for j in range(7, -1, -1): #for each row for i in range(8): # for each column if self.pieces[j][i] is None: # if self.pieces[j][i] is None s += "." # populate the row with '.' val for each column else: s += self.pieces [j][i].get_symbol() s += "\n" #after each row add a new line return s # return after iterating...
Let L = {aibj | i ≠ j; i, j ≥ 0}. Design a CFG and...
Let L = {aibj | i ≠ j; i, j ≥ 0}. Design a CFG and a PDA for this language. Provide a direct design for both CFG and PDA (no conversions from one form to another allowed).
#This function "binarySearchPythonCode" identifies the elements which is present in the start and end values def...
#This function "binarySearchPythonCode" identifies the elements which is present in the start and end values def binarySearchPythonCode(list, Element, startElement, endElement): #Variable which describes whether the element is present or not isPresent = False #condition check for start and end values while startElement<=endElement and not isPresent: #logic for calculating the mid value midElement = startElement + endElement//2 # if condition which checks whether the mid value is same as element to be searched if list[midElement] == Element: #if condition satisfies it...
public void printQueue(DoublyLinkedQueue<Integer> Q){ int len = Q.size(); int k = 0; for (int i=0; i...
public void printQueue(DoublyLinkedQueue<Integer> Q){ int len = Q.size(); int k = 0; for (int i=0; i < len; ++i){ k = Q.dequeue(); Q.enqueue(k);    System.out.println(Q.dequeue()); } } What is the complexity of this code? Select one: a. O(N), N = k b. Q(1) c. Q(N2), N = Q.size() d. O(M), M = Q.size() e. None of the alternatives is correct. which one?
binarySearchLengths(String[] inArray, String search, int start, int end) This method will take in a array of...
binarySearchLengths(String[] inArray, String search, int start, int end) This method will take in a array of strings that have been sorted in order of increasing length, for ties in the string lengths they will be in alphabetical order. The method also takes in a search string and range of indexes (start, end). The method will return a String formatted with the path of search ranges followed by a decision (true or false), see the examples below. Example 1: binarySearchLengths({"a","aaa","aaaaa"},"bb",0,2) would...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT