1

The problem is to count the elements in a list without using len(list).

My code:

def countFruits(crops):
  count = 0
  for fruit in crops:
    count = count + fruit
  return count

The error was: 'int' and 'str'

These are supposed to be the test cases that should run the program.

crops = ['apple', 'apple', 'orange', 'strawberry', 'banana','strawberry', 'apple']
count = countFruits(crops)
print count
7
John La Rooy
  • 263,347
  • 47
  • 334
  • 476
  • In the first time through your for loop, you're asking Python to add `0` and `'apple'`. Python doesn't know how to do this, so it throws an error. Can you do this so you're only adding numbers together? – Sam Mussmann May 30 '13 at 02:33
  • `count = count + 1` or simply `count +=1` – root May 30 '13 at 02:36
  • 1
    `count = crops.__len__()`?. (unless you think that's cheating :D) – kampu May 30 '13 at 02:42
  • I think there's the subtle issue of when you're actually **counting** the crops vs determining the size of the list – Ryan Haining May 30 '13 at 02:49
  • 1
    @gnibbler The point was to *not* use `len()`, so using `__len__` instead *could* be an allowed alternative. – poke May 30 '13 at 03:01

6 Answers6

1

Try this:

def countFruits(crops):
  count = 0
  for fruit in crops:
    count = count + 1
  return count

To calculate the length of the list you simply have to add 1 to the counter for each element found, ignoring the fruit. Alternatively, you can write the line with the addition like this:

count += 1

And because we're not actually using the fruit, we can write the for like this:

for _ in crops:

Making both modifications, here's the final version of the implementation:

def countFruits(crops):
    count = 0
    for _ in crops:
        count += 1
    return count
Óscar López
  • 215,818
  • 33
  • 288
  • 367
1

You need simple replace wrong expression: count=count+fruit

def countFruits(crops):
  count = 0
  for fruit in crops:
    count += 1
  return count

expression for x in y, get x how object from list y, to get number you can use function enumerate(crops), return object and number. Other way to use:

countFruits = lambda x: x.index(x[-1])+1

but the best way is use len() you can resign name:

countFruits = len
VikNik
  • 11
  • 3
1

Using Recursion and the Ternary operator:

def count_elements(list_):
    return 1 + count_elements(list_[1:]) if list_ else 0

print(count_elements(['apple', 'apple', 'orange', 'strawberry']))

Output:

4
Community
  • 1
  • 1
aldeb
  • 5,378
  • 3
  • 22
  • 46
  • 1
    That’s very ineffective as `iterable[1:]` will continuously create new list objects causing the old ones to be thrown away (not to mention the overhead for recursion itself). Also `iterable` is the wrong term when you’re using *list* access (a list is iterable, but an iterable must not be a list). – poke May 30 '13 at 03:04
  • @poke: I changed `iterable` to `list_`. I know that's not effective. Since the OP can't use `len`, I assume that this is an exercise in order to learn python programming. So I wanted to propose a way that use features that perhaps the OP didn't know about (Recursion...), and that was not already proposed. – aldeb May 30 '13 at 03:11
1
def count(x):
    return sum(1 for _ in x)

The above is fairly efficient; the comprehension isn't expanded into memory before taking the sum, but accumulated for each element generated. That is to say: sum([1 for _ in x]) would be much worse.

Can't imagine why you don't want to use len()...the only reason I can imagine is if the iterable is a generator and you don't want to eat the elements, in which case just add a counter to the loop (via enumerate makes it clean, but maybe a bit hidden.

for i, item in enumerate(my_generator):
     do_stuff(item)

print 'Did things to {} items'.format(i)
Nick T
  • 22,202
  • 10
  • 72
  • 110
0

As the usage of len() is forbidden, I assume the real meaning of the task you are given is to learn different techniques within python.

a solution using higher order function with reduce(), lambda and list comprehensions — so basically most of the python goodies…

def countFruits(crops):
    return reduce(lambda x, y: x+y, [1 for _ in crops])

crops = ['apple','orange', 'banana'] 
print countFruits(crops)
vikingosegundo
  • 51,126
  • 14
  • 131
  • 172
0
def countFruits(crops):
    return max(enumerate(crops, 1))[0]
John La Rooy
  • 263,347
  • 47
  • 334
  • 476