Python Forum
How to pass value from method to function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to pass value from method to function
#1
Hi there,

I have been tasked with writing a function that returns the length of an unknown list. I have successfully done the algorithm for it, and it works, I just can't work out how to pass the value from the class method to my function in the format specified.

The Class and the interface cannot be modified, so using len(my_list) is not what they are looking for. posted here is the Class that I cannot modify, a test that I am to use to test the function, and then finally, my function that I am trying to write. I just need to know how I am supposed to get the value into my function, the closest I have come to is getting the memory location of the List object which is of no use to me.


Here is the Class, this code cannot be modified:
[code]class MyClass(object):
    def __init__(self, l):
        self._list = l

    def get(self, index):
        try:
            return self._list[index]
        except IndexError:
            return None[/code]
here is a test case that I am to use:
[code]def test_large_list():
    s_list = My_Class([i for i in range(0, 100000)])
    assert len(s_list._list) == list_length(s_list)[/code]
and here is the function that I have written, it works nicely, but as you can see, the first line of my function was my way of testing my algorithm, I am now stuck as I can't write any more tests until I can get the values properly into my function:

[code]#!/usr/bin/python3

#def list_length(single_method_list):         This is what I am supposed to work with

from another_file import MyClass


def my_function():      # This is how I have done it and it works.
    a_list = MyClass([i for i in range(0, 234589)])

    for x in (10**p for p in range(1, 8)):
        if a_list.get(x):
            print("More than", x)
            first = x
        else:
            print("Less than", x)
            last = x
            break

    answer = False
    while not answer:
        result = (first + last)/2
        result = int(round(result))
        print(result)
        if s_list.get(result):
            first = result
            print('first', result)
        else:
            last = result
            print('last', result)

        if s_list.get(result) and not s_list.get(result + 1):
            answer = True
            print(result + 1)


my_function()[/code]
For some further clarification, the class that has been written for me to use, I would not write in this way, I would not use the word _list as a variable name as it is a python keyword I think, neither would I use the lower case "L" as a variable name as it looks too much like the number 1 and is not clear.
Reply
#2
No way this is production code, looks more like homework assignment with stupid limitations
Reply
#3
Correct in a way, It's a test that I have done, and I am now trying to find out how to do the bit I failed at. If it helps to show that I am not trying to cheat, I can post the algorithm, I have coded however, it is just a very simple one of an initial loop with sending a test value that increments by a factor of 10 and then a binary search to find the last number. It is the OOP side of things I am having difficulty with. In my opinion, the rest of the code is not necessary and would add confusion to my original question.
Reply
#4
Stop writing classes

what is the purpose to write a class with the only purpose to return an element of a list that you pass as argument at the time of instantiation?
if that is some weird test question


from single_method_list import SingleMethodList


def list_length(single_method_list):      # This is how I have done it and it works.
   single_method_list = MyClass([i for i in range(0, 234589)])

   for x in (10**p for p in range(1, 8)):
       if single_method_list.get(x):
           print("More than", x)
           first = x
       else:
           print("Less than", x)
           last = x
           break

   answer = False
   while not answer:
       result = (first + last)/2
       result = int(round(result))
       print(result)
       if single_method_list.get(result):
           first = result
           print('first', result)
       else:
           last = result
           print('last', result)

       if single_method_list.get(result) and not single_method_list.get(result + 1):
           answer = True
           print(result + 1)


a_list = SingleMethodList(list(range(0, 234589))) # python3
#a_list = SingleMethodList(range(0, 234589)) #python2 - I don't understand why test case use list comprehension from xrange, instead of simply range
it looks like you use python3 and test case is using python2. Note - I just adjusted your code, did not correct algorithm or code/style
Reply
#5
I didn't, I really tried to clarify my issue, the class is not to be altered, I am expected to interact with the class.

Yes you are correct about the python 3 and python 2, I forgot to edit it in this post.

On closer inspection, I am wondering if this is my problem, as I can't work out how you spotted it as python2
Reply
#6
test case is using xrange. that is strictly python 2 and returns generator, while range returns list. In python 3 range returns generator and xrange is not available

your function should be called list_length and must take instance of SingleMethodList class. That's why you need to create the instance outside the function and pass it as argument. Using your own algorithm list_length should return the len of the list. However at the moment it just prints some info and at the end always return None (i.e. 'the default' return value from a function). If it remain so, test case will fail always.
Reply
#7
Ok, I've editted it, I was aware of the xrange, and also the single method function. I have been trying to solve this one problem of how I get this value into my function for four days now, what I wrote there, I completed in 20 minutes, I just need to know how to get that integer into the function so that I can use the tests that were supplied. I really thought there was going to be a simple answer to this, as I thought python used classes and methods all the time, I am just trying to learn about them.

Is it actually really complex to pass a variable to a function then?
Reply
#8
Did you even look at how I changed your function?
Reply
#9
I'm really confused now, I get sent the list, I only had that first line in to generate what is supposed to be an unknown to me. Excuse me, I am really shaky on this. I thought, that when you do:
my_function(some_variable):
That meant that some variable was being passed to the function from outside the function. eg:
x = 5

result = my_function(x)
so that:
def my_function(some_variable):
    return 5 + some_variable
would return 10, I don't know how to take that first line that I wrote that generates a list out of the function, I want just the int that it returns and for it not to be in the function at all. But all I get with everything I have tried is either an error, or it returns a memory location or an empty list.

I think the main problem is that the rest of my code gives the impression I am more advanced than I am, I think what I am asking is the most basic of OOP that I can't understand. I was really expecting just a simple line of syntax that I would add in. Currently, when I pass this variable to my_function it returns a memory location when I want the int that the function is returning.
Reply
#10
single_method_list.py
class SingleMethodList(object):
    def __init__(self, l):
        self._list = l

    def get(self, index):
        try:
            return self._list[index]
        except IndexError:
            return None
your_file.py
from single_method_list import SingleMethodList

# that's the function that test case expect
def list_length(single_method_list):
   for x in (10**p for p in range(1, 8)):
       if single_method_list.get(x):
           print("More than", x)
           first = x
       else:
           print("Less than", x)
           last = x
           break

   answer = False
   while not answer:
       result = (first + last)/2
       result = int(round(result))
       print(result)
       if single_method_list.get(result):
           first = result
           print('first', result)
       else:
           last = result
           print('last', result)

       if single_method_list.get(result) and not single_method_list.get(result + 1):
           answer = True
           return result + 1 # you need to return the len of the single_method_list (that is the argument)

#your test case
def test_large_list():
    s_list = SingleMethodList([i for i in range(0, 100000)]) # here s_list is instance of SingleMethodList class
    assert len(s_list._list) == list_length(s_list) # here test case asserts what list_length return is correct len of the s_list (i.e. the instance of SingleMethodList class). note how s_list is passed as argument to list length

#run the test
test_large_list() # if your your function is incorrect you will get AssertionError, if it is correct - nothing will happen
Output:
('More than', 10) ('More than', 100) ('More than', 1000) ('More than', 10000) ('Less than', 100000) 55000 ('first', 55000) 77500 ('first', 77500) 88750 ('first', 88750) 94375 ('first', 94375) 97187 ('first', 97187) 98593 ('first', 98593) 99296 ('first', 99296) 99648 ('first', 99648) 99824 ('first', 99824) 99912 ('first', 99912) 99956 ('first', 99956) 99978 ('first', 99978) 99989 ('first', 99989) 99994 ('first', 99994) 99997 ('first', 99997) 99998 ('first', 99998) 99999 ('first', 99999)
actually you don't need to print all this info
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to pass encrypted pass to pyodbc script tester_V 0 857 Jul-27-2023, 12:40 AM
Last Post: tester_V
  i want to use type= as a function/method keyword argument Skaperen 9 1,860 Nov-06-2022, 04:28 AM
Last Post: Skaperen
Question How to pass a method as argument in an another method? anilanvesh 6 2,738 Sep-30-2021, 10:18 PM
Last Post: deanhystad
  Regex - Pass Flags as a function argument? muzikman 6 3,591 Sep-06-2021, 03:43 PM
Last Post: muzikman
  Possible to dynamically pass arguments to a function? grimm1111 2 2,187 Feb-21-2021, 05:57 AM
Last Post: deanhystad
  Building a method name in a function ffgth 9 3,199 Oct-19-2020, 01:21 PM
Last Post: buran
  Do I have to pass 85 variables to function? Milfredo 10 4,299 Sep-26-2020, 10:13 PM
Last Post: Milfredo
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 2,557 Sep-07-2020, 08:02 AM
Last Post: perfringo
  Pass integers to datetime.date function florian 3 2,719 Jul-18-2020, 04:43 AM
Last Post: scidam
  How to pass multiple arguments into function Mekala 4 2,451 Jul-11-2020, 07:03 AM
Last Post: Mekala

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020