Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.61 KB | None | 0 0
  1.  
  2. """
  3. #ШАБЛОН ПРОЕКТИРОВАНИЯ "НАБОР", (Алекс Мартелли - «Python Cookbook»)
  4. class Bunch(dict):
  5. def __init__(self, *args, **kwds):
  6. super(Bunch, self).__init__(*args, **kwds)
  7. self.__dict__ = self
  8. T = Bunch
  9.  
  10. x = Bunch(name="Jayne Cobb", position="PR")
  11. print(x.name)
  12.  
  13. t = T(left=T(left="a", right="b"), right=T(left="c"))
  14. print(t.left)
  15. print(t.left.right)
  16. print(t['left']['right'])
  17. print("left" in t.right)
  18. print("right" in t.right)
  19. """
  20.  
  21. from mysql.connector import MySQLConnection, Error
  22. from python_mysql_dbconfig import read_db_config
  23. import random
  24. import matplotlib.pyplot as plt
  25. import networkx as nx
  26. from networkx.drawing.nx_agraph import write_dot, graphviz_layout
  27. import warnings
  28. warnings.filterwarnings("ignore", category=UserWarning)
  29.  
  30. dbconfig = read_db_config()
  31.  
  32. #Здесь 'a' выступает в роли количества вершин, которое будет в нашем дереве
  33. def random_tree(a):
  34. cursor.execute("DELETE FROM tree")
  35. cursor.execute("INSERT INTO tree (ancestor, descendant) VALUES (1, 1)")
  36. for i in range(1, a):
  37. insert(random.randint(1, i))
  38.  
  39. def deletion_without_subtree(a):
  40. cursor.execute("DELETE FROM tree WHERE ancestor = " + str(a) + " OR descendant = " + str(a))
  41.  
  42. def deletion_with_subtree(a):
  43. cursor.execute("SELECT descendant FROM tree WHERE ancestor = " + str(a))
  44. des = cursor.fetchone()
  45. y = []
  46. while des is not None:
  47. y.append(des[0])
  48. des = cursor.fetchone()
  49. i = len(y)
  50. #while i > 0:
  51. # deletion_without_subtree(y[i-1])
  52. # conn.commit()
  53. # i-=1
  54. for i in range(0, len(y)):
  55. deletion_without_subtree(y[i])
  56.  
  57. #У этой функции переменная 'а' обозначает предка нашего нового листа
  58. def insert(a):
  59. cursor.execute("SELECT ancestor FROM tree WHERE descendant = " + str(a))
  60. anc = cursor.fetchone()
  61. x = []
  62. while anc is not None:
  63. x.append(anc[0])
  64. anc = cursor.fetchone()
  65.  
  66. cursor.execute("SELECT MAX(ancestor) FROM tree")
  67. new_number = cursor.fetchone()[0] + 1
  68.  
  69. x.append(new_number)
  70.  
  71. i = 0
  72. insert_request = "INSERT INTO tree (ancestor, descendant) VALUES "
  73. while i < len(x):
  74. insert_request += "(" + str(x[i]) + ", " + str(new_number) + "),"
  75. i += 1
  76. cursor.execute(insert_request[:-1])
  77.  
  78. #'a' - какую вершину берем для переноса, 'b' - под какую вершину переносим
  79.  
  80. def transfering_without_subtree(a, b):
  81. cursor.execute("DELETE FROM tree WHERE ancestor != descendant AND (ancestor = " + str(a) + " OR descendant = " + str(a) + ")")
  82.  
  83. cursor.execute("SELECT ancestor FROM tree WHERE descendant = " + str(b))
  84. anc = cursor.fetchone()
  85. x = []
  86. while anc is not None:
  87. x.append(anc[0])
  88. anc = cursor.fetchone()
  89.  
  90. i = 0
  91. insert_request = "INSERT INTO tree (ancestor, descendant) VALUES "
  92. while i < len(x):
  93. insert_request += "(" + str(x[i]) + ", " + str(a) + "),"
  94. i += 1
  95. cursor.execute(insert_request[:-1])
  96.  
  97.  
  98.  
  99. #'a' - какую вершину берем для переноса, 'b' - под какую вершину переносим
  100. def transfering_with_subrtee(a, b):
  101. s1 = "DELETE FROM tree WHERE ancestor IN (SELECT ancestor FROM tree WHERE descendant = " + str(a) +" AND ancestor != " + str(a) + ") AND descendant IN (SELECT descendant FROM tree WHERE ancestor = " + str(a) + ")"
  102. cursor.execute(s1)
  103.  
  104. cursor.execute("SELECT ancestor FROM tree WHERE descendant = " + str(b))
  105. anc = cursor.fetchone()
  106. x = []
  107. while anc is not None:
  108. x.append(anc[0])
  109. anc = cursor.fetchone()
  110.  
  111. cursor.execute("SELECT descendant FROM tree WHERE ancestor = " + str(a))
  112. des = cursor.fetchone()
  113. y = []
  114. while des is not None:
  115. y.append(des[0])
  116. des = cursor.fetchone()
  117.  
  118. i = 0
  119. j = 0
  120.  
  121. insert_request = "INSERT INTO tree (ancestor, descendant) VALUES "
  122. for i in range(len(y)):
  123. for j in range(len(x)):
  124. insert_request += "(" + str(x[i]) + ", " + str(y[j]) + "),"
  125.  
  126. cursor.execute(insert_request[:-1])
  127.  
  128.  
  129.  
  130.  
  131. def query_with_fetchone():
  132. cursor.execute("SELECT * FROM tree")
  133. row = cursor.fetchone()
  134. while row is not None:
  135. print(row)
  136. row = cursor.fetchone()
  137.  
  138. def query_with_fetchone_2():
  139. users = {}
  140. cursor.execute("SELECT * FROM tree")
  141. row = cursor.fetchone()
  142. while row is not None:
  143. row[0]
  144. row = cursor.fetchone()
  145.  
  146.  
  147.  
  148. if __name__ == '__main__':
  149.  
  150. try:
  151. conn = MySQLConnection(**dbconfig)
  152. cursor = conn.cursor()
  153. #transfering_with_subrtee(5, 3)
  154. #create_my_tree_again()
  155. #transfering_without_subtree(5, 3)
  156. random_tree(10)
  157. G = nx.DiGraph()
  158. anc = []
  159.  
  160. cursor.execute("SELECT DISTINCT ancestor FROM tree")
  161. row = cursor.fetchone()
  162. while row is not None:
  163. anc.append(row[0])
  164. G.add_node(str(row[0]))
  165. row = cursor.fetchone()
  166.  
  167. data = []
  168.  
  169. cursor.execute("SELECT * FROM tree")
  170. row = cursor.fetchone()
  171. while row is not None:
  172. data.append(row)
  173. row = cursor.fetchone()
  174.  
  175. INF = -10000
  176.  
  177. mtrx = {}
  178.  
  179. for i in anc:
  180. for j in anc:
  181. if i in mtrx:
  182. mtrx[i][j] = INF
  183. else:
  184. q = {i: {j: INF}}
  185. mtrx.update(q)
  186.  
  187. for elem in data:
  188. if(elem[0] == elem[1]):
  189. if(elem[0] != anc[0]):
  190. mtrx[elem[0]][elem[1]] = INF
  191. else:
  192. mtrx[elem[0]][elem[1]] = 0
  193. else:
  194. mtrx[elem[0]][elem[1]] = 1
  195.  
  196. for k in range(1, len(anc)+1):
  197. for i in anc:
  198. for j in anc:
  199. if(mtrx[i][j] < (mtrx[i][k] + mtrx[k][j])):
  200. mtrx[i][j] = mtrx[i][k] + mtrx[k][j]
  201.  
  202. for elem in data:
  203. if(mtrx[elem[0]][elem[1]] == 1):
  204. G.add_edge(str(elem[0]), str(elem[1]))
  205.  
  206. plt.title('my_tree')
  207. pos = graphviz_layout(G, prog='dot')
  208. nx.draw(G, pos, with_labels=True, arrows=True)
  209. plt.savefig('nx_test.png')
  210. plt.show()
  211.  
  212. #query_with_fetchone()
  213. conn.commit()
  214.  
  215.  
  216. except Error as e:
  217. print(e)
  218.  
  219. finally:
  220. cursor.close()
  221. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement