Someone please take a look at my Python syntax? [c

2019-10-02 01:13发布

问题:

Can someone please explain to me what is missing in my code? I have been looking at solutions on the internet and I found a template that I thought would be correct but its still giving me errors. Anyone know what I am doing wrong?

  • Create a function manipulate_data that does the following:

  • Accepts as the first parameter a string specifying the data structure to be used "list", "set" or "dictionary". Accepts as the second parameter the data to be manipulated based on the data structure specified (e.g [1, 4, 9, 16, 25]) for a list data structure.

  • Based off the first parameter return the reverse of a list, OR add the items "ANDELA", "TIA" and "AFRICA" to the set, or return the resulting set as keys of a dictionary.

def manipulate_data(kind, data):
    if kind == "list":
        for data in [1, 4, 9, 16, 25]:
            return data.reverse()

    elif kind == "set":
        for data in {"f", "g", "h", "i", "j"}:
            data.add("ANDELA")
            data.add("TIA")
            data.add("AFRICA")
            return data

    elif kind == "dictionary":
        for data in  {"nissan": 23, "audi": 15, "mercedes": 3, "volvo": 45}:
            return data.key()

回答1:

It looks like you've been give a classroom exercise to manipulate data differently based on its type. The first thing I would do is toss the "type" parameter as it's trivial to figure out the type in a language like Python. Your solution hard codes data that should have been passed in as the "data" parameter. Making these fixes, we get something like:

def manipulate_data(data):
    if type(data) is list:
        data.reverse()
        return data
    elif type(data) is set:
        data.add("ANDELA")
        data.add("TIA")
        data.add("AFRICA")
        return data
    elif type(data) is dict:
        return data.keys()
    return data  # just return anything else

Which we can test by passing in the three different types of data:

>>> manipulate_data([1, 4, 9, 16, 25])
[25, 16, 9, 4, 1]
>>> 
>>> manipulate_data({"f", "g", "h", "i", "j"})
{'h', 'f', 'AFRICA', 'ANDELA', 'g', 'i', 'TIA', 'j'}
>>> 
>>> manipulate_data({"nissan": 23, "audi": 15, "mercedes": 3, "volvo": 45})
dict_keys(['audi', 'volvo', 'mercedes', 'nissan'])
>>> 

A statement like return data.reverse() doesn't make sense as the .reverse() method modifies its object and these methods generally don't return anything. Another way to do this line is return reversed(data) which would copy and reverse the data, not change the original.



回答2:

This one works according to the question the function only takes in 2 parameters:

def manipulate_data(data_type=None, data=None):
    if data_type is 'list':
        return data[-1::-1]
    if data_type == 'set':
        return set.union(data, ["ANDELA", "TIA", "AFRICA"])
    if data_type == 'dict':
        return [key for key, item in data.items()]