Python function many parts need help

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 876 Views - Last Post: 21 October 2018 - 01:26 PM Rate Topic: -----

#1 ste0008   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 20-October 18

Python function many parts need help

Posted 20 October 2018 - 03:33 PM

I need to finish my class assignment and I am having trouble understanding if what I am doing is right
my assignment states:
Write a function named assignment2 with three inputs input 1 is a list of lists representing an nxn matrix input 2 is a list representing an nx1 matrix input 3 is a list of strings Your function should complete three tasks:
a. Task 1: use the input function to ask the user for a number, then add 7 to the integer value of the input number and print the result. If the user did not put in a number that can be converted to an integer, ask them for another input
b. Task 2: without using numpy or any built in matrix operation functions, multiply input 1 by input 2. You may assume that all inputs are valid and of the correct structure & size. The result should be a list of length n representing an nx1 matrix. Print out the resulting list.
c. Task 3: make a dictionary with one entry per string in the input list (input 3 in your function). the keys will be "s0", "s1", "s2", ...."sn" where the number is the index of the string in the original list and the values are tuples with the original string as the first value and the number of words in the string as the second value. Your function should return the dictionary from task 3
What I have so far some input would be great

def quiz2(input1, input2, input3):
            
    
    while True:#while loop used to run my calculation
        try:#try is used to execute my loop
            
            num = input("Enter a number: ")#num is a varible used to define a user input with string asking for number
            num = int(num)#used to convert my varible to integer
            
        except ValueError as e:#used when the value is not a nuber
                    print("You did not enter a number.")#print sting stateing you didn't post number
                    continue#goes back to top of loop
        else:#else used if number is given
            print(int(num+7))#prints out user input plus seven
            break#break used to break the loop
    input1=[[]]#input1 is a variable that assings a list or matix of nxn size
    input2=[]#input2 is an nx1 matix
    #define a variable named result that takes input one and multiplys it by input 2 printing the result
    result = [[sum(a*b for a,b in zip(input1_row,input2_col)) for input2_col in zip(*input2)] for input1_row in input1]

    for r in result:#for statement used to print my result
        print(r)#returns new matrix
    input3 = []#input3 is an empty list to input strings
    #returnDict returns a dictionary with list postions as keys and the original item and lenth of item as key values
    returnDict = {'s' + str(index): [item, len(item)] for index, item in enumerate(input3)}
    return(returnDict)#return used to output dictionary


Is This A Good Question/Topic? 0
  • +

Replies To: Python function many parts need help

#2 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 14496
  • View blog
  • Posts: 58,110
  • Joined: 12-June 08

Re: Python function many parts need help

Posted 20 October 2018 - 04:10 PM

What is your question?
Was This Post Helpful? 1
  • +
  • -

#3 ste0008   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 20-October 18

Re: Python function many parts need help

Posted 20 October 2018 - 04:19 PM

From the code I have included will it do what is asked for in the instructions

if all of those tasks are broken up into individual functions they run fine but when put together the first while loop sometimes gets stuck. The second task is returning only a blank list []. The last part is right for dictionary comprehension but I need the data in the keys to be in the form of tuples.
Was This Post Helpful? 0
  • +
  • -

#4 ste0008   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 20-October 18

Re: Python function many parts need help

Posted 20 October 2018 - 06:05 PM

Using this line of code will it be possible to convert my dictionary keys to tuple
returnDict = {'s' + str(index): [item, len(item)] for index, item in enumerate(input3)}

Was This Post Helpful? 0
  • +
  • -

#5 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 14496
  • View blog
  • Posts: 58,110
  • Joined: 12-June 08

Re: Python function many parts need help

Posted 20 October 2018 - 06:53 PM

What happens when you tryit?
Was This Post Helpful? 1
  • +
  • -

#6 ste0008   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 20-October 18

Re: Python function many parts need help

Posted 20 October 2018 - 07:02 PM

I got it to work for what i needed it for i was just unsure about the keys being tuples
Was This Post Helpful? 0
  • +
  • -

#7 sepp2k   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2662
  • View blog
  • Posts: 4,256
  • Joined: 21-June 11

Re: Python function many parts need help

Posted 21 October 2018 - 12:50 AM

's' + str(index) will produce a string, so the keys in your dictionary will be strings, not tuples. Why do you want them to be tuples and tuples of what?
Was This Post Helpful? 1
  • +
  • -

#8 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 463
  • View blog
  • Posts: 1,468
  • Joined: 27-December 13

Re: Python function many parts need help

Posted 21 October 2018 - 01:29 AM

Small thing: Your function is named 'quiz2' while the required name is 'assignment2'
Comments are good, but don't comment banal code, e.g. this is not good:
print(int(num+7))#prints out user input plus seven

Always use two space before inline comments:
some code  # the in-line comment is preceded by two spaces


The idea is that the function arguments, input2 and input2, are used in the calculation.
You overwrite any input with empty lists (line 16, 17).
This indicates to me that you may not understand how functions work.
Please check up on this.

Your matrix calculation is overly complicated and wrong.
I suggest you abandon nested list comprehensions for now and revert to a more mundane code with two nested for-loops.
In this way it is much easier to control and correct parts of the calculation.
When you have got this right, you may go back to the comprehension format.

For the last question, you again overwrite any input (line 23).
Even without this, your dict will break the string into letters, not words as required.

Give it a new try, and come back here if you need.
Was This Post Helpful? 1
  • +
  • -

#9 baavgai   User is online

  • Dreaming Coder
  • member icon


Reputation: 7288
  • View blog
  • Posts: 15,172
  • Joined: 16-October 07

Re: Python function many parts need help

Posted 21 October 2018 - 01:33 AM

View Postste0008, on 20 October 2018 - 06:19 PM, said:

if all of those tasks are broken up into individual functions they run fine


Then, do that? ;)

Indeed, given the complete disconnectedness of those three tasks, I'd recommend it. So:
def task_1():
    # your code here

def task_2(input1, input2):
    # your code here

def task_3(input3):
    # your code here

# Write a function named assignment2 
# with three inputs
# input 1 is a list of lists representing an nxn matrix 
# input 2 is a list representing an nx1 matrix
# input 3 is a list of strings Your function should complete three tasks: 
def assignment2(input1, input2, input3):
    task_1()
    task_2(input1, input2)
    return task_3(input3)



This also kind of highlights your problem. The assignment says, for task two "You may assume that all inputs are valid and of the correct structure & size". Yet, you are ignoring the inputs and creating your own.
Was This Post Helpful? 1
  • +
  • -

#10 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 463
  • View blog
  • Posts: 1,468
  • Joined: 27-December 13

Re: Python function many parts need help

Posted 21 October 2018 - 01:40 AM

I have merged your two threads.

The assignment do not call for tuples as keys but as values in the dict.
Was This Post Helpful? 1
  • +
  • -

#11 baavgai   User is online

  • Dreaming Coder
  • member icon


Reputation: 7288
  • View blog
  • Posts: 15,172
  • Joined: 16-October 07

Re: Python function many parts need help

Posted 21 October 2018 - 01:51 AM

View Postste0008, on 20 October 2018 - 08:05 PM, said:

Using this line of code will it be possible to convert my dictionary keys to tuple
returnDict = {'s' + str(index): [item, len(item)] for index, item in enumerate(input3)}


Note that this doesn't satisfy task 3. Though it does get you a dict of tuples. Rather than ask the internet, ask the compiler: it's quicker.

A quick test you could write:
def task_3(input3):
    return {'s' + str(index): [item, len(item)] for index, item in enumerate(input3)}

print(task_3(['Alice','Bob','Chuck']))



Result:
{'s0': ['Alice', 5], 's1': ['Bob', 3], 's2': ['Chuck', 5]}



Given the assignment, I'd expect something like:
def task_3(input3):
    def key(i):
        return "s%d" % (i,)
    # the values are tuples with the original string as the first value and the number of words in the string as the second value.
    def value(s):
        # your code here
    return dict((key(i), value(x)) for (i,x) in enumerate(input3))

print(task_3(['Once upon a time', 'the end', 'fin']))



Result:
{'s0': ('Once upon a time', 4), 's1': ('the end', 2), 's2': ('fin', 1)}



Hope this helps.
Was This Post Helpful? 1
  • +
  • -

#12 ste0008   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 20-October 18

Re: Python function many parts need help

Posted 21 October 2018 - 09:30 AM

This assignment was a quiz for my database applications class in Industrial/Systems engineering that we had to complete in 20 minutes. It was then assigned as a homework because the majority of the class fails all quizzes/test the majority of the assignments make no logical sense and haven't helped me learn except by getting help like all of you have done. All the tasks are in one function so they can be passed through a grading program to check for correctness. I am having trouble understanding what user defined function should look like I keep thinking I need to define the arguments(as variables) in the function thanks for pointing that out, I also am having some trouble with understanding dictionaries as in how to turn other objects lists, strings, sets into dictionaries. This is the entirety of my code excessive comments are required

def author():#function used to call my student log info
    return 'ste0008'#return statement that stores my info into function

#Problem 2
    
def inCommon(list1, list2):# define a funciton called inCommon with two inputs list1 and list2
    
    newList = list(set(list1 + list2))#variable new lists takes list1 and two and adds them as sets to remove duplicates this is enclosed in list to convert back to list 
    return(newList)#return function ends fuction and sets newlist variable
    
list1 = [1,2,3,4,5,6]#sample list1 for problem
list2 = [20,3,5,89,1,17]#sample list2 for problem

print(inCommon(list1, list2))#sample print statement calling on function

#Problem 3

def makeIdentity(n):#function makeIdentity has one argument for function that creates an identity matrix
    
    for row in range(0, n):#for statement that evaluates my rows 
        for col in range(0, n):#for statement that evalutates my columns 
  
            # Here end is used to stay in same line 
            if (row == col):#if statement that print my ones for id matrix 
                print(1 , end=" ")#print outs my ones in id matrix
            else:#else will be used to fill in my 0s in id matrix 
                print(0 , end=" ")#print my 0s for my id matrix 
        print(int())#print statement that conversts all back to integers
  
# call function with input to test outputs        
makeIdentity(5)

#problem 4 

def quiz2(input1, input2, input3):#function that has three arguments a nxn matrix a 1xn matrix and a list of strings
        
    
    while True:#while loop used to run my calculation
        try:#try is used to execute my loop
            
            num = input("Enter a number: ")#num is a varible used to define a user input with string asking for number
            num = int(num)#used to convert my varible to integer
            
        except ValueError as e:#used when the value is not a nuber
                    print("You did not enter a number.")#print sting stateing you didn't post number
                    continue#goes back to top of loop
        else:#else used if number is given
            
            print(int(num+7))#prints out user input plus seven
            break#break used to break the loop
    
    result = []#establishing an empty list for task2
    for i in range(len(input1[0])): #this loops through columns of the matrix
        total = 0#set total value equal to zero
        for j in range(len(input2)): #this loops through vector coordinates & rows of matrix
            total += input2[j] * input1[j][i]#total plus the values in for statements are multiplied here
        result.append(total)#append total to result
    print(result)#print statemnet that will return new matrix of size 1xn
   
    #returnDict returns a dictionary with list postions as keys and the original item and lenth of item as key values
    returnDict = {'s' + str(index): [item, len(item)] for index, item in enumerate(input3)}
    #print(returnDict)#return used to output dictionary
    return(returnDict)
a=quiz2([[1,2],[1,3]], [1,2], ['hotdog', 'taco', 'burger'] )#assigning varible to function with input arguments

print(a)#used to test function    
    
   
    


Was This Post Helpful? 0
  • +
  • -

#13 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 463
  • View blog
  • Posts: 1,468
  • Joined: 27-December 13

Re: Python function many parts need help

Posted 21 October 2018 - 09:59 AM

ok, - still problems with the last question.
The dict values are lists, not tuples as required - very easy to fix, just change the square brackets to normal parenthesis.

The values are still counting the letters in a single word; as I read the assignment, you should count word in a word list.
Hint: Look-up the 'split()' function on strings.
Was This Post Helpful? 1
  • +
  • -

#14 ste0008   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 20-October 18

Re: Python function many parts need help

Posted 21 October 2018 - 11:03 AM

Thanks for pointing that out I do believe this works
returnDict = {'s' + str(index): (item, len(str.split(item))) for index, item in enumerate(input3)}

it gives my output with values as tuples and len(str.split(input3)) will count number of words in string from original list
Thanks for the input/tips DK3250
Was This Post Helpful? 1
  • +
  • -

#15 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 463
  • View blog
  • Posts: 1,468
  • Joined: 27-December 13

Re: Python function many parts need help

Posted 21 October 2018 - 11:53 AM

Your solution works but honestly I'm not sure why...

The normal way to use split() is:
my_string = "This is my string"
print(my_string.split(' '))  # generic: <string>.split(<delimiter>) delimiter: separation character.



This is how it is described in the documentation: https://docs.python....split#str.split

Your construction is not in the docs, so I wonder what's going on...?

I would do like this:
returnDict = {'s' + str(index): (item, len(item.split(' '))) for index, item in enumerate(input3)}

This post has been edited by DK3250: 21 October 2018 - 11:53 AM

Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2