main.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import tqdm
  2. class Bag:
  3. def __init__(self,color):
  4. self.color = color
  5. self.capacity = []
  6. def __str__(self):
  7. return self.color + str(self.capacity)
  8. def addCapacity(self, amount, color):
  9. self.capacity.append([amount,color])
  10. def getCapacity(self):
  11. return self.capacity
  12. def getColor(self):
  13. return self.color
  14. def isColor(self, color):
  15. if color == self.color:
  16. return True
  17. else:
  18. return False
  19. def canHold(self, color):
  20. for x in self.capacity:
  21. print('['+self.color+'] check '+color+' in '+str(x))
  22. if color in x:
  23. return True
  24. else:
  25. return False
  26. file = open('input.txt','r')
  27. #file = open('test.txt','r')
  28. rules = file.readlines()
  29. bags = []
  30. def getBag(color):
  31. found = False
  32. for b in bags:
  33. if b.isColor(color):
  34. found = True
  35. return b
  36. if not found:
  37. b = Bag(color)
  38. bags.append(b)
  39. return b
  40. for r in rules:
  41. r = r.replace('.','')
  42. r = r.replace('\n','')
  43. par = r.split(' bags contain')
  44. b = getBag(par[0])
  45. if par[1] == ' no other bags':
  46. continue
  47. cap = par[1].split(',')
  48. for c in cap:
  49. c = c.strip()
  50. amount = c.split(' ')[0]
  51. color = c.replace(str(amount)+' ','').replace(' bags','').replace(' bag','')
  52. b.addCapacity(amount,color)
  53. sum = 0
  54. def getToColor(target,start):
  55. if target == start:
  56. return True
  57. bag = getBag(start)
  58. for b in bag.getCapacity():
  59. if getToColor(target,getBag(b[1]).getColor()):
  60. return True
  61. return False
  62. def countSubBags(color):
  63. sum = 0
  64. bag = getBag(color)
  65. if len(bag.getCapacity()) == 0:
  66. return 1
  67. for b in bag.getCapacity():
  68. #print('['+color+'] '+ b[0] + ' * ' + str(countSubBags(b[1])))
  69. sum += int(b[0]) * countSubBags(b[1])
  70. print(color + ' ' +str(sum))
  71. return sum + 1
  72. print(countSubBags('shiny gold') - 1)
  73. exit()
  74. for b in bags:
  75. if b.getColor() == 'shiny gold':
  76. continue
  77. if getToColor('shiny gold',b.getColor()):
  78. sum += 1
  79. print(str(sum))