Python Forum
Array - Problem with Simple Code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Array - Problem with Simple Code
#1
Hello.
I am having trouble understanding arrays and how to populate them(later). I am just starting out. Right now I get an error message for the code below, yet I copied the program (below) from the book and the classArray (below) is copied from our instructor. I'm trying to learn arrays by trying the most basic code from my book. It is frustrating to get this error. Here is what I have:
from classArray import Array
a = Array(8)

for i in range(len(a)):
    a[i] = i + 1
for item in a:
    print(item)
Here is the class Array (classArray.py)
class Array(object):

    def __init__(self, capacity, fillValue = None):
        """Capacity is the static size of the array.
        fillValue is placed at each position."""
        self._items = list()
        for count in range(capacity):
            self._items.append(fillValue)

    def __len__(self):
        """-> The capacity of the array."""
        return len(self._items)

    def __str__(self):
        """-> The string representation of the array."""
        return str(self._items)

    def __iter__(self):
        """Supports iteration over a view of an array."""
        return iter(self._items)

    def __getitem__(self, index):
        """Subscript operator for access at index."""
        return self._items[index]

    def __setitem__(self, index, newItem):
        """Subscript operator for replacement at index."""
        self._items[index] = newItem
And here is the error message I get:
    for i in range(len(a)):

TypeError: 'Array' object is not callable
Reply
#2
Are you sure that's the code you're running? I copy and pasted your code and didn't get that error.

That's some screwy code your instructor gave you. It's like a list, only less useful. Take this line:

for i in range(len(a)):
This is considered a big no-no in Python. Python allows you to iterate directly over a sequence, which is much better. But the way the Array class is constructed, it eliminates the pythonic ways to populate your initial values (like append or a list comprehension). So you have to use that line.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
The error doesn't seem to relate to the len() call; rather, it appears to be in reference to your call on line 2. Besides, you have the __len__ dunder defined properly so that should work. As written, it worked on my machine. The only change I made was putting Array into the same file as the script, but your import should take care of that.

Can you provide more information about your machine?

On a side note, I recommend that you use a list comprehension to create Array._items:

def __init__(self, capacity, fillValue = None):
    """Capacity is the static size of the array.
    fillValue is placed at each position."""
    self._items = [fillValue for count in range(capacity)]
Reply
#4
I'm running this on Spyder. Maybe I'll try idle.
I pasted the class into the same file as the program and still got the error message.
My machine is Mac OS 10.13.6
Honestly, it's got to be operator error somehow. This is so frustrating, I'm getting a headache from it.
If it works in regular idle I'll post the results.
Thank you all so much for the input.
Pete

It worked great on idle. I don't understand.... Any ideas?
Reply
#5
(Oct-11-2018, 03:52 AM)emerger Wrote: It worked great on idle. I don't understand.... Any ideas?
Is it possible that you have another classArray module with a different Array definition?

Try in Spyder
import classArray
print(classArray.__file__)
BTW, IDLE is considered one of the worst interactive environment.

PS classArray name is un-Pythonic too, class names in Python follow CapWords convention

PPS I would demand refund for the book Wall
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#6
Hello again. This is the second part to my previous question. I've learned a bit about arrays, but the solution to this array problem still alludes me, so I thought I'd ask for help again here. Bottom line is, my instructor wants us to understand arrays (old skool). He says its like looking under the 'hood' of lists. So here's what I've got (below). Here's my array class that was given to me by him. I believe it was designed to mimic a 'restrictive list' to appear array-like. I've enclosed my .csv file and my instructor's directions. Right now all I want to do is populate the array with the info from the .csv file. "Step 1: Add a menu option to load students from a CSV file" (no problem). This should create an Array of Student objects which contain the relevant data."(problem) I figure I can figure out steps 2 and 3 on my own. At present I'm scouring You Tube for any information on arrays so I can teach myself.
class Array(object):
    """Represents an array."""

    def __init__(self, capacity, fillValue = None):
        """Capacity is the static size of the array.
        fillValue is placed at each position."""
        self._items = list()
        for count in range(capacity):
            self._items.append(fillValue)

    def __len__(self):
        """-> The capacity of the array."""
        return len(self._items)

    def __str__(self):
        """-> The string representation of the array."""
        return str(self._items)

    def __iter__(self):
        """Supports iteration over a view of an array."""
        return iter(self._items)

    def __getitem__(self, index):
        """Subscript operator for access at index."""
        return self._items[index]

    def __setitem__(self, index, newItem):
        """Subscript operator for replacement at index."""
        self._items[index] = newItem
This is my code. I'm trying to populate an array with the data from a .csv file (bottom of page)
    #a = Array(8)
    lyst1 = []
    with open("student_advisees_testdata.csv",'r') as csv_file:
        csv_reader = csv.reader(csv_file)
        next(csv_reader)

        for line in csv_file:
            line = line.split(',')
            index = 0
            for word in line:
                lyst2 = []
                lyst2.append(word)
                lyst1.append(lyst2)
   
    a = Array(8,lyst1)
    print(a)
.csv file:
ID,First Name,Last Name,Program,Start Date,Adv Last Name,Most Recent Term,GPA
104,Todd,Jeffries,B25590S,01/11/16,Willy,2017SU,3.9
047,George,Evans,B25590C,08/21/17,Willy,2017FA,3.1
257,Jennifer,Reynolds,B25590N,01/17/17,Willy,2017FA,2.9
1707,Twan,Jelens,B25590C,08/15/16,Smith,2017SP,3.3
1865,Paul,Knapp,B25590S,08/15/16,Willy,2018FA,3.4
2104,Phyllis,Cashwell,B25590C,08/15/16,Smith,2017SP,3.25
2214,Beeman,Ciani,B25590N,08/15/16,Willy,2017SP,2.9
2215,Gertrude,Carmella,B25590C,08/15/16,Willy,2018SP,3.8
2838,Morty,Balzano,B25590C,05/30/17,Willy,2018FA,2.7
3104,Steve,Abrams,B25590S,08/21/17,Willy,2018FA,3.15
Reply
#7
The second value to Array is the value that gets put in each index of Array. So you don't want to put the list of items there, it will just copy the list into each item of the array.

You need to assign by index, because that is the only option your teacher has given you. Say you have a list (which is what CSVReader should be giving you, you shouldn't have to split it to get a list). The way to put it into an array would be:

student = Array(len(data_list))
for index in range(len(data_list)):
    student[index] = data_list[index]
That's horrid code. You could use enumerate to make it more pythonic. Enumerate takes a sequence and allows you to iterate over the indexes of the sequence and the items of the sequence.

student = Array(len(data_list))
for index, item in enumerate(data_list):
    student[index] = item
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
Ok-Got it!.
So the result (output) is now considered an array? The output 'Array' looks the same as the list output.
    data_list = []
    with open("student_advisees_testdata.csv",'r') as csv_file:
        csv_reader = csv.reader(csv_file)
        next(csv_reader)
        for line in csv_file:
            line = line.split(',')
            data_list.append(line)
    print(data_list)
   
        
#    student = Array(len(data_list))
#    index = 0
#    for index in range(len(data_list)):
#        student[index] = data_list[index]
#    print(student)
    
    student = Array(len(data_list))
    for index, item in enumerate(data_list):
        student[index] = item 
    print(student)
data_list:
[['104', 'Todd', 'Jeffries', 'B25590S', '1/11/16', 'Williams', '2017SU', '3.9\n'], ['47', 'Morty', 'Evans', 'B25590C', '8/21/17', 'Williams', '2017FA', '3.1\n'], ['257', 'Jennifer', 'Reynolds', 'B25590N', '1/17/17', 'Williams', '2017FA', '2.9\n'], ['1707', 'Twan', 'Jelens', 'B25590C', '8/15/16', 'Williams', '2017SP', '3.3\n'], ['1865', 'Paul', 'Knapp', 'B25590S', '8/15/16', 'Williams', '2018FA', '3.4\n'], ['2104', 'Michelle', 'Cashwell', 'B25590C', '8/15/16', 'Smith', '2017SP', '3.25\n'], ['2214', 'Bruce', 'Ciani', 'B25590N', '8/15/16', 'Williams', '2017SP', '2.9\n'], ['2215', 'Mike', 'Carmella', 'B25590C', '8/15/16', 'Williams', '2018SP', '3.8\n'], ['2838', 'Gene', 'Balzano', 'B25590C', '5/30/17', 'Williams', '2018FA', '2.7\n'], ['3104', 'Steve', 'Abrams', 'B25590S', '8/21/17', 'Williams', '2018FA', '3.15']]
student(Array?)
[['104', 'Todd', 'Jeffries', 'B25590S', '1/11/16', 'Williams', '2017SU', '3.9\n'], ['47', 'Morty', 'Evans', 'B25590C', '8/21/17', 'Williams', '2017FA', '3.1\n'], ['257', 'Jennifer', 'Reynolds', 'B25590N', '1/17/17', 'Williams', '2017FA', '2.9\n'], ['1707', 'Twan', 'Jelens', 'B25590C', '8/15/16', 'Williams', '2017SP', '3.3\n'], ['1865', 'Paul', 'Knapp', 'B25590S', '8/15/16', 'Williams', '2018FA', '3.4\n'], ['2104', 'Michelle', 'Cashwell', 'B25590C', '8/15/16', 'Smith', '2017SP', '3.25\n'], ['2214', 'Bruce', 'Ciani', 'B25590N', '8/15/16', 'Williams', '2017SP', '2.9\n'], ['2215', 'Mike', 'Carmella', 'B25590C', '8/15/16', 'Williams', '2018SP', '3.8\n'], ['2838', 'Gene', 'Balzano', 'B25590C', '5/30/17', 'Williams', '2018FA', '2.7\n'], ['3104', 'Steve', 'Abrams', 'B25590S', '8/21/17', 'Williams', '2018FA', '3.15']]
Reply
#9
Yeah, they look the same. That's another screwy thing your teacher did. You'll note in the __str__ and __repr__ methods of Array that it just uses the str and repr of _items, which is a list. So the text versions of Array look exactly the same as the text versions of list. So you can't tell them apart.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with simple code JacobSkinner 1 309 Mar-18-2024, 08:08 PM
Last Post: deanhystad
  I have a code which is very simple but still I cannot detect what's wrong with it max22 1 476 Nov-07-2023, 04:32 PM
Last Post: snippsat
  A simple problem, how best to solve it? SuchUmami 2 717 Sep-01-2023, 05:36 AM
Last Post: Pedroski55
  help me simple code result min and max number abrahimusmaximus 2 901 Nov-12-2022, 07:52 AM
Last Post: buran
  Simple encoding code ebolisa 3 1,436 Jun-18-2022, 10:59 AM
Last Post: deanhystad
  How to solve this simple problem? Check if cvs first element is the same in each row? thesquid 2 1,222 Jun-14-2022, 08:35 PM
Last Post: thesquid
  How would you (as an python expert) make this code more efficient/simple coder_sw99 3 1,787 Feb-21-2022, 10:52 AM
Last Post: Gribouillis
  Simple code question about lambda and tuples JasPyt 7 3,296 Oct-04-2021, 05:18 PM
Last Post: snippsat
Big Grin question about simple algorithm to my problem jamie_01 1 1,665 Oct-04-2021, 11:55 AM
Last Post: deanhystad
  My simple code don't works !! Nabi666 1 1,601 Sep-06-2021, 12:10 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

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