当前位置:网站首页>Two quality interview questions

Two quality interview questions

2020-12-07 20:27:18 Se7eN_ HOU

Words first : Before the shortage , Your advice are most welcome

One 、 Multi level dictionary parsing problem

Original title

{
  "Count":5,
  "Items":
  [
    {
          "name":{"string":"a"},
        "email":{"string":"abc@163.com"},
        "friends":
          [
            {
              "friend1": {
                "name": {
                  "string": "name1"
                },
                "sex": {
                  "int": 1
                },
                "addr": {
                  "string": "addr1"
                }
              }
            }
          ],
        "moreinfo":{
            "Desc1":{"string":"aaaa"},
            "Desc2":{"int":22},
            "Desc3":{"list":["ddddd","11111"]}
        }
    }
  ]
}

The above json file , Turn into python Content , And get rid of unnecessary data such as ( Contains the corresponding data types such as :string,int,list) And then it became

{
  "Count":5,
  "Items":
  [
    {
          "name":"a",
        "email":"abc@163.com",
        "friends":
          [
            {
              "friend1": {
                "name": "name1"
                "sex":  1
                "addr":  "addr1"
              }
            }
          ],
        "moreinfo":{
            "Desc1":"aaaa",
            "Desc2":22,
            "Desc3":"ddddd","11111"}
        }
    }
  ]
}

Their thinking : Using recursion to solve the node problem of multi-layer dictionary , There are two forms of child nodes: list and dictionary , So both forms are recursive ,

Solution code

import json

#  Modified function 
def modify(dic):
    #  Make sure it's a dictionary , I don't use it here try-except Make fault tolerance , It's just for the realization of the requirements 
    if isinstance(dic,dict):
        #  Variable dictionary key and value
        for key,val in dic.items():
            #  If there are multiple dictionaries nested here , Sublayers are mainly dictionaries or lists , Here, we mainly focus on the sublayer: dictionary and list 
            if isinstance(val,dict):
                #  If val It's a dictionary , And the length is 1, The description is the innermost dictionary , It's a place to deal with 
                if len(val) == 1:
                    #  Will the inner Dictionary of val Assigned to the next level key, The requirements of the project 
                    dic[key]=list(val.values())[0]
                #  If it's not the innermost layer , Continue to recursive 
                modify(val)
            #  The inner data is in the case of lists 
            elif isinstance(val,list):
                if len(val)>0:
                    for _dic in val:
                        #  In the list, the dictionary continues to recurse 
                        modify(_dic)
                      
if __name__ == '__main__':

    with open('./test_json.json', 'r') as fp:
        json_str = fp.read()

    json_dic = json.loads(json_str)
    print(' Print before modification *********************')
    print(json_dic)
    modify(json_dic)
    print(' Print after modification *********************')
    print(json_dic)

Print the results

 Print before modification *********************
{'Count': 5, 'Items': [{'name': {'string': 'a'}, 'email': {'string': 'abc@163.com'}, 'friends': [{'friend1': {'name': {'string': 'name1'}, 'sex': {'int': 1}, 'addr': {'string': 'addr1'}}}], 'moreinfo': {'Desc1': {'string': 'aaaa'}, 'Desc2': {'int': 22}, 'Desc3': {'list': ['ddddd', '11111']}}}]}
 Print after modification *********************
{'Count': 5, 'Items': [{'name': 'a', 'email': 'abc@163.com', 'friends': [{'friend1': {'name': 'name1', 'sex': 1, 'addr': 'addr1'}}], 'moreinfo': {'Desc1': 'aaaa', 'Desc2': 22, 'Desc3': ['ddddd', '11111']}}]}

Two 、mongodb Basic use of

Original title :

Mongodb  Inquire about :
Db.msg.find()
{ "_id" : ObjectId("5f96ef6c1fb5b9e52cd23179"), "msgId" : 1696261644, "fromUserName" : "user1", "toUserName" : "user2", "msgType" : 1, "content" : "ufne", "newMsgId" : NumberLong("4690548300089373689"), "createTime" : 1603727095 }
{ "_id" : ObjectId("5f96ef6c1fb5b9e52cd2317a"), "msgId" : 1696261645, "fromUserName" : "user2", "toUserName" : "user1", "msgType" : 10002, "content" : "<sysmsg type=\"ClientCheckConsistency\"</ClientCheckConsistency></sysmsg>", "newMsgId" : NumberLong("4429536039473582128"), "createTime" : 1603727095 }
{ "_id" : ObjectId("5f96ef6c1fb5b9e52cd2317b"), "msgId" : 1696261647, "fromUserName" : "user1", "toUserName" : "user2", "msgType" : 1, "content" : "Hello", "newMsgId" : NumberLong("1453640785042681328"), "createTime" : 1603727109 }
{ "_id" : ObjectId("5f96ef6c1fb5b9e52cd2317c"), "msgId" : 1696261648, "fromUserName" : "user2", "toUserName" : "user1", "msgType" : 1, "content" : "gggg", "newMsgId" : NumberLong("4776642146216801785"), "createTime" : 1603727130 }
….

 With user1,user2 For example , Need to get  user1, user2  The last message in a chat message .
 Construct a method , Get the query record , The last chat record of the specified user .
Def get_last_msg(user:str) -> msg_dict:dict:

 In addition, for the scene of getting the last message , Propose solutions .

The data is in mongodb Shown in

 

 

  The code is

import pymongo
#  link mongodb
pymongo_client = pymongo.MongoClient('mongodb://root:123456@127.0.0.1:27017')
#  Linked database 
pymongo_db = pymongo_client['test_db']
#  Link table 
pymongo_table = pymongo_db.test_table



def get_last_msg(user):
    #  Pipeline conditions 
    pipeline = [
        #  Search according to the users passed in 
        {'$match':{'fromUserName':user}},
        #  Because the last one , So flashbacks are more convenient 
        {'$sort': {'createTime': -1,}},
        #  After flashback, take out the first one 
        {'$limit':1}
        
    ]
    #  Interlude 
    ret = pymongo_table.aggregate(pipeline)
    ret1 = [u for u in ret]
    #  Return results 
    return ret1[0]

msg = get_last_msg('user2')
#  Print verification 
print(msg)

Print the results

{'_id': ObjectId('5fce176c3dcc6560be446156'), 'msgId': 1696261648.0, 'fromUserName': 'user2', 'toUserName': 'user1', 'msgType': 1.0, 'content': 'gggg', 'newMsgId': '"4776642146216801785"', 'createTime': 1603727130}

  

版权声明
本文为[Se7eN_ HOU]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207202657908y.html