Beispiel #1
0
 def __init__(self):
     """
     Initialize your data structure here.
     """
     self.follows = dt(list)
     self.posts = dt(dq)
     self.newsfeed = dt(dq)
     self.cnt = 0
Beispiel #2
0
def calculateModifiedZScore(graph, nodeOutWeightDict):
    '''
    Modified Z Score = A /  B ; where
    A = ∑ outweights  - ∑ (1 - inweights * 𝛃)
    B = √ (∑ outweights  + ∑ (1 - inweights * 𝛃)) ; 𝛃 is a parameter

    '''

    modifiedZScoreDict = dt(lambda: float('-inf'))

    # print('printing the user relationship graph..')
    # print(graph.edges())

    nodeInWeightDict = dt(lambda: 0.0)

    graph2 = graph.reverse()
    for eachNode in graph2.nodes():
        for eachKey in graph2[eachNode]:
            # print(f"from {eachNode} to {eachKey}")
            try:
                nodeInWeightDict[
                    eachNode] += 1 - graph[eachNode][eachKey][0]['weight']
            except KeyError:
                pass
                # print(f'keyError for {eachNode}')
                # nodeInWeightDict[eachNode] = 0.0

    for k, v in nodeOutWeightDict.items():
        try:
            modifiedZScoreDict[k] = (nodeOutWeightDict[k] - nodeInWeightDict[k]
                                     ) * 1.0 / math.sqrt(nodeOutWeightDict[k] +
                                                         nodeInWeightDict[k])

        except:
            pass
            # print(f'keyError for {k} in modifiedZScoreDict')
            # modifiedZScoreDict[k] = 0.0

    #
    # lis = ['227', '4348', '10008', '7', '35762', '5', '46355', '3', '87381', '59472', '160951', '49943', '24373', '12135', '92', '69933', '43434', '6094', '1', '49115', '0', '68973', '52138', '39382', '2', '15998', '6297', '61', '72520', '31183', '76024', '29454']
    # print("checking in the new graph now...")
    # for _ in lis :
    #     if int(_) in graph.nodes() :
    #         print(f'{_} is present in the graph.')
    '''
    sorting the dictionary now..
    '''

    sortedModifiedZScoreDict = sorted(modifiedZScoreDict.items(),
                                      key=lambda obj: obj[1],
                                      reverse=True)

    # print('sorted dictionary based on z score is below: \n*10')
    # print(sortedZScoreDict)

    return sortedModifiedZScoreDict
    def getKth(self, lo: int, hi: int, k: int) -> int:

        # Time: O(N) where N is the range of numbers from lo to hi [lo, hi].
        # Space: O(N)

        def solve(n):
            nonlocal d
            if d[n]:
                return d[n]

            if n % 2:
                d[n] = 1 + solve(n * 3 + 1)
            else:
                d[n] = 1 + solve(n // 2)
            return d[n]

        k -= 1
        d = dt(int)
        d[1] = 1
        ret = list()

        for i in range(lo, hi + 1):
            d[i] = solve(i)
            ret.append((d[i] - 1, i))

        ret.sort()

        return ret[k][1]
Beispiel #4
0
    def equal(self, A):
        d = dt(list)
        l = len(A)
        sol = []
        ans = []
        for i in range(l):
            for j in range(i + 1, l):
                Sum = A[i] + A[j]
                if Sum in d and Sum not in sol: sol += [
                        Sum,
                ]
                d[Sum] += [
                    (i, j),
                ]
                if Sum in sol:
                    for s in d[Sum]:
                        if s == (i, j): continue
                        else:
                            x, y = s[0], s[1]
                            if x == i or y == j or x == j or y == i: continue
                            if ans == []: ans = [x, y, i, j]
                            else: ans = min([x, y, i, j], ans)

        #print(sol,'\n',d,ans)
        if sol == []: return sol
        else:
            return ans
Beispiel #5
0
def getreservas():
    id_usuario = request.json.get('id_usuario')
    reservas_usr = []
    lista_reservas = Reservas.query.filter_by(usuario_id=id_usuario).all()
    for i in lista_reservas:
        reservas_usr.append(
            (i.data_checkin, i.data_checkout, i.status, i.id_reserva))
    dict_user = dt(list)
    dict_user[id_usuario] = reservas_usr
    return jsonify({'retorno': 'ok', 'reservas': dict_user}), 200
Beispiel #6
0
def count_words(article):
    from collections import defaultdict as dt
    # replace \n to space,then split to list
    article_list = article.replace('\n', ' ').split()
    # counts = {}
    counts = dt(int)
    for word in article_list:
        # if word not in counts:
        #     counts[word] = 1
        # else:
        #     counts[word] += 1
        counts[word] += 1
    print(counts)
Beispiel #7
0
def process_activity(ddd):
    '''process data to format like {(uid,bid):[0,1,2,3]}'''
    cc = dt(int)
    dddd = [(row[0],row[1],row[2]) for  row in ddd]
    for k in dddd:
        cc[k] += 1
#    return cc.items()
    tmp = {}
    for it in list(cc.items()):
        tmp[(it[0][0],it[0][1])] = [0,0,0,0]
    for it in list(cc.items()):
        tmp[(it[0][0],it[0][1])][it[0][2]] = it[1]
    return tmp #{(1,2):[1,2,3,4]}
Beispiel #8
0
def process_activity(ddd):
    '''process data to format like {(uid,bid):[0,1,2,3]}'''
    cc = dt(int)
    dddd = [(row[0], row[1], row[2]) for row in ddd]
    for k in dddd:
        cc[k] += 1


#    return cc.items()
    tmp = {}
    for it in list(cc.items()):
        tmp[(it[0][0], it[0][1])] = [0, 0, 0, 0]
    for it in list(cc.items()):
        tmp[(it[0][0], it[0][1])][it[0][2]] = it[1]
    return tmp  #{(1,2):[1,2,3,4]}
Beispiel #9
0
    def findDiagonalOrder(self, a: List[List[int]]) -> List[int]:

        # Time: O(R * C) Where R and C are length of the row and columns of the matrix respectively
        # Space: O(R * C)

        d = dt(list)
        ret = list()

        for i in range(len(a)):
            for j in range(len(a[i])):
                d[i + j].append(a[i][j])

        for k, v in d.items():
            ret += v[::-1]

        return ret
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        # 初始化 行,列
        m, n = len(board), len(board[0])
        # 创建 trie树,根据官方的骚方法
        Tree = lambda: dt(Tree)
        tree = Tree()
        for w in words:
            reduce(dict.__getitem__, w + "#", tree)
        # 初始化返回的list和方向
        ret = []
        directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]

        # 深度搜索
        def dfs(used, x, y, dic, now):
            if "#" in dic:  # 如果dic是末尾字符,即包含"#"字符
                ret.append(now)  # 结算
                del dic["#"]  # "某字符":{"#":{}} 中的key="#" 没了,"某字符" 的字典也空了

            used.add((x, y))  # 记录已访问过 board上的位置,避免这一次重复访问
            for direct in directions:
                # 四个方向
                new_x = x + direct[0]
                new_y = y + direct[1]
                # 方向满足条件
                if 0 <= new_x < m and 0 <= new_y < n and (new_x,
                                                          new_y) not in used:
                    # 检查这个新value是否在dic中
                    next_val = board[new_x][new_y]
                    if next_val in dic:
                        # 那么保存这个value,然后进入到对应这个value的字典
                        dfs(used, new_x, new_y, dic[next_val], now + next_val)
                        # 妙处,如果它里面没东西了,例如"#":{}已经被删除了。
                        # 那么它也没作用了
                        if not dic[next_val]: del dic[next_val]
            # 这一趟结束了,now已经存入ret,可以清除这个(x,y)
            used.remove((x, y))

        # 从每个节点开始
        for i in range(m):
            for j in range(n):
                curr_val = board[i][j]
                if curr_val in tree:
                    dfs(set(), i, j, tree[curr_val], curr_val)
                    if not tree[curr_val]: del tree[curr_val]

        return ret
    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:

        st = set()
        for i in orders:
            st.add(i[2])

        foods = sorted(list(st))
        tables = dt(lambda: [0] * len(foods))

        for order in orders:
            tables[order[1]][foods.index(order[2])] += 1

        ret = [["Table"] + foods]

        for k, v in sorted(tables.items(), key=lambda x: int(x[0])):
            v = [str(i) for i in v]
            ret.append([k] + v)

        return ret
    def subdomainVisits(self, a: List[str]) -> List[str]:
        d = dt(int)

        for i in a:
            tmp = i.split()
            d[tmp[1]] += int(tmp[0])

            tmp2 = tmp[1].replace('.', ' ').split()

            for i in range(1, len(tmp2)):
                y = '.'.join(tmp2[i:])
                d[y] += int(tmp[0])

        ret = list()

        for i in d:
            ret.append(str(d[i]) + ' ' + i)

        return ret
Beispiel #13
0
    def findDiagonalOrder(self, a: List[List[int]]) -> List[int]:

        # Time: O(N * M) Where N and M are rows and columns respectively
        # Space: O(N * M)

        d = dt(list)

        for i in range(len(a)):
            for j in range(len(a[0])):
                d[i + j].append(a[i][j])

        ret = list()

        for k, v in d.items():
            if not k % 2:
                ret += v[::-1]
            else:
                ret += v

        return ret
Beispiel #14
0
    def isHappy(self, n: int) -> bool:
        d = dt(int)

        def helper(a):
            sumi = 0
            while a > 9:
                sumi += (a % 10)**2
                a //= 10
            sumi += a**2

            return sumi

        while n > 1:
            d[n] = 1
            n = helper(n)
            if d[n]:
                return False
        if n == 1:
            return True
        return False
 def equal(self, A):
     d = dt(list)
     l = len(A)
     sol= []
     ans = []
     for i in range(l):
         for j in range(i+1,l):
             Sum = A[i]+A[j]
             if Sum in d and Sum not in sol:    sol+=[Sum,]
             d[Sum] += [(i,j),]
             if Sum in sol:
                 for s in d[Sum]:
                     if s==(i,j):    continue
                     else:   
                         x,y=s[0],s[1]
                         if x==i or y==j or x==j or y==i:    continue
                         if ans ==[]:    ans=[x,y,i,j]
                         else:   ans = min([x,y,i,j],ans)
                 
     #print(sol,'\n',d,ans)
     if sol==[]:  return sol
     else:
         return ans
Beispiel #16
0
 def groupAnagrams(self, a: List[str]) -> List[List[str]]:
     ret = dt(list)
     for i in a:
         ret[tuple(sorted(i))].append(i)
     return ret.values()
x, y = tempi, tempj
while (x < m and y < n):
    l[x][y] = '*'
    x += 1
    y += 1
for i in l:
    print(*i)

#######################################################################################################
##################################### Method 3 - Using Dictionary######################################
#######################################################################################################
from collections import defaultdict as dt
r, c = map(int, input().split())
m = [list(map(int, input().split())) for i in range(r)]
x = int(input())
d1 = dt(list)
d2 = dt(list)
for i in range(r):
    for j in range(c):
        d1[i - j].append(m[i][j])
        d2[i + j].append(m[i][j])
k1 = [i for i in d1.keys()]
k2 = [i for i in d2.keys()]
for i in k1:
    if x in d1[i]:
        a = i
for i in k2:
    if x in d2[i]:
        b = i
for i in range(r):
    for j in range(c):
Beispiel #18
0
 def __init__(self):
     """
     Initialize your data structure here.
     """
     self.d = dt(list)
Beispiel #19
0
def getCategory():

    url = request.form['title']

    link = urllib.request.urlopen(url)

    html_soup = BeautifulSoup(link, 'html.parser')

    get_header_one = str(html_soup.find('h1').string)

    if html_soup.find('h2'):

        get_header_two = str(html_soup.find('h2').string)

        if (len(get_header_one) > len(get_header_two)):

            string = get_header_one

        else:

            string = get_header_two
    else:

        string = get_header_one

    file = open("static/Classifier.csv", "rt")

    mydict = dt(list)

    asc_set = {
        '.', ',', '?', '/', ':', ';', '{', '}', '[', ']', '+', '=', ')', '(',
        '*', '&', '^', '%', '$', '#', '@', '!', '~', '`', '1', '2', '3', '4',
        '5', '6', '7', '8', '9'
    }

    for c in file.readlines():

        s = c.split(",")

        if len(s) > 1 and len(s[1]) == 1:

            title = s[0]

            category = s[1]

            mydict[category].extend(set(title.split(" ")))

    for k, v in mydict.items():

        mydict[k] = set(v)

    file.close()

    article = Article(url)

    article.download()

    article.parse()

    article.nlp()

    summary = article.summary

    keywords = article.keywords

    # print (article.text)

    # print ("Article: ",article.summary)

    # print ("Keywords: ", article.keywords)

    max_length, category = 0, "other"

    category_list = list()

    category_dict = dict()

    for k, v in mydict.items():

        matched_words = set(keywords).intersection(v)

        length = len(matched_words)

        print(k, matched_words)

        category_dict[k] = length

    max_value = max(category_dict.values())

    for k, v in category_dict.items():

        if v == max_value:

            if k == "e":

                category_list.append("Entertainment")

            elif k == "t":

                category_list.append("Technology")

            elif k == "m":

                category_list.append("Medical")

            elif k == "b":

                category_list.append("Business")

            else:

                category_list.append("Other")

    category = "/".join(category_list)

    return render_template("home.html", summary=summary, category=category)
from sys import stdin as Si
from collections import defaultdict as dt
from operator import itemgetter as ig
if __name__ == '__main__':
    n, m = map(int, Si.readline().split())
    h = dt(dict)

    for i in range(n):
        s, r, p = map(str, Si.readline().split())
        r, p = map(int, (r, p))
        if p in h[r]: h[r][p] += [s]
        else: h[r][p] = [s]
    for da in h:
        d = sorted(h[da].items(), key=ig(0), reverse=True)
        #print(d)
        ns, i = [], 0
        while len(ns) < 2:
            if len(d[i][1]) + len(ns) >= 3:
                ns = '?'
                break
            else:
                ns += d[i][1][:2 - len(ns)]
            i += 1
            if i >= len(d): break
        print(' '.join(ns))
'''
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.

The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.

Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.
from sys import stdin as Si
from collections import defaultdict as dt
from operator import itemgetter as ig 
if __name__=='__main__':
    n,m = map(int,Si.readline().split())
    h = dt(dict)

    for i in range(n):
        s,r,p = map(str,Si.readline().split())
        r,p = map(int,(r,p))
        if p in h[r]:   h[r][p]+=[s]
        else:   h[r][p]=[s]
    for da in h:
        d = sorted(h[da].items(),key=ig(0),reverse=True)
        #print(d)
        ns,i = [],0
        while len(ns)<2:
            if len(d[i][1])+len(ns)>=3:
                ns='?'
                break
            else:
                ns+= d[i][1][:2-len(ns)]
            i+=1
            if i>=len(d):   break
        print(' '.join(ns))
'''
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.

The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.

Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.
 def findDuplicate(self, a: List[int]) -> int:
     d = dt(int)
     for i in a:
         if d[i]:
             return i
         d[i] = 1
 def __init__(self):
     self.passenger = dt(list)
     self.time = dt(list)