Home > Enterprise >  Python function that finds the shortest string in a string list or the lowest element of an integer
Python function that finds the shortest string in a string list or the lowest element of an integer

Time:12-30

I'm doing this exercise:

Write a Python program that gives two options to the user to either find the shortest string in a string list or the lowest element of an integer list. The program should read the two lists in both cases and handle any invalid inputs as well. Explain how can you use the top-down approach to analyze and design your model.

def findShortest(stringList):
    indexofshortest = 0 
    shortest = stringList[0]
    length = len(stringList)
    for index in range(1,length):
        current = stringList[index]
        print("Current string is:",current)
        if len(current)<len(shortest):
            print("This is Shorter than:",shortest)
            shortest = current
            indexofshortest = index
    return indexofshortest

print(findShortest(["abc","bc","c"]))

def longestLength(a):
    max1 = len(a[0])
    temp = a[0]
    for i in a:
        if(len(i) > max1):
            max1 = len(i)
            temp = i
            print("The word with the longest length is:", temp,
          " and length is ", max1)

a = ["one", "two", "third", "four"]
print(longestLength(a))

How can I connect the functions together?

CodePudding user response:

You just call them one by one, but as far as I understand the task description:

gives two options to the user

So you want something like:

option = input("Choose one: 1 - longest, 2 - shortest\n")
if option == "1":
    # read lists
    longestLength(...)
elif option == "2":
    # read lists
    findShortest(...)
else:
    print(f"Wrong {option=}")

CodePudding user response:

You can also construct a separate function to provide the options and execute your functions based on the selected option. In this example I use main()

def main():
    while True:
        print("Select options:")
        print("1. Find the shortest word in a list of string.")
        print("2. Find the longest word in list of string.")
        print("3. Exit program.")
        
        select = input("Enter Option: ")
        if select == "3":
            break
        
        word_list = []
        if select in ["1", "2"]:
            input_words = input("Enter comma-separated words: \n")
            word_list = [word.strip() for word in input_words.split(",")]
        else:
            print("\nInvalid selection. please select a valid option.")
            continue

        if select == "1":
            print("Finding the shortest word in a list of strings..\n")
            findShortest(word_list)
      
        elif select == "2":
            print("Finding the longest word in a list of strings..\n")
            longestLength(word_list)
main()

CodePudding user response:

Carefully read the task. It asks for shortest string OR lowest integer. Simplest way is to use min() function with key

def lowest_or_shortest(ints, strs, option):
    if option == "1":
        print(min(ints))
    elif option == "2":
        print(min(strs, key=len))
    else:
        print(f"Wrong {option=}")

ints, strs = [6, 4, 3, 4, 5, 6, 7, 8, 9, 10], ["hello", "hi", "hey"]

lowest_or_shortest(ints, strs, input("Choose one: 1 - lowest integert, 2 - shortest string\n"))
  • Related