python isinstance(), stack,判断list, dict, tuple为空

2023-05-16

Problem:

Nikola likes to categorize everything in sight. One time Stephan gave him a label maker for his birthday, and the robots were peeling labels off of every surface in the ship for weeks. He has since categorized all the reagents in his laboratory, books in the library and notes on the desk. But then he learned about pythondictionaries, and categorized all the possible configurations for Sophia’s drones. Now the files are organized in a deep nested structure, but Sophia doesn’t like this. Let's help Sophia to flatten these dictionaries.

Python dictionaries are a convenient data type to store and process configurations. They allow you to store data by keys to create nested structures. You are given a dictionary where the keys are strings and the values are strings or dictionaries. The goal is flatten the dictionary, but save the structures in the keys. The result should be the a dictionary without the nested dictionaries. The keys should contain paths that contain the parent keys from the original dictionary. The keys in the path are separated by a "/". If a value is an empty dictionary, then it should be replaced by an empty string (""). Let's look at an example:

{
    "name": {
        "first": "One",
        "last": "Drone"
    },
    "job": "scout",
    "recent": {},
    "additional": {
        "place": {
            "zone": "1",
            "cell": "2"}
    }
}

The result will be:

{"name/first": "One",           #one parent
 "name/last": "Drone",
 "job": "scout",                #root key
 "recent": "",                  #empty dict
 "additional/place/zone": "1",  #third level
 "additional/place/cell": "2"}

Sophia has already written the code for this task, but it has a bug.You need to find and fix this bug.

Input: An original dictionary as a dict.

Output: The flattened dictionary as a dict.

Precondition:
Keys in a dictionary are non-empty strings.
Values in a dictionary are strings or dicts.
root_dictionary != {}


code:

def flatten(dictionary):
    stack = [((), dictionary)]
    result = {}
    while stack:
        path, current = stack.pop()
        for k, v in current.items():                
            if isinstance(v, dict):
                if v == {}:
                    result["/".join((path + (k,)))] = ""                      
                else:                
                    stack.append((path + (k,), v))        
            else:
                result["/".join((path + (k,)))] = v    
    return result

check:

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert flatten({"key": "value"}) == {"key": "value"}, "Simple"
    assert flatten(
        {"key": {"deeper": {"more": {"enough": "value"}}}}
    ) == {"key/deeper/more/enough": "value"}, "Nested"
    assert flatten({"empty": {}}) == {"empty": ""}, "Empty value"
    assert flatten({"name": {
                        "first": "One",
                        "last": "Drone"},
                    "job": "scout",
                    "recent": {},
                    "additional": {
                        "place": {
                            "zone": "1",
                            "cell": "2"}}}
    ) == {"name/first": "One",
          "name/last": "Drone",
          "job": "scout",
          "recent": "",
          "additional/place/zone": "1",
          "additional/place/cell": "2"}

扩展:

1. 判断类型

isinstance(object, classinfo) 判断实例是否是这个类或者object是变量

  1. isinstance说明如下:  
  2.     isinstance(object, class-or-type-or-tuple) -> bool  
  3.       
  4.     Return whether an object is an instance of a class or of a subclass thereof.  
  5.     With a type as second argument, return whether that is the object's type.  
  6.     The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for  
  7.     isinstance(x, A) or isinstance(x, B) or ... (etc.).  
  8. 其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。若对象的类型与参数二的类型相同则返回True。若参数二为一个元组,则若对象类型与元组中类型名之一相同即返回True。 
    1. >>>isinstance(lst, list)  
    2. True  
    3.   
    4. >>>isinstance(lst, (int, str, list) )  
    5. True  

isinstance(obj, basestring)等价于isinstance(obj, (str, unicode))


2. 判断为空

m = []

m = ()

m = {}

>>> if m

>>> if not m 


3. stack:

Stack() 建立一个空的栈对象
push() 把一个元素添加到栈的最顶层
pop() 删除栈最顶层的元素,并返回这个元素
peek() 返回最顶层的元素,并不删除它
isEmpty() 判断栈是否为空
size() 返回栈中元素的个数

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python isinstance(), stack,判断list, dict, tuple为空 的相关文章

随机推荐