简体   繁体   中英

Python Built in f(x) size of arguments

I'm struggling with writing a script that returns the total amount of arguments that are given for the function, the arguments can be either a string, tuple, list or a mapping dictionary. In the script below the test sample only returns 3 when the problem is requesting to count every single argument so id like it to return 7. Any explanation or help is greatly appreciated!

'''Return the length (the number of items) of a sequence (string, tuple or list) or a mapping (dictionary).'''

Write a function that returns the total size of the arguments.

Note: *args denotes a variable argument list, represented by a tuple.

def totSize(*args): 
    return len(args)
print(totSize('abc', (1,), [1,2,3]))

3

I assume, that you want to get length of all arguments and add the lengths together.

Here is the code:

def totSize(*args):
    return sum(map(len, args))

This code first maps len on all arguments ['abc', (1,), [1, 2, 3]] becomes [3, 1, 3] and than sums them. Note that this code assumes, that all argumens can be passed to len

This solution is more general as it works for any object that can be passed to len as well as simple objects like int or float s

def totSize(*args):

    total_length = 0
    for arg in args:
        try:
            total_length += len(arg)
        except TypeError:
            total_length += 1
    return total_length

You can check if the element is Iterable ( str , tuple , list , dict , etc..) and accumulate the total size according to it's type (for non iterable elements, like numerics, add 1 to the total size).

For example:

from collections import Iterable


def totSize(*args):
    total_size = 0
    for i in args:
        if isinstance(i, Iterable):
            total_size += len(i)
        else:
            total_size += 1
    return total_size


print(totSize('abc', (1,), [1, 2, 3]))

You can use len to get the number of items in each arg... sometimes. You also need to cover the case where an argument doesn't have a length

>>> def totSize(*args):
...     count = 0
...     for arg in args:
...         try:
...             count += len(arg)
...         except TypeError:
...             count += 1
...     return count
... 
>>> print(totSize('abc', (1,), [1,2,3]))
7
from collections import Iterable
def totSize(*args):
    return sum(len(x) if isinstance(x, Iterable) else 1 for x in args)

(thanks to L. MacKenzie for reminding about Iterable )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM