Question

HI I would like to ask how to write the function when my list is [[1,2,4],[0,3,2]]. Like merging them. I managed to do it separately only. The mean for [1,2,4] is 2.33 and so xbar return me [-1.33,-0.33,1.67] (is like [1,2,4] minus the 2.33. I need help for more lists. Thanks

>>> def mean(Ist): return sum(Ist)/len(Ist) >>> def xbar(data): i = 0 a = mean(data) for i in range(len(data)): data[i] -= a

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer

Here is your answer, Here we can use exception handling properties of pythhon. When we passed through the single list of element, we can easly perform sum() operation. But when we are passing a array of list(2_D array) , we can't perform sum() operation it will produce the above error. So we can handle this problem using exception handling. If there is exception occured during the runtime, we can convert the array of list into a single list, and can find the sum() of elements and length.

So here is your code for fixed code.

def mean(lst):
    return sum(lst)/len(lst)
def xbar(data):
    """
    Just modified with exception handling,If exception occurred, we will convert the array into list.
    """
    try:
        i=0
        a=mean(data)
        for i in range(len(data)):
            data[i]-=a
            i+=1
        return data
    except:
        #create a new list 
        new_data=[]
        #iterate through elements in the array of list, and create a new list with all elements in the array of list
        for row in data:
                a=mean(row)
                for i in row:
                    new_data.append(i-a)
        return new_data
data1=[[1,2,4],[0,3,2]]
data2=[0,3,2]
print(xbar(data1))

output

print(xbar(datai)) [-1.3333333333333335, -0.3333333333333335, 1.6666666666666665, -1.6666666666666667, 1.3333333333333333, 0.

Any doubt please comment, i am here to help you

Thanks in advance

Add a comment
Know the answer?
Add Answer to:
HI I would like to ask how to write the function when my list is [[1,2,4],[0,3,2]]....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to...

    I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to guess its because I'm not using the swap function I built. Every time I run it though I get an error that says the following Traceback (most recent call last): File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 146, in <module> main() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 122, in main studentArray.gpaSort() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py",...

  • For my computer class I have to create a program that deals with making and searching...

    For my computer class I have to create a program that deals with making and searching tweets. I am done with the program but keep getting the error below when I try the first option in the shell. Can someone please explain this error and show me how to fix it in my code below? Thanks! twitter.py - C:/Users/Owner/AppData/Local/Programs/Python/Python38/twitter.py (3.8.3) File Edit Format Run Options Window Help import pickle as pk from Tweet import Tweet import os def show menu():...

  • Using python 3.6 How do I incorporate 0 or negative input to raise an error and...

    Using python 3.6 How do I incorporate 0 or negative input to raise an error and let the user try again? like <=0 #loop to check valid input option. while True: try: choice = int(input('Enter choice: ')) if choice>len(header): print("Invalid choice!! Please try again and select value either:",end=" ") for i in range(1,len(header)+1): print(i,end=",") else: break choice = int(input('\nEnter choice: ')) except ValueError as ve:print('Invalid response, You need to select the number choice from the option menu') # Catch your...

  • Python3, write a program, specific information is in the graphs, I got 7 marks out of...

    Python3, write a program, specific information is in the graphs, I got 7 marks out of 10, you may change my codes to let it gives correct output,restrications are also on the graph, for loop, in key word, enumerate,zip,slices, with key word can't be used. All the information is on the graph, is_shakespeare_play(line) may be a function given that can check whether is Shakespeare play Question 2- 10 marks Write the function keep titles short (filename, max charactars) which takes...

  • Using Python3, How can I aggregate the output from each iteration to one single list? Because...

    Using Python3, How can I aggregate the output from each iteration to one single list? Because from the program I have right now, it gives me the result of every iteration and gives me something like this as individual results and not one large list: None None ... None 130.0 None ... 1764 1765 None To clarify, I have this program where it calculates the sum of bytes sent within each incrementation of every 1 second, but there are instances...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • Below is my code please help me edit it so in the beginning it ask for Press any key to start Tas...

    below is my code please help me edit it so in the beginning it ask for Press any key to start Task n, where n is the task number (1, 2, or 3,4). I already wrote the code for the 4 task. Also please write it so when 1 code is finish running it return to the prompt where it ask to run another task #task 1 list1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','.',',','?'] morse = ['.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','.-.-.-','--..--','..--..'] inp = input("Enter original text : ")...

  • Please help me fix my errors. I would like to read and write the text file...

    Please help me fix my errors. I would like to read and write the text file in java. my function part do not have errors. below is my code import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.IOException; public class LinkedList {    Node head;    class Node    {        int data;        Node next;       Node(int d)        {            data = d;            next = null;        }    }    void printMiddle()    {        Node slow_ptr...

  • Could anyone help add to my python code? I now need to calculate the mean and...

    Could anyone help add to my python code? I now need to calculate the mean and median. In this programming assignment you are to extend the program you wrote for Number Stats to determine the median and mode of the numbers read from the file. You are to create a program called numstat2.py that reads a series of integer numbers from a file and determines and displays the following: The name of the file. The sum of the numbers. The...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT