Home > Software design >  Trouble with creating my own math functions and displaying them
Trouble with creating my own math functions and displaying them

Time:11-09

I am required to make a program that asks a user to input a list of numbers and then what function they'd like to apply, adn then print out the results. I have a few problems: It's saying I'm using variables before I assign them, it's saying invalid or unexpected types for my for loop, and I'm not sure the math functions will even 100% work.

I expected to be able to input a list of numbers and then do calculations based on the list and print out the results.

my code:

list = []
def median(list):
    if len(list) == 0:
        return 0
    list.sort()
    medianIndex = len(list) // 2
    if len(list) %2 == 1:
        return list[medianIndex]
    else:
        return (list[medianIndex]   list[medianIndex - 1]) / 2

def mean(list):
    if len(list) == 0:
        return 0
    list.sort()
    total = 0
    for number in list:
        total  = number
    return total / len(list)

def mode(list):
    numDict = {}
    for digit in list:
        number = numDict.get(digit, None)
    if number == None:
        numDict[digit] = 1
    else:
        numDict[digit] = number   1
    maxVal = max(numDict.values())
    modeList = []
    for key in numDict:
        if numDict[key] == maxVal:
            modeList.append(key)
        return modeList
    else:
        return 0

def main():
    while True:
        inputList = input("Enter a number: ")
        if inputList == "":
          break

        list = inputList.split()
        for i in range(len(list)):
            list[i] = int(list[i])
            list.append(inputList)

    function = input("Enter what math function you'd like to use: ")
    if function == "mean":
        print("Here is the list and its mean: ", "\n", list, "\n", mean(list))
    elif function == "median":
        print("Here is the list and its median: ", "\n", list, "\n", median(list))
    elif function == "mode":
        print("Here is the list and its mode: ", "\n", list, "\n", mode(list))
    else:
        print("that is not a acceptable function, please retry.")

if __name__ == "__main__":
    main()


errors I'm getting when running what's above: 

Traceback (most recent call last):
  File "C:\Users\Phillip\PycharmProjects\pythonProject-Snake_Game\stats.py", line 70, in <module>
    main()
  File "C:\Users\Phillip\PycharmProjects\pythonProject-Snake_Game\stats.py", line 61, in main
    print("Here is the list and its mean: ", "\n", list, "\n", mean(list))
  File "C:\Users\Phillip\PycharmProjects\pythonProject-Snake_Game\stats.py", line 25, in mean
    list.sort()
TypeError: '<' not supported between instances of 'str' and 'int'

CodePudding user response:

this is how I would do it, made minor changes to only main function. everything else is same. compare it to yours.

def main(): list = [] while True: inputvar = input("Enter a number: ") print(type(inputvar)) if inputvar == "": break else: list.append(int(inputvar))

function = input("Enter what math function you'd like to use: ")
if function == "mean":

CodePudding user response:

I've made some tweaks to your program, added some type hints to the function parameters, made it a little more robust, and wrote some docstrings as well.

Here's my suggestion on how you might consider writing your app:


from typing import Any, List, Union
import re


Numeric = Union[int, float]


def to_number(num: Any) -> Any:
    """Convert numbers represented as strings to numeric values.

    Parameters
    ----------
    num : Any
        Object that might contain a numeric value.

    Returns
    -------
    Any
        ``num`` as either ``float``, ``int``, or ``unmodified``.
    """
    try:
        num = int(num)
    except ValueError:
        num = round(float(num), 4)
    finally:
        return num


def extract_numbers(text: str) -> List[Numeric]:
    """Extract all numbers from a string returning a list of numbers.

    Parameters
    ----------
    text : str
        The string to extract numbers from.

    Returns
    -------
    List[Numeric]
        A list of numbers.

    Examples
    --------
    >>> extract_numbers('1 2 3')
    [1, 2, 3]
    >>> extract_numbers('1.5,2.5,3.5')
    [1.5, 2.5, 3.5]
    """
    return [
        to_number(num)
        for num in re.findall(r"[- ]?\d*\.\d |\d ", text)
    ]


def median(_list: List[Numeric]) -> Numeric:
    """Return the median value from a list of numbers.

    Parameters
    ----------
    _list : List[Numeric]
        A list of numbers.

    Returns
    -------
    Numeric
        The median value.
    """
    if not _list:
        return 0
    _list.sort()
    median_index = len(_list) // 2
    if len(_list) % 2 == 1:
        return _list[median_index]
    return (_list[median_index]   _list[median_index - 1]) / 2


def mean(_list: List[Numeric]) -> Numeric:
    """Compute the mean from a list of numbers.

    Parameters
    ----------
    _list : List[Numeric]
        A list of numbers.

    Returns
    -------
    Numeric
        The mean value of the given ``_list``.
    """
    return sum(_list) / len(_list) if _list else 0


def mode(_list: List[Numeric]) -> List[Numeric]:
    """Return the mode from a list of numbers.

    Parameters
    ----------
    _list : List[Numeric]
        A list of numbers.

    Returns
    -------
    List[Numeric]
        A list with the mode(s) from ``_list``.

    Examples
    --------
    >>> mode([1, 2, 3])
    [1, 2, 3]
    >>> mode([1, 1, 2, 3, 3])
    [1, 3]
    """
    num_dict = {
        digit: _list.count(digit)
        for digit in _list
    }
    max_val = max(num_dict.values())
    return [key for key, value in num_dict.items() if value == max_val]


def main():
    """Main entry point for the program."""
    
    print(f"{' Welcome to the List Calculator ':=^50}")
    print("At any time, write \"q\" to exit the program")

    while True:
        input_list = input("Enter a number or list of numbers: ").lower()
        if input_list in ["", "q", "quit"]:
            print("Okay, bye!")
            break
        _list = extract_numbers(input_list)
        if len(_list) == 0:
            print("No values were entered, exiting program...")
            break

        function = input(
            "Enter the name of the math operation you'd like to apply: "
        ).lower()

        if function == "mean":
            print("Here is the list and its mean:", _list, to_number(mean(_list)), sep="\n")
        elif function == "median":
            print(
                "Here is the list and its median:", _list, to_number(median(_list)), sep="\n"
            )
        elif function == "mode":
            print("Here is the list and its mode:", _list, mode(_list), sep="\n")
        elif function in ["", "q", "quit"]:
            print("Okay, bye!")
            break
        else:
            print(
                f"Unknown math operation \"{function}\". "
                "Please choose one of the following operations: "
                  ", ".join(["mode", "mean", "median"])
            )


if __name__ == "__main__":
    main()

Example usage:

enter image description here

  • Related