blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
751eba4e5bb07a8aedd1b07c34deb61883a7fcf6
AlgorithmOnline/jaeeun
/2_20210216.py
353
3.625
4
def solution(routes): routes.sort() answer = 1 travel = routes[0] for i in range(1,len(routes)): travel2=routes[i] travel =[max(travel[0], travel2[0]), min(travel[1], travel2[1])] if travel[0]<=travel[1]: continue else: answer+=1 travel =travel2 return answer
e52687a118e5b20633742d2de98ca183ebe7fe4d
AlgorithmOnline/jaeeun
/2_20200812.py
703
3.625
4
# 프로그래머스 이중 우선순위 큐 def solution(operations): # 항상 소팅이 돼어 있어야한다. answer = [] queue=[] for op in operations: if op[:1] =='I': queue.append(int(op[2:])) queue.sort() elif op =="D 1": # 최대 제거 if len(queue) ==0: continue else: queue=queue[:-1] elif op =="D -1": # 최소 제거 if len(queue) ==0: continue else: queue=queue[1:] if len(queue) ==0: return [0,0] else: answer.append(queue[-1]) answer.append(queue[0]) return answer
6e480641effc28b3d49ea423dee4cb516febb2f7
AlgorithmOnline/jaeeun
/1_20210205.py
982
3.828125
4
import math x0, y0, r0, x1, y1, r1 = map(float, input().split()) def area(x0, y0, r0, x1, y1, r1): d = math.sqrt((x0 - x1) ** 2 + (y0 - y1) ** 2) rr0 = r0 * r0 rr1 = r1 * r1 # Circles do not overlap if (d > r1 + r0): return 0 # Circle1 is completely inside circle0 elif (d <= abs(r0 - r1) and r0 >= r1): return math.pi * rr1 # Circle0 is completely inside circle1 elif (d <= abs(r0 - r1) and r0 < r1): # Return area of circle0 return math.pi * rr0 # Circles partially overlap else: phi = (math.acos((rr0 + (d * d) - rr1) / (2 * r0 * d))) * 2 theta = (math.acos((rr1 + (d * d) - rr0) / (2 * r1 * d))) * 2 area1 = 0.5 * theta * rr1 - 0.5 * rr1 * math.sin(theta) area2 = 0.5 * phi * rr0 - 0.5 * rr0 * math.sin(phi) # Return area of intersection return area1 + area2 answer = float(round(1000 * area(x0, y0, r0, x1, y1, r1)) / 1000) print('%.3f' % answer)
5cef9d58b690a0e6a805fc83a8483ca890e889f3
pengjinfu/DemoDjango
/study/ArrayClass.py
2,401
3.75
4
import random import re import statistics class ArrayClass: def __init__(self, name, init_arr): self.name = name self.init_arr = init_arr def to_string(self): return self.name def demo_arr(self): arr = ['a', 'b', 'c'] return arr.append(self.name) def demo_if(self): if isinstance(self.name, int): exit("Name is not an integer !") if self.name == 'A': return self.name elif self.name == 'B': return self.name + 'BBB' else: return self.name + 'CCC' def set_name(self, value): self.name = value def __str__(self): return 'it is file to string ' + self.name def add_arr(self, new_arr): # 支持数据的直接累加 # return self.init_arr + new_arr def demo_fib(self, num): a, b = 0, 1 data = [] while a < num: data.append(a) a = b b = a + b return data def demo_for(self, result): for w in result: print(w) def demo_even(self, num): # 返回数组中构思的个数 for n in range(2, num): if n % 2 == 0: print("Found an even number", n) continue print("Found a number", num) def demo_in_array(self, value): if value in self.init_arr: return True def demo_stack(self): stack = [1, 3, 5, 8, 4] stack.append(6) return stack def demo_matrix(self): matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] def demo_format(self): print('{0} and {1}'.format('aaa', 'bbb')) def regular(self, str): re.findall(r'\bf[a-z]*', str) def demo_random(self, arr): value = random.choice(arr) return value def demo_stat(self, arr): # python 的均值和方差, 该statistics模块计算数值数据的基本统计属性(均值,中位数,方差等) # data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] statistics.mean(arr) statistics.median(arr) statistics.variance(arr) def demo_empty(self, key): arr = [{"a": 1, "b": 2}] if key is not None and hasattr(arr, key): print("{0} key is exist ", key) pass
9e18840ba570b2c8366a8bf68e9ffcab18782421
PaNOSC-ViNYL/XOPPY
/devel/glossary/test1.py
564
3.515625
4
def read_json(json_name): json_text = open(json_name).read() json_dict = eval(json_text) json = sorted(json_dict.items(), key=lambda x: json_text.index('"{}"'.format(x[0]))) #print(json) #json_lowercase = dict((k.lower(), v) for k, v in json.iteritems()) json_lowercase = json return json_lowercase if __name__ == "__main__": a = read_json("IC_Lens.json") for i,j in a: print("--- %s %s "%(i,j)) b = read_json("BC_PerfectCrystal.json") for i,j in b: print("--- %s %s "%(i,j))
90d819ae7a224af104405a39d6e75a3f38eab8e6
MrCat9/HelloPython
/从list删除元素.py
377
3.84375
4
#用list的pop()方法删除最后一个: L = ['Adam', 'Lisa', 'Bart', 'Paul'] L.pop() print(L) #['Adam', 'Lisa', 'Bart'] #Paul的索引是2,用 pop(2)把Paul删掉: L = ['Adam', 'Lisa', 'Paul', 'Bart'] L.pop(2) print(L) #['Adam', 'Lisa', 'Bart'] #如果我们要把Paul和Bart都删掉 L = ['Adam', 'Lisa', 'Paul', 'Bart'] L.pop(2) L.pop(2) print(L) #['Adam', 'Lisa']
f0054948c66568ce30cb8d9e94d723b5179de097
MrCat9/HelloPython
/list中替换元素.py
298
4.21875
4
#先删除,在添加==替换 #对list中的某一个索引赋值,就可以直接用新的元素替换掉原来的元素,list包含的元素个数保持不变。 L = ['Adam', 'Lisa', 'Bart'] print(L) #['Adam', 'Lisa', 'Bart'] #L[2] = 'Paul' L[-1] = 'Paul' print(L) #['Adam', 'Lisa', 'Paul']
682ccfae072a9a22bfe9374f7ce0ebb0a0d43f8d
MrCat9/HelloPython
/Python之set.py
4,832
4.125
4
#dict的作用是建立一组 key 和一组 value 的映射关系,dict的key是不能重复的。 #有的时候,我们只想要 dict 的 key,不关心 key 对应的 value,目的就是保证这个集合的元素不会重复,这时,set就派上用场了。 #set 持有一系列元素,这一点和 list 很像,但是set的元素没有重复,而且是无序的,这点和 dict 的 key很像。 #创建 set 的方式是调用 set() 并传入一个 list,list的元素将作为set的元素: s = set(['A', 'B', 'C']) print(s) #{'A', 'B', 'C'} #请注意,上述打印的形式类似 list, 但它不是 list,仔细看还可以发现, #打印的顺序和原始 list 的顺序有可能是不同的,因为set内部存储的元素是无序的。 #因为set不能包含重复的元素,所以,当我们传入包含重复元素的 list时,set会自动去掉重复的元素,原来的list有4个元素,但set只有3个元素。 s = set(['A', 'B', 'C', 'C']) print(s) #{'B', 'A', 'C'} print(len(s)) #3 #由于set存储的是无序集合,所以我们没法通过索引来访问。 #访问 set中的某个元素实际上就是判断一个元素是否在set中。 #例如,存储了班里同学名字的set: s = set(['Adam', 'Lisa', 'Bart', 'Paul']) print('Bart' in s) #True print('bart' in s) #False 区分大小写,'Bart' 和 'bart'被认为是两个不同的元素。 print('Bill' in s) #False #lower() print('AABB'.lower()) #aabb #改进set,使得 'adam' 和 'bart'都能返回True。 s = set(name.lower() for name in ['Adam', 'Lisa', 'Bart', 'Paul']) print(s) #{'adam', 'paul', 'lisa', 'bart'} print('adam' in s) #True print('bart' in s) #True #set的内部结构和dict很像,唯一区别是不存储value,因此,判断一个元素是否在set中速度很快。 #set存储的元素和dict的key类似,必须是不变对象,因此,任何可变对象是不能放入set中的。 #set存储的元素也是没有顺序的。 #set 的应用 #星期一到星期日可以用字符串'MON', 'TUE', ... 'SUN'表示。 #假设我们让用户输入星期一至星期日的某天,如何判断用户的输入是否是一个有效的星期呢? #可以用 if 语句判断,但这样做非常繁琐 #如果事先创建好一个set,包含'MON' ~ 'SUN': #再判断输入是否有效,只需要判断该字符串是否在set中: weekdays = set(['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']) print(weekdays) {'FRI', 'TUE', 'WED', 'THU', 'SAT', 'MON', 'SUN'} x = input("input:") if x in weekdays: print('input ok') else: print('input error') #请设计一个set并判断用户输入的月份是否有效。 months = set(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']) x1 = 'Feb' #输入1 x2 = 'Sun' #输入2 if x1 in months: print('x1: ok') else: print('x1: error') if x2 in months: print('x2: ok') else: print('x2: error') #x1: ok #x2: error #由于 set 也是一个集合,所以,遍历 set 和遍历 list 类似,都可以通过 for 循环实现。 #直接使用 for 循环可以遍历 set 的元素: s = set(['Adam', 'Lisa', 'Bart']) for name in s: print(name) #Lisa #Adam #Bart #注意: 观察 for 循环在遍历set时,元素的顺序和list的顺序很可能是不同的,而且不同的机器上运行的结果也可能不同。 #请用 for 循环遍历如下的set,打印出 name: score 来。 s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)]) for x in s: print(x[0]+': '+str(x[1])) #或者 s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)]) for name,score in s: print(name+': '+str(score)) #由于set存储的是一组不重复的无序元素,因此,更新set主要做两件事: #一是把新的元素添加到set中,二是把已有元素从set中删除。 #添加元素时,用set的add()方法: s = set([1, 2, 3]) print(s) #{1, 2, 3} s.add(4) print(s) #{1, 2, 3, 4} #如果添加的元素已经存在于set中,add()不会报错,但是不会加进去了: s = set([1, 2, 3]) print(s) #{1, 2, 3} s.add(3) print(s) #{1, 2, 3} #删除set中的元素时,用set的remove()方法: s = set([1, 2, 3, 4]) print(s) #{1, 2, 3, 4} s.remove(4) print(s) #{1, 2, 3} #如果删除的元素不存在set中,remove()会报错 #所以用add()可以直接添加,而remove()前需要判断。 #针对下面的set,给定一个list,对list中的每一个元素,如果在set中,就将其删除,如果不在set中,就添加进去。 s = set(['Adam', 'Lisa', 'Paul']) L = ['Adam', 'Lisa', 'Bart', 'Paul'] for name in L: if name in s: s.remove(name) else: s.add(name) print(s) #{'Bart'} #或者 s = set(['Adam', 'Lisa', 'Paul']) L = ['Adam', 'Lisa', 'Bart', 'Paul'] t = set(L) for a in s: t.remove(a) print(t) #{'Bart'}
fd2c03b45022de5c70da5245fa75ffb03cc39093
JamesTadleyGreen/Instagram_Liker
/instagram.py
3,168
3.53125
4
#Program to load up instagram, login using details, navigate to specific tags # and like a specified number of photos. Then record data in text file. #imports from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys import webbrowser import time import datetime import random from random import randint import os #main function def main(): USERNAME = "" PASSWORD = "" script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in rel_path = "chrome/chromedriver" abs_file_path = os.path.join(script_dir, rel_path) #Tags to like insta = ['https://www.instagram.com/explore/tags/computerscience/', 'https://www.instagram.com/explore/tags/study/', 'https://www.instagram.com/explore/tags/learning/', 'https://www.instagram.com/explore/tags/maths/', 'https://www.instagram.com/explore/tags/math/', 'https://www.instagram.com/explore/tags/science/', 'https://www.instagram.com/explore/tags/exploring/'] #location of the chrome browser driver = webdriver.Chrome(executable_path=abs_file_path) #login information driver.get("https://www.instagram.com/accounts/login/") time.sleep(1) inputElementUsername = driver.find_element_by_name("username") inputElementUsername.send_keys(USERNAME) inputElementPassword = driver.find_element_by_name("password") inputElementPassword.send_keys(PASSWORD) time.sleep(1) inputElementUsername.send_keys(Keys.ENTER) #opening a random webpage #sleeping to allow time for page to load time.sleep(3) driver.get(random.choice(insta)) time.sleep(3) #running liker driver.find_element_by_css_selector('._e3il2').click() #find and click on first image (starts "slideshow") time.sleep(1) i = 1 #like photos while i < random.randint(10, 50): #random number of photos chosen time.sleep(1.5) try: driver.execute_script("document.querySelector('.coreSpriteHeartOpen').click();") #like the photo except: pass #if 404 error or page does not load on time, move on try: driver.find_element_by_css_selector('._3a693').click() #move on to next photo except: driver.get(random.choice(insta)) #if 404 error, restart with new tag selection time.sleep(3) driver.find_element_by_css_selector('._e3il2').click() time.sleep(1) i += 1 #collect data about run time.sleep(10) #write out the last URL to check for errors with open('last_url.txt', 'a') as the_file: the_file.write(driver.current_url + ' at ' + ('%s' % datetime.datetime.now())) #go to account and check followers driver.get("https://www.instagram.com/" + USERNAME + "/") with open('last_url.txt', 'a') as the_file: the_file.write(' with ' + driver.find_elements_by_class_name("_t98z6")[1].text + '\n') #quit the browser driver.quit(); print('Done') print(datetime.datetime.now()) #run main program main()
af846700f2a2ec653612061a5208a5281052d5ad
OsaAjani/cours-iot
/introduction_a_python/tp/crypto_price.py
1,064
3.609375
4
#!/usr/bin/env python3.5 #-*- coding: utf-8 -*- import cryptocompare def quit () : print('Merci d\'avoir utilisé CryptoPrice !') exit(0) def show_coin_list () : coin_list = cryptocompare.get_coin_list(format = True) for coin in coin_list : print(coin) def show_coin_price (coin) : if coin not in cryptocompare.get_coin_list(format = True) : print('Désolé, cette crypto n\'existe pas !') return False coin_price = cryptocompare.get_price(coin, full = False, curr = 'USD') print('1 {coin} = {coin_price} $'.format(coin = coin, coin_price = coin_price[coin]['USD'])) #Main part print('###########################\nBienvenu dans CryptoPrice !\n###########################\n') while True : coin = input(""" Entrez l\'acronyme de la monnaie dont vous voulez le prix ? Sinon, pour voir la liste des monnaies : list. Et pour quitter : quit. Acronyme : """) if coin == 'quit' : quit() if coin == 'list' : show_coin_list() continue show_coin_price(coin)
8c893dcb173cb7dc653d93d89512e184b80016b3
caspeerpoiuy/data-structures-and-algorithms-
/classical_algorithms/select_sort/implement.py
544
4.0625
4
def select_sort(alist): """ select sort thinking: compare element and find the min index, if element less than min, change their position. """ if len(alist) == 0: return for i in range(1, len(alist)): min_index = i - 1 for j in range(i, len(alist)): if alist[j] < alist[min_index]: min_index = j alist[i - 1], alist[min_index] = alist[min_index], alist[i - 1] if __name__ == '__main__': li = [35, 66, 21, 77, 54, 22] select_sort(li) print(li)
bb6d923f1614534d539d9e4258a80235ae73fab2
stepin105014/github-upload
/proj_base.py
1,955
3.796875
4
from nltk.tokenize import sent_tokenize, word_tokenize import nltk from nltk.corpus import stopwords """ Reading Input """ val = input("Enter the text : ") print ("Input given :"+ str(val)) # Tokenization tokens=sent_tokenize(val) print("Tokens are :") print(tokens) wtokens=word_tokenize(val) print("Word Tokens are :") print(wtokens) # Stopword removal common_words = open("common_words.txt", "r") with open("common_words.txt") as f: lineList = f.readlines() print(lineList) print(common_words) cwlist = [line.split('\n') for line in common_words.readlines()] print(cwlist) stop_words = cwlist print(stop_words) filtered_sentence = [w for w in wtokens if not w in stop_words[0]] filtered_sentence = [] flag=0 for w in wtokens: for i in range(len(stop_words)): if w!=stop_words[i][0]: flag=1 break if(flag==0): filtered_sentence.append(w) print(filtered_sentence) class Reader: """Simplifies the reading of files to extract a list of strings. Simply pass in the name of the file and it will automatically be read, returning you a list of the strings in that file.""" def __init__(self, name): """\"name\" is the name of the file to open. The file should be a series of lines, each line separated with a newline character.""" self.name = name; def open_file(self): """Reads the file given by the file name and returns its contents as a list of seperate strings, each string being a line in the file.""" with open(self.name) as fp: contents = fp.read().split() fp.close() return contents def open_file_single_string(self): """Reads the file given by the file name and returns its contents as a list of seperate strings, each string being a line in the file.""" with open(self.name) as fp: contents = fp.read() fp.close() return contents
773b1abb8495beae8dbe657a1b3d3785cdcb3442
danhouldsworth/helloLanguages
/HelloWorld+/hello.py
153
3.875
4
# 1. Done # Note: This is the syntax for Python 2.X # in Python 3.x print is a function. greeting = "Hello" greeting += ", " + "world!" print greeting
cff75e4f5f2a051df3653fa1ec86e01f371d19c5
Likhith-Sreekar/PYTHN-PROGRAMS
/addition.py
157
3.96875
4
def addition(no1,no2): Result=no1+no2 return Result a=int(input('Enter the 1st number')) b=int(input('Enter the 2nd number')) print(addition(a,b))
ee7879ca5072d5cbd6c99433d5fac43371752348
balbok0/MC-and-Jet-Tutorial
/scicomp/debug/conways_game_of_life/2_conway_pre_formatted.py
1,049
3.84375
4
#!/usr/bin/env python """ Conway's game of life example, part two. This does not conform to PEP8 standards. Use pep8 to check most standards, and then fix the others by eye. """ def conway(population, generations = 100): for i in range(generations): population = evolve(population) return population def evolve(population): activeCells = population[:] for cell in population: for neighbor in neighbors(cell): if neighbor not in activeCells: activeCells.append(neighbor) newPopulation = [] for cell in activeCells: count = sum(neighbor in population for neighbor in neighbors(cell)) if count == 3 or (count == 2 and cell in population): if cell not in newPopulation: newPopulation.append(cell) return newPopulation def neighbors(cell): x, y = cell return [(x, y), (x+1, y), (x-1, y), (x, y+1), (x, y-1), (x+1, y+1), (x+1, y-1), (x-1, y+1), (x-1, y-1)] glider = [(0, 0), (1, 0), (2, 0), (0, 1), (1, 2)] print conway(glider)
fa3a024cd1fec523eb0023f13eb5bd1485e8e123
daminiamin/Dictionary-WordCount
/wordcount.py
344
3.515625
4
# put your code here. test_file = open("twain.txt") def counts_words(phrase): word_count = {} for line in test_file: words = line.split() for word in words: word_count[word] = word_count.get(word, 0) + 1 for word in word_count.items(): print(f"{word[0]} {word[1]}") counts_words(test_file)
62442ae7e65f511647a46820a322ba70380eab54
TOlmsteadWSCU/CS-310-Python-Projects
/Bank_TOlmstead_310/Account.py
748
3.765625
4
# class for one account class Account: ''' An account consists of an owner and a balance ''' def __init__(self,account_num, owner,init_balance=0): self.account_num = account_num self.owner = owner self.balance = init_balance def credit(self,amt): self.balance+=amt def debit(self,amt): self.balance-=amt def query(self): return(self.balance) def __str__(self): return("owner:"+str(self.owner)+ "\nbalance:"+str(self.balance)+"\n") # tests if __name__ == "__main__": a1 = Account(1,"bobo",60) a2 = Account(2,"coco",500) print(a1) print(a2) a1.credit(50) print(a1.query()) a1.debit(50) print(a1.query())
5bb4b5f9a9d2b22fde70d344a9da5230e75354f8
Eiman24/FM6001
/fishrename.py
2,027
3.546875
4
# 对cocos捕鱼资源文件进行重命名 import os, sys def main(): pass # list_foldernames = ['dragon', 'quanpingzhadan', 'shayu', 'haitun', 'chuitousha', 'bianfuyu', 'hetun', 'jianzuiyu', 'shiziyu', 'dianman', 'xiaowugui', 'denglongyu', 'hudieyu', 'xiaochouyu'] # for foldername in list_foldernames: # name_changer(foldername + os.sep + foldername + '_move', foldername + '_move_') # name_changer(foldername + os.sep + foldername + '_capture', foldername + '_capture_') def name_changer(fish_folder, ren_str): # 定义文件路径 # first_folder = 'fish_png_cocos' # second_folder = fish_folder filedir = fish_folder # 提取、排序 list_rawname = [] for filename in os.listdir(filedir): list_rawname.append(filename) list_rawname.sort() if '.DS_Store' in list_rawname: list_rawname.remove('.DS_Store') # 核对未更改前的文件名 print(list_rawname) # 筛选 name_dic = dict() for rawname in list_rawname: suffix = os.path.splitext(rawname)[-1] if suffix in name_dic.keys(): name_dic[suffix] += 1 else: name_dic[suffix] = 1 print(name_dic) my_suffix = max(name_dic, key=name_dic.get) spam = [] for rawname in list_rawname: print(rawname) suffix = os.path.splitext(rawname)[-1] if suffix != my_suffix: spam.append(rawname) for spamname in spam: list_rawname.remove(spamname) print(spam) # 修改 rename_string = ren_str i = 0 for rawname in list_rawname: src = filedir + os.sep + rawname # 提取文件后缀名 suffix = os.path.splitext(rawname)[-1] zero_count = len(str(len(list_rawname))) #print(zero_count) dst = filedir + os.sep + ren_str + '0'*(zero_count - len(str(i))) + str(i) + suffix os.rename(src, dst) i += 1 # notice print('重命名成功') if __name__ == '__main__': main()
4bba499b572fe4986ef55e08439058a60ab5b4fd
parthjpatelx/deviations
/app.py
2,164
3.890625
4
# Reading an excel file using Python import xlrd, datetime import xlwt from xlwt import Workbook def write_deviation(last_name, date_string, cycle_name, IRB_number): my_deviation = f"Patient {last_name} was assessed on {date_string} for {cycle_name} on {IRB_number}. At this visit, the patient was dispensed drug. However, since the patient was unabel to travel to clinic due to circumstances surrounding COVID-19, the drug was shipped to them. This event constitues a protocol deviation." return my_deviation # Give the location of the file- https://www.geeksforgeeks.org/reading-excel-file-using-python/ loc = ('/Users/parth/drugshipments.xls') # To open Workbook wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) #create a new workbook to write writing_wb = Workbook() sheet1 = writing_wb.add_sheet('Deviations') all_deviations= [] IRB_number = "19-257" LAST_COLUMN = 6 DATE_COLUMN = 1 VISIT_COLUMN = 2 NAME_COLUMN = 3 for i in range(sheet.nrows): MRN = cycle_name = last_name = string_date = "" for j in range(sheet.ncols): #if the column represents a date, we need to treat it differently if j == DATE_COLUMN: #cast the date string into an integer xl_date = int(sheet.cell_value(i,DATE_COLUMN)) #convert integer into a datetime object datetime_date = xlrd.xldate_as_datetime(xl_date, 0) date_object = datetime_date.date() #convert datetime object into string string_date = date_object.isoformat() sheet1.write(i, j, string_date) else: cell_value = sheet.cell_value(i,j) if j == VISIT_COLUMN: cycle_name = cell_value if j == NAME_COLUMN: last_name = cell_value sheet1.write(i,j, cell_value) deviation = write_deviation(last_name, string_date, cycle_name, IRB_number) all_deviations.append(deviation) number_deviations = len(all_deviations) for n in range(number_deviations): current_deviation = all_deviations[n] sheet1.write(n,LAST_COLUMN, current_deviation) writing_wb.save('deviations4.xls')
b6bf1a9a7938250f814500050793e86a23f35b32
aalyar/Alya-Ramadhani_I0320123_Mas-Abyan_Tugas2
/I0320123_soal1_tugas2.py
1,043
3.859375
4
#menghitung luas persegi panjang print("Luas Persegi Panjang") p = float(input("Masukkan panjang: ")) l = float(input("Masukkan lebar: ")) luas_persegi_panjang = p * l print("luas persegi panjang:", luas_persegi_panjang) print("---------------") #menghitung luas lingkaran print("Luas Lingkaran") r = float(input("Masukkan jari-jari: ")) phi = 3.14 luas_lingkaran = 3.14 * (r ** 2) print("luas lingkaran:", luas_lingkaran) print("---------------") #menghitung luas kubus print("Luas Kubus") r = float(input("Masukkan rusuk: ")) luas_kubus = 6 * r * r print("luas kubus:", luas_kubus) print("---------------") #menghitung nilai suhu Celcius ke Fahrenheit print("Konversi suhu (Celcius ke Fahrenheit)") C = float(input("Masukkan suhu (Celcius): ")) F = (9/5 * C) + 32 print ("Celcius: ", C) print("Fahrenheit: ", F) print("---------------") #menghitung nilai suhu Reamur ke Kelvin print("Konversi suhu (Reamur ke Kelvin)") R = float(input("Masukkan suhu (Reamur): ")) K = (5/4 * R) + 273 print("Reamur: ", R) print("Kelvin: ", K)
62c04de5e4a5b2f1fb9b4526cd62aea1cc781fa7
audtjf4008/programming
/0624/dna.py
853
3.734375
4
def comp(seq): comp_dict={'A':'T','T':'A','C':'G','G':'C'} seq_comp = "" for char in seq: if char in comp_dict: seq_comp += comp[char] else: seq_comp += '?' retrun seq_comp def rev(seq): seq_dna = "ATGC" seq_rev = "" for char in seq: if char in seq_dna: seq_rev += char else: seq_rev += '?' seq_rev = ''.join(reversed(seq_rev)) def rev_comp(seq): tmp = comp(seq) return rev(tmp) src = input("DNA sequence : ") cvnt = int(input("1(comp), 2(Rev), 3(Rev_comp): ")) if (cvnt >= 1 and cnvt <= 3): if (cnvt ==1): rst = comp(src) elif (cnvt == 2): rst = rev(src) else: ret = rev_comp(src) print(src, "->", rst) else: print("1(comp), 2(Rev), 3(Rev_comp)!!")
d366f6bc0285023ec30a6ff8cb2e236c3f6e477f
JEONINSUCK/PythonChallenge
/pythonchallenge stage 15.py
662
3.59375
4
import re import calendar as cal def cal_year(year): if (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)): return True else: return False data = [] for year in range(1000,2017): if cal_year(year)==True: data.append(year) else: continue string = "" f = [] for i in data: string+=str(i) q = re.compile('[1]..[6]') year_data = q.findall(string) print(year_data) result = [] for i in year_data: if (cal.weekday(int(i),1,26)==0): print(cal.prmonth(int(i),1)) result.append(i) print(year_data) print(result) for i in result: print(cal.prmonth(int(i), 1)) #print(cal.calendar(1976))
c29038f295cdeb6c21fd9664df9d3898d19d7ede
KamilPrzybysz/python
/04.03.18/zad3/zad3.py
86
3.890625
4
lista=[1,2,3,4,5,6,7,8,9,10] print(lista) lista=list(i*3 for i in lista) print(lista)
3de7a31e38f1766045412875190ac2293f627c99
KamilPrzybysz/python
/04.03.18/zad6/zad6.py
480
3.59375
4
def funkcja(wektor1, wektor2): iloczyn=0 c=len(wektor1) for i in range(c): iloczyn+=wektor1[i]*wektor2[i] return iloczyn a=int(input('Podaj dlugosc wektorow: ')) w1=[] w2=[] for i in range(a): w1.append(int(input('Podaj '+str(i+1)+' wartosc do wektora w1: '))) print('-------------') for i in range(a): w2.append(int(input('Podaj '+str(i+1)+' wartosc do wektora w2: '))) print('Iloczyn skalarny '+str(w1)+' i '+str(w2)+' to '+str(funkcja(w1,w2)))
b2d765b6068e05992dbce84a502fadba875fb304
jvfd3/DataStructure
/Lists/LE2/Codigos/Programas Exemplo 7 - Casamento de parênteses em Python/Casamento_Parenteses.py
1,080
3.953125
4
# Livro: Data Structures and Algorithms Using Python. Rance Necaise. 2011. # casamento_parenteses.py - # Verifica o balanceamento de parenteses (, { e [ usando uma pilha em Python. from lliststack import Stack # Nome do Arquivo a abrir FILE_NAME = "no-errors.txt" def main() : arquivo = open( FILE_NAME, "r" ) if isValidSource(arquivo) : print("O arquivo tem casamento de parenteses ok!") else: print("O arquivo tem um erro no casamento de parenteses!!") arquivo.close() def isValidSource( srcfile ): s = Stack() for line in srcfile : for token in line : if token in "{[(" : s.push( token ) elif token in "}])" : if s.estaVazia(): return False else : left = s.pop() if (token == "}" and left != "{") or \ (token == "]" and left != "[") or \ (token == ")" and left != "(") : return False return s.estaVazia() # Executa a rotina principal main()
90a3fab2b6574e51e6330ee053c5d10c472dbae7
BirgerK/KL_HAW
/MDP/Aufgabe4/Birger/MDP_Aufgabe4/src/Simulation/Elevator.py
4,983
3.6875
4
import Simulation from Simulation.Statuses import ElevatorStatus, DoorStatus, Direction, CallStatus class Elevator(object): 'An elevator which transports people vertically in a building.' def __init__(self, elevator_id, start_in_floor, scheduler): self._id = elevator_id self._current_floor = start_in_floor self._calls = [] self._direction = None self._status = ElevatorStatus.waiting self._door_status = DoorStatus.open self._scheduler = scheduler def is_driving_in_direction_of(self, floor): result = False if self._direction == Direction.up: result = floor >= self._current_floor if self._direction == Direction.down: result = floor <= self._current_floor return result def act(self, env): # print ' elevator #' + str(self._id) + " is acting" if self._status == ElevatorStatus.waiting and self.stop_in_floors: # print ' elevator is getting busy' self._status = ElevatorStatus.busy elif self._status == ElevatorStatus.busy: self._direction = Elevator.get_direction_by_floors(self._current_floor, self.target_floor) # print ' target set to floor ' + str(self.target_floor) if self._door_status == DoorStatus.open: # print ' doors closed' self._door_status = DoorStatus.closed return if self._door_status == DoorStatus.closed: target_floor = self.target_floor if self._current_floor == target_floor: # print ' target reached' # target_floor is reached # print ' doors opened' self._door_status = DoorStatus.open if not self.is_going_to_drive_in_current_direction(): self._direction = None self.update_call_statuses(env.now) self.cleanup_calls() self._calls = self._scheduler.get_priorized_call_list(self) if not self.stop_in_floors: self._status = ElevatorStatus.waiting return self._direction = self.get_direction_by_floors(self._current_floor, target_floor) if self._direction == Direction.up: # print ' driving up' self._current_floor += 1 return if self._direction == Direction.down: # print ' driving down' self._current_floor -= 1 return # else: # print ' but nothing to do' def is_going_to_drive_in_current_direction(self): result = False for target in self.stop_in_floors: if self.direction == Direction.up and target >= self.current_floor: result = True if self.direction == Direction.down and target < self.current_floor: result = True return result def update_call_statuses(self, now): for call in self._calls: call.processed_by_elevator = self._id call.update_status(self._current_floor, now) def cleanup_calls(self): calls = list(self._calls) for call in calls: if call.call_status == CallStatus.done: self._calls.remove(call) @staticmethod def get_direction_by_floors(start_floor, end_floor): result = None if end_floor is None: return None if start_floor >= Simulation.MAX_FLOOR: result = Direction.down if start_floor < end_floor: result = Direction.up if start_floor >= end_floor: result = Direction.down return result @property def id(self): return self._id @property def status(self): return self._status @property def current_floor(self): return self._current_floor @property def target_floor(self): if self.stop_in_floors: return self.stop_in_floors[0] else: return None @property def door_status(self): return self._door_status @property def calls(self): return self._calls @calls.setter def calls(self, value): self._calls = value @property def stop_in_floors(self): result = [] for elevator_call in self.calls: if elevator_call.is_already_known(Simulation.env.now): result.append(elevator_call.next_relevant_floor) else: if elevator_call.will_be_previously_known and elevator_call.call_status == CallStatus.open: result.append(elevator_call.next_relevant_floor) return result @property def direction(self): return self._direction
308d8f4dca8b463b3717c5b015f55ff2efad0a39
jvano74/advent_of_code
/2019/day_19_test.py
15,791
3.828125
4
import pytest from typing import List, NamedTuple class Puzzle: """ --- Day 19: Tractor Beam --- Unsure of the state of Santa's ship, you borrowed the tractor beam technology from Triton. Time to test it out. When you're safely away from anything else, you activate the tractor beam, but nothing happens. It's hard to tell whether it's working if there's nothing to use it on. Fortunately, your ship's drone system can be configured to deploy a drone to specific coordinates and then check whether it's being pulled. There's even an Intcode program (your puzzle input) that gives you access to the drone system. The program uses two input instructions to request the X and Y position to which the drone should be deployed. Negative numbers are invalid and will confuse the drone; all numbers should be zero or positive. Then, the program will output whether the drone is stationary (0) or being pulled by something (1). For example, the coordinate X=0, Y=0 is directly in front of the tractor beam emitter, so the drone control program will always report 1 at that location. To better understand the tractor beam, it is important to get a good picture of the beam itself. For example, suppose you scan the 10x10 grid of points closest to the emitter: X 0-> 9 0#......... |.#........ v..##...... ...###.... ....###... Y .....####. ......#### ......#### .......### 9........## In this example, the number of points affected by the tractor beam in the 10x10 area closest to the emitter is 27. However, you'll need to scan a larger area to understand the shape of the beam. How many points are affected by the tractor beam in the 50x50 area closest to the emitter? (For each of X and Y, this will be 0 through 49.) Your puzzle answer was 110. --- Part Two --- You aren't sure how large Santa's ship is. You aren't even sure if you'll need to use this thing on Santa's ship, but it doesn't hurt to be prepared. You figure Santa's ship might fit in a 100x100 square. The beam gets wider as it travels away from the emitter; you'll need to be a minimum distance away to fit a square of that size into the beam fully. (Don't rotate the square; it should be aligned to the same axes as the drone grid.) For example, suppose you have the following tractor beam readings: #....................................... .#...................................... ..##.................................... ...###.................................. ....###................................. .....####............................... ......#####............................. ......######............................ .......#######.......................... ........########........................ .........#########...................... ..........#########..................... ...........##########................... ...........############................. ............############................ .............#############.............. ..............##############............ ...............###############.......... ................###############......... ................#################....... .................########OOOOOOOOOO..... ..................#######OOOOOOOOOO#.... ...................######OOOOOOOOOO###.. ....................#####OOOOOOOOOO##### .....................####OOOOOOOOOO##### .....................####OOOOOOOOOO##### ......................###OOOOOOOOOO##### .......................##OOOOOOOOOO##### ........................#OOOOOOOOOO##### .........................OOOOOOOOOO##### ..........................############## ..........................############## ...........................############# ............................############ .............................########### In this example, the 10x10 square closest to the emitter that fits entirely within the tractor beam has been marked O. Within it, the point closest to the emitter (the only highlighted O) is at X=25, Y=20. Find the 100x100 square closest to the emitter that fits entirely within the tractor beam; within that square, find the point closest to the emitter. What value do you get if you take that point's X coordinate, multiply it by 10000, then add the point's Y coordinate? (In the example above, this would be 250020.) Your puzzle answer was 17302065. """ pass class Point(NamedTuple): x: int y: int class BoxRange(NamedTuple): ul: Point lr: Point HALT = 99 ADD = 1 MULTIPLY = 2 INPUT = 3 OUTPUT = 4 JUMP_IF_TRUE = 5 JUMP_IF_FALSE = 6 LESS_THAN = 7 EQUAL = 8 BASE = 9 class Program: def __init__(self, program): self.head = 0 self.relative_base = 0 self.disk = list(program) self.memory = list(program) self.input = [] self.output = [] self.opt_hx = [] def reset(self): self.head = 0 self.relative_base = 0 self.memory = list(self.disk) self.input = [] self.output = [] self.opt_hx = [] def process(self, op_code, modes): if op_code in [INPUT, OUTPUT, BASE]: self.process_one_parameter_operation(modes, op_code) elif op_code in [JUMP_IF_TRUE, JUMP_IF_FALSE]: self.process_two_parameter_operation(modes, op_code) elif op_code in [ADD, MULTIPLY, LESS_THAN, EQUAL]: self.process_three_parameter_operation(modes, op_code) else: raise SyntaxError(f'Unknown optcode {op_code}\nOpt Hx:\n{self.opt_hx}') def read_memory(self, pos): if len(self.memory) - 1 < pos: self.memory.extend([0]*(pos + 1 - len(self.memory))) return self.memory[pos] def write_memory(self, pos, mode, val): if mode == 2: pos += self.relative_base if len(self.memory) - 1 < pos: self.memory.extend([0]*(pos + 1 - len(self.memory))) self.memory[pos] = val def get_val(self, offset=1, mode=0): val = self.read_memory(self.head + offset) if mode == 0: return self.read_memory(val) if mode == 2: return self.read_memory(self.relative_base + val) return val def process_one_parameter_operation(self, modes, op_code): if op_code == INPUT: if len(self.input) == 0: return mem_loc = self.memory[self.head + 1] self.write_memory(mem_loc, modes % 10, self.input.pop(0)) elif op_code == OUTPUT: self.output.append(self.get_val(1, modes % 10)) elif op_code == BASE: self.relative_base += self.get_val(1, modes % 10) else: raise SyntaxError(f'Unknown op_code {op_code}') self.head += 2 def process_two_parameter_operation(self, modes, op_code): reg_a = self.get_val(1, modes % 10) modes //= 10 reg_b = self.get_val(2, modes % 10) if op_code == JUMP_IF_TRUE: if reg_a: self.head = reg_b return elif op_code == JUMP_IF_FALSE: if not reg_a: self.head = reg_b return else: raise SyntaxError(f'Unknown op_code {op_code}') self.head += 3 def process_three_parameter_operation(self, modes, op_code): reg_a = self.get_val(1, modes % 10) modes //= 10 reg_b = self.get_val(2, modes % 10) modes //= 10 mem_loc = self.memory[self.head + 3] if op_code == ADD: self.write_memory(mem_loc, modes % 10, reg_a + reg_b) elif op_code == MULTIPLY: self.write_memory(mem_loc, modes % 10, reg_a * reg_b) elif op_code == LESS_THAN: self.write_memory(mem_loc, modes % 10, 1 if reg_a < reg_b else 0) elif op_code == EQUAL: self.write_memory(mem_loc, modes % 10, 1 if reg_a == reg_b else 0) else: raise SyntaxError(f'Unknown op_code {op_code}') self.head += 4 def run(self, std_in: List[int] = None) -> int: if std_in is not None: self.input = std_in while True: op_code = self.memory[self.head] % 100 modes = self.memory[self.head] // 100 if op_code == HALT: return 0 if op_code == INPUT and len(self.input) == 0: return -1 self.process(op_code, modes) with open('day_19_input.txt') as fp: raw = fp.read() SRC = [int(d) for d in raw.split(',')] DRONE = Program(SRC) class Image: DELTAS = [Point(0, 1), Point(1, 0), Point(0, -1), Point(-1, 0)] def __init__(self, program): self.program = program self.beam = set() def is_point_in_beam(self, x, y): self.program.reset() run_result = self.program.run([x, y]) if run_result != 0: raise ChildProcessError return True if self.program.output.pop() == 1 else False def scan_range(self, p1: Point, p4: Point): for y in range(p1.y, p4.y + 1): seen_beam = False if y < 10: x_max = 3 * y + 1 else: x_max = p4.x + 1 x_start = p1.x for x in range(x_start, x_max): if self.is_point_in_beam(x, y): if not seen_beam: x_start = x seen_beam = True self.beam.add(Point(x, y)) elif seen_beam: break def does_region_fit_in_beam(self, box: BoxRange): p1 = box.ul p4 = box.lr if self.is_point_in_beam(p1.x, p1.y) and self.is_point_in_beam(p4.x, p1.y) and \ self.is_point_in_beam(p1.x, p4.y) and self.is_point_in_beam(p4.x, p4.y): return True return False def sum_in_range(self, p1: Point, p4: Point): ramge_sum = 0 for x in range(p1.x, p4.x + 1): for y in range(p1.y, p4.y + 1): if Point(x, y) in self.beam: ramge_sum += 1 return ramge_sum def print_region(self, p1: Point, p4: Point, box: BoxRange = None): print(f'UL={p1} LR={p4} box={box}') if box is None: box_x = range(0, 0) box_y = range(0, 0) else: box_x = range(box.ul.x, box.lr.x + 1) box_y = range(box.ul.y, box.lr.y + 1) for y in range(p1.y, p4.y + 1): for x in range(p1.x, p4.x + 1): if Point(x, y) in self.beam: if x in box_x and y in box_y: print('o', end='') else: print('#', end='') else: if x in box_x and y in box_y: print('x', end='') else: print('.', end='') print(y) def make_box(ll: Point, length: int, height: int): return BoxRange(Point(ll.x, ll.y - height), Point(ll.x + length, ll.y)) def search_for_box(lower: Point, size: int): image = Image(DRONE) santa_ll = lower santa_box = make_box(santa_ll, size - 1, size - 1) while not image.does_region_fit_in_beam(santa_box): # move down and over y = santa_ll.y + 1 x = santa_ll.x while not image.is_point_in_beam(x, y): x += 1 santa_ll = Point(x, y) santa_box = make_box(santa_ll, size - 1, size - 1) santa_ll_range = make_box(Point(santa_ll.x - 15, santa_ll.y + 15), 30, 30) santa_ur = Point(santa_ll.x + size, santa_ll.y - size) santa_ur_range = make_box(Point(santa_ur.x - 15, santa_ur.y + 15), 30, 30) image.scan_range(santa_ll_range.ul, santa_ll_range.lr) image.print_region(santa_ll_range.ul, santa_ll_range.lr, santa_box) image.scan_range(santa_ur_range.ul, santa_ur_range.lr) image.print_region(santa_ur_range.ul, santa_ur_range.lr, santa_box) print(santa_box) return santa_box.ul.x * 10000 + santa_box.ul.y def test_submission(): image = Image(DRONE) image.scan_range(Point(0, 0), Point(49, 49)) image.print_region(Point(0, 0), Point(49, 49)) assert image.sum_in_range(Point(0, 0), Point(49, 49)) == 110 def test_box_stuff(): image = Image(DRONE) image.scan_range(Point(220, 280), Point(300, 300)) smaller_box = make_box(Point(300 - 60, 299), 13, 13) image.print_region(Point(220, 280), Point(300, 300), smaller_box) assert image.does_region_fit_in_beam(smaller_box) big_box = make_box(Point(300 - 60, 299), 13, 14) image.print_region(Point(220, 280), Point(300, 300), big_box) assert image.does_region_fit_in_beam(big_box) is False def test_submission2(): assert search_for_box(Point(0, 10), 100) == 17302065 def test_program(): error_program = Program([555]) with pytest.raises(SyntaxError): error_program.run([]) p1 = Program([1, 0, 0, 0, 99]) assert p1.run([]) == 0 and p1.memory == [2, 0, 0, 0, 99] p2 = Program([2, 3, 0, 3, 99]) assert p2.run([]) == 0 and p2.memory == [2, 3, 0, 6, 99] p3 = Program([2, 4, 4, 5, 99, 0]) assert p3.run([]) == 0 and p3.memory == [2, 4, 4, 5, 99, 9801] p4 = Program([1, 1, 1, 4, 99, 5, 6, 0, 99]) assert p4.run([]) == 0 and p4.memory == [30, 1, 1, 4, 2, 5, 6, 0, 99] # IO TESTS io = Program([3, 0, 4, 0, 99]) assert io.run([12]) == 0 and io.output == [12] and io.memory == [12, 0, 4, 0, 99] # COMPARE TESTS p5 = Program([3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8]) assert p5.run([8]) == 0 and p5.output == [1] p5.reset() assert p5.run([7]) == 0 and p5.output == [0] p6 = Program([3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8]) assert p6.run([7]) == 0 and p6.output == [1] p6.reset() assert p6.run([8]) == 0 and p6.output == [0] p7 = Program([3, 3, 1108, -1, 8, 3, 4, 3, 99]) assert p7.run([8]) == 0 and p7.output == [1] p8 = Program([3, 3, 1107, -1, 8, 3, 4, 3, 99]) assert p8.run([7]) == 0 and p8.output == [1] p8.reset() assert p8.run([8]) == 0 and p8.output == [0] # JUMP TESTS pjump1 = Program([3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9]) assert pjump1.run([0]) == 0 and pjump1.output == [0] pjump1.reset() assert pjump1.run([4]) == 0 and pjump1.output == [1] pjump2 = Program([3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1]) assert pjump2.run([0]) == 0 and pjump2.output == [0] pjump2.reset() assert pjump2.run([7]) == 0 and pjump2.output == [1] pbig = Program([3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99]) assert pbig.run([7]) == 0 and pbig.output == [999] pbig.reset() assert pbig.run([8]) == 0 and pbig.output == [1000] pbig.reset() assert pbig.run([9]) == 0 and pbig.output == [1001] # BASE TESTS copy_code = [109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99] copy_program = Program(copy_code) assert copy_program.run([]) == 0 and copy_program.output == copy_code digit_program = Program([1102, 34915192, 34915192, 7, 4, 7, 99, 0]) assert digit_program.run([]) == 0 and digit_program.output == [1219070632396864] large_digit_program = Program([104, 1125899906842624, 99]) assert large_digit_program.run([]) == 0 and large_digit_program.output == [1125899906842624]
9f1b37c28e8170fb67895bd40725672c8e4bc742
jvano74/advent_of_code
/2015/day_21_test.py
7,514
4.1875
4
from typing import NamedTuple class Puzzle: """ --- Day 21: RPG Simulator 20XX --- Little Henry Case got a new video game for Christmas. It's an RPG, and he's stuck on a boss. He needs to know what equipment to buy at the shop. He hands you the controller. In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes first. Each attack reduces the opponent's hit points by at least 1. The first character at or below 0 hit points loses. Damage dealt by an attacker each turn is equal to the attacker's damage score minus the defender's armor score. An attacker always does at least 1 damage. So, if the attacker has a damage score of 8, and the defender has an armor score of 3, the defender loses 5 hit points. If the defender had an armor score of 300, the defender would still lose 1 hit point. Your damage score and armor score both start at zero. They can be increased by buying items in exchange for gold. You start with no items and have as much gold as you need. Your total damage or armor is equal to the sum of those stats from all of your items. You have 100 hit points. Here is what the item shop is selling: Weapons: Cost Damage Armor Dagger 8 4 0 Shortsword 10 5 0 Warhammer 25 6 0 Longsword 40 7 0 Greataxe 74 8 0 Armor: Cost Damage Armor Leather 13 0 1 Chainmail 31 0 2 Splintmail 53 0 3 Bandedmail 75 0 4 Platemail 102 0 5 Rings: Cost Damage Armor Damage +1 25 1 0 Damage +2 50 2 0 Damage +3 100 3 0 Defense +1 20 0 1 Defense +2 40 0 2 Defense +3 80 0 3 You must buy exactly one weapon; no dual-wielding. Armor is optional, but you can't use more than one. You can buy 0-2 rings (at most one for each hand). You must use any items you buy. The shop only has one of each item, so you can't buy, for example, two rings of Damage +3. For example, suppose you have 8 hit points, 5 damage, and 5 armor, and that the boss has 12 hit points, 7 damage, and 2 armor: The player deals 5-2 = 3 damage; the boss goes down to 9 hit points. The boss deals 7-5 = 2 damage; the player goes down to 6 hit points. The player deals 5-2 = 3 damage; the boss goes down to 6 hit points. The boss deals 7-5 = 2 damage; the player goes down to 4 hit points. The player deals 5-2 = 3 damage; the boss goes down to 3 hit points. The boss deals 7-5 = 2 damage; the player goes down to 2 hit points. The player deals 5-2 = 3 damage; the boss goes down to 0 hit points. In this scenario, the player wins! (Barely.) You have 100 hit points. The boss's actual stats are in your puzzle input. What is the least amount of gold you can spend and still win the fight? --- Part Two --- Turns out the shopkeeper is working with the boss, and can persuade you to buy whatever items he wants. The other rules still apply, and he still only has one of each item. What is the most amount of gold you can spend and still lose the fight? """ pass class Item(NamedTuple): name: str cost: int damage: int armor: int def __lt__(self, other): return self.cost < other.cost def __add__(self, other): return Item(f'{self.name}, {other.name}', self.cost + other.cost, self.damage + other.damage, self.armor + other.armor) def test_items(): assert Weapons[0] + Weapons[1] == Item('Dagger, Shortsword', 18, 9, 0) class Stats(NamedTuple): name: str hp: int damage: int armor: int def attacks(self, other, print_combat=False): """ Damage dealt by an attacker each turn is equal to the attacker's damage score minus the defender's armor score. An attacker always does at least 1 damage. So, if the attacker has a damage score of 8, and the defender has an armor score of 3, the defender loses 5 hit points. If the defender had an armor score of 300, the defender would still lose 1 hit point. """ damage_delt = self.damage - other.armor if damage_delt < 1: damage_delt = 1 if print_combat: print(f'{self.name} deals {damage_delt}; {other.name} down to {other.hp - damage_delt} hp') return Stats(other.name, other.hp - damage_delt, other.damage, other.armor) class Player: def __init__(self, enemy, items, hp=100): self.items = items self.enemy = enemy self.stats = Stats('Player', hp, items.damage, items.armor) def run_combat(self, print_combat=False): while True: self.enemy = self.stats.attacks(self.enemy, print_combat) if self.enemy.hp <= 0: if print_combat: print('You won') return 'You won' self.stats = self.enemy.attacks(self.stats, print_combat) if self.stats.hp <= 0: if print_combat: print('You lost') return 'You lost' def test_player(): print() player1 = Player(Stats('Sample Boss', 12, 7, 2), Item('Total Items', 0, 5, 5), 8) assert player1.run_combat(print_combat=True) == 'You won' # Real game values INPUT_BOSS = Stats('Boss', 104, 8, 1) Weapons = [Item('Dagger', 8, 4, 0), Item('Shortsword', 10, 5, 0), Item('Warhammer', 25, 6, 0), Item('Longsword', 40, 7, 0), Item('Greataxe', 74, 8, 0)] Armor = [Item('Leather', 13, 0, 1), Item('Chainmail', 31, 0, 2), Item('Splintmail', 53, 0, 3), Item('Bandedmail', 75, 0, 4), Item('Platemail', 102, 0, 5)] Rings = [Item('Damage +1', 25, 1, 0), Item('Damage +2', 50, 2, 0), Item('Damage +3', 100, 3, 0), Item('Defense +1', 20, 0, 1), Item('Defense +2', 40, 0, 2), Item('Defense +3', 80, 0, 3)] def generate_player_items(weapons, armor, rings): weapon_only = set(weapons) weapon_and_armor = set() for w in weapon_only: for a in armor: weapon_and_armor.add(w + a) ring_options = set() for i in range(0, len(rings)): ring_options.add(rings[i]) for j in range(i+1, len(rings)): ring_options.add(rings[i] + rings[j]) non_ring_options = weapon_only.union(weapon_and_armor) total_options = set(non_ring_options) for option in non_ring_options: for rings in ring_options: total_options.add(option + rings) return sorted(list(total_options)) def find_solution(win=True): possible_gear = generate_player_items(Weapons, Armor, Rings) if not win: possible_gear = reversed(possible_gear) for gear in possible_gear: player1 = Player(INPUT_BOSS, gear) if win and player1.run_combat() == 'You won': return player1.items elif not win and player1.run_combat() != 'You won': return player1.items def test_find_solution(): assert find_solution() == Item(name='Longsword, Leather, Damage +1', cost=78, damage=8, armor=1) def test_find_solution2(): assert find_solution(win=False) == Item(name='Dagger, Damage +3, Defense +2', cost=148, damage=7, armor=2)
8c4df39a55b73cc8d7786370c03137bc3074cab5
jvano74/advent_of_code
/2015/day_03_test.py
3,093
4.09375
4
def move(d, x, y): if d == ">": x += 1 elif d == "<": x -= 1 elif d == "^": y += 1 elif d == "v": y -= 1 return (x, y) def ans(directions): """ --- Day 3: Perfectly Spherical Houses in a Vacuum --- Santa is delivering presents to an infinite two-dimensional grid of houses. He begins by delivering a present to the house at his starting location, and then an elf at the North Pole calls him via radio and tells him where to move next. Moves are always exactly one house to the north (^), south (v), east (>), or west (<). After each move, he delivers another present to the house at his new location. However, the elf back at the north pole has had a little too much eggnog, and so his directions are a little off, and Santa ends up visiting some houses more than once. How many houses receive at least one present? For example: > delivers presents to 2 houses: one at the starting location, and one to the east. ^>v< delivers presents to 4 houses in a square, including twice to the house at his starting/ending location. ^v^v^v^v^v delivers a bunch of presents to some very lucky children at only 2 houses. """ presents = dict() (x, y) = (0, 0) presents[(x, y)] = 1 for d in directions: (x, y) = move(d, x, y) presents[(x, y)] = 1 return len(presents) def robot_ans(directions): """ --- Part Two --- The next year, to speed up the process, Santa creates a robot version of himself, Robo-Santa, to deliver presents with him. Santa and Robo-Santa start at the same location (delivering two presents to the same starting house), then take turns moving based on instructions from the elf, who is eggnoggedly reading from the same script as the previous year. This year, how many houses receive at least one present? For example: ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa goes south. ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa end up back where they started. ^v^v^v^v^v now delivers presents to 11 houses, with Santa going one direction and Robo-Santa going the other. """ presents = dict() (x, y) = (0, 0) presents[(x, y)] = 1 (rx, ry) = (0, 0) presents[(rx, ry)] = 1 for who, direction in enumerate(directions): if who % 2 == 0: (x, y) = move(direction, x, y) presents[(x, y)] = 1 else: (rx, ry) = move(direction, rx, ry) presents[(rx, ry)] = 1 return len(presents) def test_houses_visited(): assert ans(">") == 2 assert ans("^>v<") == 4 assert ans("^v^v^v^v^v") == 2 def test_robot_houses_visited(): assert robot_ans("^>") == 3 assert robot_ans("^>v<") == 3 assert robot_ans("^v^v^v^v^v") == 11 def test_submission(): fp = open("./input_day_3.txt", "r") if fp.mode == "r": submission_input = fp.read() assert robot_ans(submission_input) == 2639
58899a589a4d90c428776ed8f74fc59fb5b2eff3
jvano74/advent_of_code
/2016/day_04_test.py
4,107
3.8125
4
from collections import defaultdict class Puzzle: """ --- Day 4: Security Through Obscurity --- Finally, you come across an information kiosk with a list of rooms. Of course, the list is encrypted and full of decoy data, but the instructions to decode the list are barely hidden nearby. Better remove the decoy data first. Each room consists of an encrypted name (lowercase letters separated by dashes) followed by a dash, a sector ID, and a checksum in square brackets. A room is real (not a decoy) if the checksum is the five most common letters in the encrypted name, in order, with ties broken by alphabetization. For example: aaaaa-bbb-z-y-x-123[abxyz] is a real room because the most common letters are a (5), b (3), and then a tie between x, y, and z, which are listed alphabetically. a-b-c-d-e-f-g-h-987[abcde] is a real room because although the letters are all tied (1 of each), the first five are listed alphabetically. not-a-real-room-404[oarel] is a real room. totally-real-room-200[decoy] is not. Of the real rooms from the list above, the sum of their sector IDs is 1514. What is the sum of the sector IDs of the real rooms? --- Part Two --- With all the decoy data out of the way, it's time to decrypt this list and get moving. The room names are encrypted by a state-of-the-art shift cipher, which is nearly unbreakable without the right software. However, the information kiosk designers at Easter Bunny HQ were not expecting to deal with a master cryptographer like yourself. To decrypt a room name, rotate each letter forward through the alphabet a number of times equal to the room's sector ID. A becomes B, B becomes C, Z becomes A, and so on. Dashes become spaces. For example, the real name for qzmt-zixmtkozy-ivhz-343 is very encrypted name. What is the sector ID of the room where North Pole objects are stored? """ pass with open("day_04_input.txt") as f: INPUTS = [line.strip() for line in f] SAMPLES = [ "aaaaa-bbb-z-y-x-123[abxyz]", "a-b-c-d-e-f-g-h-987[abcde]", "not-a-real-room-404[oarel]", "totally-real-room-200[decoy]", ] def parse_encrypted(encrypted): a, b = encrypted.split("[") a = a.split("-") checksum = b[:-1] sector_id = int(a[-1]) words = a[0:-1] letter_list = sorted("".join(a)) return sector_id, checksum, letter_list, words def generate_frequency_string(letter_list): letter_current = letter_list[0] letter_count = 0 frequency = defaultdict(str) for c in letter_list: if c == letter_current: letter_count += 1 else: frequency[letter_count] += letter_current letter_current = c letter_count = 1 frequency[letter_count] += letter_current return "".join([s for (_, s) in sorted(frequency.items(), key=lambda x: -x[0])]) def shift_letter(c, amount): return chr((ord(c) - ord("a") + amount) % 26 + ord("a")) def shift_word(word, amount): return "".join([shift_letter(c, amount) for c in word]) def decode(encrypted): sector_id, _, _, words = parse_encrypted(encrypted) return " ".join([shift_word(w, sector_id) for w in words]) def get_sector_id(encrypted: str) -> int: sector_id, checksum, letter_list, _ = parse_encrypted(encrypted) by_frequency = generate_frequency_string(letter_list) if checksum == by_frequency[: len(checksum)]: return sector_id return 0 def test_get_sector_id(): assert sum([get_sector_id(w) for w in SAMPLES]) == 1514 assert sum([get_sector_id(w) for w in INPUTS]) == 185371 def test_gecode(): assert shift_letter("a", 1) == "b" assert shift_letter("z", 1) == "a" assert shift_letter("a", 26) == "a" assert shift_word("fdw", 23) == "cat" assert decode("qzmt-zixmtkozy-ivhz-343[asd]") == "very encrypted name" for w in INPUTS: if decode(w) == "northpole object storage": print(w) assert int(w.split("-")[3].split("[")[0]) == 984
3869487719f0196d56f2005a5af45c204295ac1b
jvano74/advent_of_code
/2015/day_02_test.py
3,121
4.125
4
def wrapping_paper_needed(input): """ --- Day 2: I Was Told There Would Be No Math --- The elves are running low on wrapping paper, and so they need to submit an order for more. They have a list of the dimensions (length l, width w, and height h) of each present, and only want to order exactly as much as they need. Fortunately, every present is a box (a perfect right rectangular prism), which makes calculating the required wrapping paper for each gift a little easier: find the surface area of the box, which is 2*l*w + 2*w*h + 2*h*l. The elves also need a little extra paper for each present: the area of the smallest side. For example: A present with dimensions 2x3x4 requires 2*6 + 2*12 + 2*8 = 52 square feet of wrapping paper plus 6 square feet of slack, for a total of 58 square feet. A present with dimensions 1x1x10 requires 2*1 + 2*10 + 2*10 = 42 square feet of wrapping paper plus 1 square foot of slack, for a total of 43 square feet. All numbers in the elves' list are in feet. How many total square feet of wrapping paper should they order? """ (l, w, h) = [int(x) for x in input.split("x")] sides = [l * w, w * h, h * l] return 2 * sum(sides) + min(sides) def test_wrapping_paper_needed(): assert wrapping_paper_needed("2x3x4") == 58 def test_wrapping_paper_sub(): with open("./day_02_input.txt", "r") as fp: total = 0 line = fp.readline() while line: total += wrapping_paper_needed(line) line = fp.readline() assert total == 1588178 def ribbon_needed(input): """ --- Part Two --- The elves are also running low on ribbon. Ribbon is all the same width, so they only have to worry about the length they need to order, which they would again like to be exact. The ribbon required to wrap a present is the shortest distance around its sides, or the smallest perimeter of any one face. Each present also requires a bow made out of ribbon as well; the feet of ribbon required for the perfect bow is equal to the cubic feet of volume of the present. Don't ask how they tie the bow, though; they'll never tell. For example: A present with dimensions 2x3x4 requires 2+2+3+3 = 10 feet of ribbon to wrap the present plus 2*3*4 = 24 feet of ribbon for the bow, for a total of 34 feet. A present with dimensions 1x1x10 requires 1+1+1+1 = 4 feet of ribbon to wrap the present plus 1*1*10 = 10 feet of ribbon for the bow, for a total of 14 feet. How many total feet of ribbon should they order? """ (l, w, h) = [int(x) for x in input.split("x")] return 2 * min(l + w, w + h, h + l) + l * w * h def test_ribbon_needed(): assert ribbon_needed("2x3x4") == 34 assert ribbon_needed("1x1x10") == 14 def test_ribbon_needed_sub(): with open("./day_02_input.txt", "r") as fp: total = 0 line = fp.readline() while line: total += ribbon_needed(line) line = fp.readline() assert total == 3783758
31edc903410b6781967b9413700b031d931133cf
jvano74/advent_of_code
/2015/day_12_test.py
4,696
4.3125
4
import re import json def string_sum(string): """ --- Day 12: JSAbacusFramework.io --- Santa's Accounting-Elves need help balancing the books after a recent order. Unfortunately, their accounting software uses a peculiar storage format. That's where you come in. They have a JSON document which contains a variety of things: arrays ([1,2,3]), objects ({"a":1, "b":2}), numbers, and strings. Your first job is to simply find all of the numbers throughout the document and add them together. For example: [1,2,3] and {"a":2,"b":4} both have a sum of 6. [[[3]]] and {"a":{"b":4},"c":-1} both have a sum of 3. {"a":[-1,1]} and [-1,{"a":1}] both have a sum of 0. [] and {} both have a sum of 0. You will not encounter any strings containing numbers. What is the sum of all numbers in the document? """ return sum([int(d) for d in re.findall(r'-?\d+', string)]) def test_sum(): assert string_sum('[1,2,3]') == 6 assert string_sum('{"a":2,"b":4}') == 6 assert string_sum('{"a":[-1,1]}') == 0 assert string_sum('[-1,{"a":1}]') == 0 assert string_sum('[]') == 0 assert string_sum('{}') == 0 def test_submission(): assert sum([string_sum(l) for l in open('day_12_input.txt', 'r')]) == 119433 def non_red_sum(string): """ --- Part Two --- Uh oh - the Accounting-Elves have realized that they double-counted everything red. Ignore any object (and all of its children) which has any property with the value "red". Do this only for objects ({...}), not arrays ([...]). [1,2,3] still has a sum of 6. [1,{"c":"red","b":2},3] now has a sum of 4, because the middle object is ignored. {"d":"red","e":[1,2,3,4],"f":5} now has a sum of 0, because the entire structure is ignored. [1,"red",5] has a sum of 6, because "red" in an array has no effect. """ return string_sum(remove_red(string)) def trim_right_to_bracket(string): cnt = 0 pos = len(string) - 1 string_array = list(string) while pos >= 0: if re.match(r'\d', string_array[pos]): string_array[pos] = '0' elif string_array[pos] == '{': cnt += 1 elif string_array[pos] == '}': cnt -= 1 if cnt == 1: break if pos == 0: raise RecursionError('Could not search back far enough...') pos -= 1 return ''.join(string_array) def trim_left_to_bracket(string): cnt = 0 pos = 0 string_array = list(string) while pos < len(string_array): if re.match(r'\d', string_array[pos]): string_array[pos] = '0' elif string_array[pos] == '{': cnt += 1 elif string_array[pos] == '}': cnt -= 1 if cnt == -1: break pos += 1 # return string[pos:] return ''.join(string_array) def remove_red(string): pieces = re.split(r':"red"', string, maxsplit=1) if len(pieces) == 1: return pieces[0] non_red = '' while len(pieces) > 1: non_red += trim_right_to_bracket(pieces[0]) + ':"red"' pieces = re.split(r':"red"', trim_left_to_bracket(pieces[1]), maxsplit=1) non_red += pieces[0] return non_red def test_remove_red(): assert remove_red('[1,2,3]') == '[1,2,3]' assert remove_red('[1,"red",5]') == '[1,"red",5]' assert remove_red('[1,{"c":"red","b":2},3]') == '[1,{"c":"red","b":0},3]' assert remove_red('{"d":"red","e":[1,2,3,4],"f":5}') == '{"d":"red","e":[0,0,0,0],"f":0}' assert remove_red('[1,{"b":2,"bb":{"m":8},"c":"red",{"d":3}},3]') == '[1,{"b":0,"bb":{"m":0},"c":"red",{"d":0}},3]' assert remove_red('[1,{"b":2,"cc":"red","bb":{"m":8},"c":"red",{"d":3}},3]') == '[1,{"b":0,"cc":"red","bb":{' \ '"m":0},"c":"red",{"d":0}},3] ' def test_remove_red_submission(): assert [remove_red(l) for l in open('day_12_input.txt', 'r')] == [] def test_submission2(): assert sum([non_red_sum(l) for l in open('day_12_input.txt', 'r')]) == 77651 # ===== SOLUTION FROM REDDIT ===== # Okay, I now see where my manual solution was going astray... def sum_object(obj): if type(obj) is int: return obj if type(obj) is list: return sum(map(sum_object, obj)) if type(obj) is dict: vals = obj.values() # remove these two lines for part one if "red" in vals: return 0 return sum(map(sum_object, vals)) else: return 0 def test_from_redit(): with open("day_12_input.txt") as f: obj = json.loads(f.read()) assert sum_object(obj) == 68466
3589a4854d2b38e36d8d56f28c18f1cbf0658266
jvano74/advent_of_code
/2021/day_22_test.py
18,996
4.34375
4
from typing import NamedTuple class Puzzle: """ --- Day 22: Reactor Reboot --- Operating at these extreme ocean depths has overloaded the submarine's reactor; it needs to be rebooted. The reactor core is made up of a large 3-dimensional grid made up entirely of cubes, one cube per integer 3-dimensional coordinate (x,y,z). Each cube can be either on or off; at the start of the reboot process, they are all off. (Could it be an old model of a reactor you've seen before?) To reboot the reactor, you just need to set all of the cubes to either on or off by following a list of reboot steps (your puzzle input). Each step specifies a cuboid (the set of all cubes that have coordinates which fall within ranges for x, y, and z) and whether to turn all of the cubes in that cuboid on or off. For example, given these reboot steps: on x=10..12,y=10..12,z=10..12 on x=11..13,y=11..13,z=11..13 off x=9..11,y=9..11,z=9..11 on x=10..10,y=10..10,z=10..10 The first step (on x=10..12,y=10..12,z=10..12) turns on a 3x3x3 cuboid consisting of 27 cubes: 10,10,10 10,10,11 10,10,12 10,11,10 10,11,11 10,11,12 10,12,10 10,12,11 10,12,12 11,10,10 11,10,11 11,10,12 11,11,10 11,11,11 11,11,12 11,12,10 11,12,11 11,12,12 12,10,10 12,10,11 12,10,12 12,11,10 12,11,11 12,11,12 12,12,10 12,12,11 12,12,12 The second step (on x=11..13,y=11..13,z=11..13) turns on a 3x3x3 cuboid that overlaps with the first. As a result, only 19 additional cubes turn on; the rest are already on from the previous step: 11,11,13 11,12,13 11,13,11 11,13,12 11,13,13 12,11,13 12,12,13 12,13,11 12,13,12 12,13,13 13,11,11 13,11,12 13,11,13 13,12,11 13,12,12 13,12,13 13,13,11 13,13,12 13,13,13 The third step (off x=9..11,y=9..11,z=9..11) turns off a 3x3x3 cuboid that overlaps partially with some cubes that are on, ultimately turning off 8 cubes: 10,10,10 10,10,11 10,11,10 10,11,11 11,10,10 11,10,11 11,11,10 11,11,11 The final step (on x=10..10,y=10..10,z=10..10) turns on a single cube, 10,10,10. After this last step, 39 cubes are on. The initialization procedure only uses cubes that have x, y, and z positions of at least -50 and at most 50. For now, ignore cubes outside this region. Here is a larger example: on x=-20..26,y=-36..17,z=-47..7 on x=-20..33,y=-21..23,z=-26..28 on x=-22..28,y=-29..23,z=-38..16 on x=-46..7,y=-6..46,z=-50..-1 on x=-49..1,y=-3..46,z=-24..28 on x=2..47,y=-22..22,z=-23..27 on x=-27..23,y=-28..26,z=-21..29 on x=-39..5,y=-6..47,z=-3..44 on x=-30..21,y=-8..43,z=-13..34 on x=-22..26,y=-27..20,z=-29..19 off x=-48..-32,y=26..41,z=-47..-37 on x=-12..35,y=6..50,z=-50..-2 off x=-48..-32,y=-32..-16,z=-15..-5 on x=-18..26,y=-33..15,z=-7..46 off x=-40..-22,y=-38..-28,z=23..41 on x=-16..35,y=-41..10,z=-47..6 off x=-32..-23,y=11..30,z=-14..3 on x=-49..-5,y=-3..45,z=-29..18 off x=18..30,y=-20..-8,z=-3..13 on x=-41..9,y=-7..43,z=-33..15 on x=-54112..-39298,y=-85059..-49293,z=-27449..7877 on x=967..23432,y=45373..81175,z=27513..53682 The last two steps are fully outside the initialization procedure area; all other steps are fully within it. After executing these steps in the initialization procedure region, 590784 cubes are on. Execute the reboot steps. Afterward, considering only cubes in the region x=-50..50,y=-50..50,z=-50..50, how many cubes are on? To begin, get your puzzle input. --- Part Two --- Now that the initialization procedure is complete, you can reboot the reactor. Starting with all cubes off, run all of the reboot steps for all cubes in the reactor. Consider the following reboot steps: on x=-5..47,y=-31..22,z=-19..33 on x=-44..5,y=-27..21,z=-14..35 on x=-49..-1,y=-11..42,z=-10..38 on x=-20..34,y=-40..6,z=-44..1 off x=26..39,y=40..50,z=-2..11 on x=-41..5,y=-41..6,z=-36..8 off x=-43..-33,y=-45..-28,z=7..25 on x=-33..15,y=-32..19,z=-34..11 off x=35..47,y=-46..-34,z=-11..5 on x=-14..36,y=-6..44,z=-16..29 on x=-57795..-6158,y=29564..72030,z=20435..90618 on x=36731..105352,y=-21140..28532,z=16094..90401 on x=30999..107136,y=-53464..15513,z=8553..71215 on x=13528..83982,y=-99403..-27377,z=-24141..23996 on x=-72682..-12347,y=18159..111354,z=7391..80950 on x=-1060..80757,y=-65301..-20884,z=-103788..-16709 on x=-83015..-9461,y=-72160..-8347,z=-81239..-26856 on x=-52752..22273,y=-49450..9096,z=54442..119054 on x=-29982..40483,y=-108474..-28371,z=-24328..38471 on x=-4958..62750,y=40422..118853,z=-7672..65583 on x=55694..108686,y=-43367..46958,z=-26781..48729 on x=-98497..-18186,y=-63569..3412,z=1232..88485 on x=-726..56291,y=-62629..13224,z=18033..85226 on x=-110886..-34664,y=-81338..-8658,z=8914..63723 on x=-55829..24974,y=-16897..54165,z=-121762..-28058 on x=-65152..-11147,y=22489..91432,z=-58782..1780 on x=-120100..-32970,y=-46592..27473,z=-11695..61039 on x=-18631..37533,y=-124565..-50804,z=-35667..28308 on x=-57817..18248,y=49321..117703,z=5745..55881 on x=14781..98692,y=-1341..70827,z=15753..70151 on x=-34419..55919,y=-19626..40991,z=39015..114138 on x=-60785..11593,y=-56135..2999,z=-95368..-26915 on x=-32178..58085,y=17647..101866,z=-91405..-8878 on x=-53655..12091,y=50097..105568,z=-75335..-4862 on x=-111166..-40997,y=-71714..2688,z=5609..50954 on x=-16602..70118,y=-98693..-44401,z=5197..76897 on x=16383..101554,y=4615..83635,z=-44907..18747 off x=-95822..-15171,y=-19987..48940,z=10804..104439 on x=-89813..-14614,y=16069..88491,z=-3297..45228 on x=41075..99376,y=-20427..49978,z=-52012..13762 on x=-21330..50085,y=-17944..62733,z=-112280..-30197 on x=-16478..35915,y=36008..118594,z=-7885..47086 off x=-98156..-27851,y=-49952..43171,z=-99005..-8456 off x=2032..69770,y=-71013..4824,z=7471..94418 on x=43670..120875,y=-42068..12382,z=-24787..38892 off x=37514..111226,y=-45862..25743,z=-16714..54663 off x=25699..97951,y=-30668..59918,z=-15349..69697 off x=-44271..17935,y=-9516..60759,z=49131..112598 on x=-61695..-5813,y=40978..94975,z=8655..80240 off x=-101086..-9439,y=-7088..67543,z=33935..83858 off x=18020..114017,y=-48931..32606,z=21474..89843 off x=-77139..10506,y=-89994..-18797,z=-80..59318 off x=8476..79288,y=-75520..11602,z=-96624..-24783 on x=-47488..-1262,y=24338..100707,z=16292..72967 off x=-84341..13987,y=2429..92914,z=-90671..-1318 off x=-37810..49457,y=-71013..-7894,z=-105357..-13188 off x=-27365..46395,y=31009..98017,z=15428..76570 off x=-70369..-16548,y=22648..78696,z=-1892..86821 on x=-53470..21291,y=-120233..-33476,z=-44150..38147 off x=-93533..-4276,y=-16170..68771,z=-104985..-24507 After running the above reboot steps, 2758514936282235 cubes are on. (Just for fun, 474140 of those are also in the initialization procedure region.) Starting again with all cubes off, execute all reboot steps. Afterward, considering all cubes, how many cubes are on? """ with open('day_22_input.txt') as fp: INPUTS = [line.strip() for line in fp] SMALL_SAMPLE = '''on x=10..12,y=10..12,z=10..12 on x=11..13,y=11..13,z=11..13 off x=9..11,y=9..11,z=9..11 on x=10..10,y=10..10,z=10..10'''.split('\n') SAMPLE = '''on x=-20..26,y=-36..17,z=-47..7 on x=-20..33,y=-21..23,z=-26..28 on x=-22..28,y=-29..23,z=-38..16 on x=-46..7,y=-6..46,z=-50..-1 on x=-49..1,y=-3..46,z=-24..28 on x=2..47,y=-22..22,z=-23..27 on x=-27..23,y=-28..26,z=-21..29 on x=-39..5,y=-6..47,z=-3..44 on x=-30..21,y=-8..43,z=-13..34 on x=-22..26,y=-27..20,z=-29..19 off x=-48..-32,y=26..41,z=-47..-37 on x=-12..35,y=6..50,z=-50..-2 off x=-48..-32,y=-32..-16,z=-15..-5 on x=-18..26,y=-33..15,z=-7..46 off x=-40..-22,y=-38..-28,z=23..41 on x=-16..35,y=-41..10,z=-47..6 off x=-32..-23,y=11..30,z=-14..3 on x=-49..-5,y=-3..45,z=-29..18 off x=18..30,y=-20..-8,z=-3..13 on x=-41..9,y=-7..43,z=-33..15 on x=-54112..-39298,y=-85059..-49293,z=-27449..7877 on x=967..23432,y=45373..81175,z=27513..53682'''.split('\n') SAMPLE2 = '''on x=-5..47,y=-31..22,z=-19..33 on x=-44..5,y=-27..21,z=-14..35 on x=-49..-1,y=-11..42,z=-10..38 on x=-20..34,y=-40..6,z=-44..1 off x=26..39,y=40..50,z=-2..11 on x=-41..5,y=-41..6,z=-36..8 off x=-43..-33,y=-45..-28,z=7..25 on x=-33..15,y=-32..19,z=-34..11 off x=35..47,y=-46..-34,z=-11..5 on x=-14..36,y=-6..44,z=-16..29 on x=-57795..-6158,y=29564..72030,z=20435..90618 on x=36731..105352,y=-21140..28532,z=16094..90401 on x=30999..107136,y=-53464..15513,z=8553..71215 on x=13528..83982,y=-99403..-27377,z=-24141..23996 on x=-72682..-12347,y=18159..111354,z=7391..80950 on x=-1060..80757,y=-65301..-20884,z=-103788..-16709 on x=-83015..-9461,y=-72160..-8347,z=-81239..-26856 on x=-52752..22273,y=-49450..9096,z=54442..119054 on x=-29982..40483,y=-108474..-28371,z=-24328..38471 on x=-4958..62750,y=40422..118853,z=-7672..65583 on x=55694..108686,y=-43367..46958,z=-26781..48729 on x=-98497..-18186,y=-63569..3412,z=1232..88485 on x=-726..56291,y=-62629..13224,z=18033..85226 on x=-110886..-34664,y=-81338..-8658,z=8914..63723 on x=-55829..24974,y=-16897..54165,z=-121762..-28058 on x=-65152..-11147,y=22489..91432,z=-58782..1780 on x=-120100..-32970,y=-46592..27473,z=-11695..61039 on x=-18631..37533,y=-124565..-50804,z=-35667..28308 on x=-57817..18248,y=49321..117703,z=5745..55881 on x=14781..98692,y=-1341..70827,z=15753..70151 on x=-34419..55919,y=-19626..40991,z=39015..114138 on x=-60785..11593,y=-56135..2999,z=-95368..-26915 on x=-32178..58085,y=17647..101866,z=-91405..-8878 on x=-53655..12091,y=50097..105568,z=-75335..-4862 on x=-111166..-40997,y=-71714..2688,z=5609..50954 on x=-16602..70118,y=-98693..-44401,z=5197..76897 on x=16383..101554,y=4615..83635,z=-44907..18747 off x=-95822..-15171,y=-19987..48940,z=10804..104439 on x=-89813..-14614,y=16069..88491,z=-3297..45228 on x=41075..99376,y=-20427..49978,z=-52012..13762 on x=-21330..50085,y=-17944..62733,z=-112280..-30197 on x=-16478..35915,y=36008..118594,z=-7885..47086 off x=-98156..-27851,y=-49952..43171,z=-99005..-8456 off x=2032..69770,y=-71013..4824,z=7471..94418 on x=43670..120875,y=-42068..12382,z=-24787..38892 off x=37514..111226,y=-45862..25743,z=-16714..54663 off x=25699..97951,y=-30668..59918,z=-15349..69697 off x=-44271..17935,y=-9516..60759,z=49131..112598 on x=-61695..-5813,y=40978..94975,z=8655..80240 off x=-101086..-9439,y=-7088..67543,z=33935..83858 off x=18020..114017,y=-48931..32606,z=21474..89843 off x=-77139..10506,y=-89994..-18797,z=-80..59318 off x=8476..79288,y=-75520..11602,z=-96624..-24783 on x=-47488..-1262,y=24338..100707,z=16292..72967 off x=-84341..13987,y=2429..92914,z=-90671..-1318 off x=-37810..49457,y=-71013..-7894,z=-105357..-13188 off x=-27365..46395,y=31009..98017,z=15428..76570 off x=-70369..-16548,y=22648..78696,z=-1892..86821 on x=-53470..21291,y=-120233..-33476,z=-44150..38147 off x=-93533..-4276,y=-16170..68771,z=-104985..-24507'''.split('\n') class Pt(NamedTuple): x: int y: int z: int def max(self): return max(abs(self.x), abs(self.y), abs(self.z)) class Box(NamedTuple): min_pt: Pt max_pt: Pt def size(self): return (self.max_pt.x - self.min_pt.x) * \ (self.max_pt.y - self.min_pt.y) * \ (self.max_pt.z - self.min_pt.z) def contains_pt(self, pt): return self.min_pt.x <= pt.x < self.max_pt.x and \ self.min_pt.y <= pt.y < self.max_pt.y and \ self.min_pt.z <= pt.z < self.max_pt.z def overlap(self, other): if self.min_pt.x >= other.max_pt.x: return False if other.min_pt.x >= self.max_pt.x: return False if self.min_pt.y >= other.max_pt.y: return False if other.min_pt.y >= self.max_pt.y: return False if self.min_pt.z >= other.max_pt.z: return False if other.min_pt.z >= self.max_pt.z: return False return True def union(self, other): x_axis = list({self.min_pt.x, self.max_pt.x, other.min_pt.x, other.max_pt.x}) x_axis.sort() y_axis = list({self.min_pt.y, self.max_pt.y, other.min_pt.y, other.max_pt.y}) y_axis.sort() z_axis = list({self.min_pt.z, self.max_pt.z, other.min_pt.z, other.max_pt.z}) z_axis.sort() extra_bits = [] x_last, y_last, z_last = None, None, None for zi, z in enumerate(z_axis): if zi == 0: z_last = z continue for yi, y in enumerate(y_axis): if yi == 0: y_last = y continue for xi, x in enumerate(x_axis): if xi == 0: x_last = x continue min_pt = Pt(x_last, y_last, z_last) max_pt = Pt(x, y, z) if other.contains_pt(min_pt) and not self.contains_pt(min_pt): extra_bits.append(Box(min_pt, max_pt)) x_last = x y_last = y z_last = z return extra_bits def test_box_size(): assert Box(Pt(0, 3, 5), Pt(2, 4, 8)).size() == 6 def test_box_contains_pt(): assert Box(Pt(-2, -2, -2), Pt(3, 3, 3)).contains_pt(Pt(0, 0, 0)) is True assert Box(Pt(0, 3, 7), Pt(2, 4, 8)).contains_pt(Pt(1, 3, 7)) is True assert Box(Pt(0, 3, 7), Pt(2, 4, 8)).contains_pt(Pt(2, 3, 7)) is False assert Box(Pt(0, 3, 7), Pt(2, 4, 8)).contains_pt(Pt(-1, 3, 7)) is False def test_box_overlap(): assert Box(Pt(-2, -2, -2), Pt(3, 3, 3)).overlap( Box(Pt(-1, -1, -1), Pt(2, 2, 2))) is True assert Box(Pt(0, 3, 7), Pt(2, 4, 8)).overlap( Box(Pt(1, 3, 7), Pt(4, 4, 8))) is True assert Box(Pt(0, 3, 7), Pt(2, 4, 8)).overlap( Box(Pt(1, 3, 3), Pt(4, 4, 4))) is False assert Box(Pt(0, 3, 7), Pt(2, 4, 8)).overlap( Box(Pt(2, 3, 3), Pt(4, 4, 4))) is False assert Box(Pt(0, 3, 7), Pt(2, 4, 8)).overlap( Box(Pt(-1, -3, -7), Pt(0, 0, 0))) is False def test_box_union(): assert Box(Pt(0, 3, 7), Pt(2, 4, 8)).union( Box(Pt(1, 3, 7), Pt(4, 4, 8))) == [Box(Pt(2, 3, 7), Pt(4, 4, 8))] assert Box(Pt(0, 3, 7), Pt(2, 4, 8)).union( Box(Pt(1, 3, 3), Pt(4, 4, 4))) == [Box(Pt(1, 3, 3), Pt(2, 4, 4)), Box(Pt(2, 3, 3), Pt(4, 4, 4))] assert Box(Pt(-2, -2, -2), Pt(3, 3, 3)).union( Box(Pt(-1, -1, -1), Pt(2, 2, 2))) == [] assert Box(Pt(-1, -1, -1), Pt(2, 2, 2)).union( Box(Pt(-2, -2, -2), Pt(3, 3, 3))) == [Box(Pt(-2, -2, -2), Pt(-1, -1, -1)), Box(Pt(-1, -2, -2), Pt(2, -1, -1)), Box(Pt(2, -2, -2), Pt(3, -1, -1)), Box(Pt(-2, -1, -2), Pt(-1, 2, -1)), Box(Pt(-1, -1, -2), Pt(2, 2, -1)), Box(Pt(2, -1, -2), Pt(3, 2, -1)), Box(Pt(-2, 2, -2), Pt(-1, 3, -1)), Box(Pt(-1, 2, -2), Pt(2, 3, -1)), Box(Pt(2, 2, -2), Pt(3, 3, -1)), Box(Pt(-2, -2, -1), Pt(-1, -1, 2)), Box(Pt(-1, -2, -1), Pt(2, -1, 2)), Box(Pt(2, -2, -1), Pt(3, -1, 2)), Box(Pt(-2, -1, -1), Pt(-1, 2, 2)), Box(Pt(2, -1, -1), Pt(3, 2, 2)), Box(Pt(-2, 2, -1), Pt(-1, 3, 2)), Box(Pt(-1, 2, -1), Pt(2, 3, 2)), Box(Pt(2, 2, -1), Pt(3, 3, 2)), Box(Pt(-2, -2, 2), Pt(-1, -1, 3)), Box(Pt(-1, -2, 2), Pt(2, -1, 3)), Box(Pt(2, -2, 2), Pt(3, -1, 3)), Box(Pt(-2, -1, 2), Pt(-1, 2, 3)), Box(Pt(-1, -1, 2), Pt(2, 2, 3)), Box(Pt(2, -1, 2), Pt(3, 2, 3)), Box(Pt(-2, 2, 2), Pt(-1, 3, 3)), Box(Pt(-1, 2, 2), Pt(2, 3, 3)), Box(Pt(2, 2, 2), Pt(3, 3, 3))] class Board: def __init__(self, initial_lines, max_range=None): self.instructions = [] self.grid = dict() if max_range is not None: bounding_box = Box(Pt(-max_range, -max_range, -max_range), Pt(max_range + 1, max_range + 1, max_range + 1)) else: bounding_box = None for line in initial_lines: state, region = line.split(' ') raw_x, raw_y, raw_z = region.split(',') x_range = [int(n) for n in raw_x[2:].split('..')] y_range = [int(n) for n in raw_y[2:].split('..')] z_range = [int(n) for n in raw_z[2:].split('..')] self.instructions.append( (state, Box(Pt(x_range[0], y_range[0], z_range[0]), Pt(x_range[1] + 1, y_range[1] + 1, z_range[1] + 1)) )) for (state, next_box) in self.instructions: if bounding_box is not None and not bounding_box.overlap(next_box): continue if state == 'on': boxes_to_add = [next_box] while len(boxes_to_add) > 0: inserting_box = boxes_to_add.pop() bits = None for pt, box in self.grid.items(): if inserting_box.overlap(box): bits = box.union(inserting_box) boxes_to_add.extend(bits) break if bits is None: self.grid[inserting_box.min_pt] = inserting_box elif state == 'off': box_to_remove = next_box next_pass = list(self.grid.items()) for pt, box in next_pass: if box_to_remove.overlap(box): new_bits = box_to_remove.union(box) del(self.grid[pt]) for nb in new_bits: self.grid[nb.min_pt] = nb def total(self): total = 0 for box in self.grid.values(): total += box.size() return total def test_board(): small_board = Board(SMALL_SAMPLE, 50) assert small_board.total() == 39 sample_board = Board(SAMPLE, 50) assert sample_board.total() == 590784 sample2_board = Board(SAMPLE2) assert sample2_board.total() == 2758514936282235 def test_game_board(): game_board = Board(INPUTS, 50) assert game_board.total() == 611378 def test_second_part_with_game_board(): game_board = Board(INPUTS) assert game_board.total() == 1214313344725528
59e3b18b030420f4459be6dea16c073f06107e35
jvano74/advent_of_code
/2022/day_25_test.py
9,351
4
4
class Puzzle: """ --- Day 25: Full of Hot Air --- As the expedition finally reaches the extraction point, several large hot air balloons drift down to meet you. Crews quickly start unloading the equipment the balloons brought: many hot air balloon kits, some fuel tanks, and a fuel heating machine. The fuel heating machine is a new addition to the process. When this mountain was a volcano, the ambient temperature was more reasonable; now, it's so cold that the fuel won't work at all without being warmed up first. The Elves, seemingly in an attempt to make the new machine feel welcome, have already attached a pair of googly eyes and started calling it "Bob". To heat the fuel, Bob needs to know the total amount of fuel that will be processed ahead of time so it can correctly calibrate heat output and flow rate. This amount is simply the sum of the fuel requirements of all of the hot air balloons, and those fuel requirements are even listed clearly on the side of each hot air balloon's burner. You assume the Elves will have no trouble adding up some numbers and are about to go back to figuring out which balloon is yours when you get a tap on the shoulder. Apparently, the fuel requirements use numbers written in a format the Elves don't recognize; predictably, they'd like your help deciphering them. You make a list of all of the fuel requirements (your puzzle input), but you don't recognize the number format either. For example: 1=-0-2 12111 2=0= 21 2=01 111 20012 112 1=-1= 1-12 12 1= 122 Fortunately, Bob is labeled with a support phone number. Not to be deterred, you call and ask for help. "That's right, just supply the fuel amount to the-- oh, for more than one burner? No problem, you just need to add together our Special Numeral-Analogue Fuel Units. Patent pending! They're way better than normal numbers for--" You mention that it's quite cold up here and ask if they can skip ahead. "Okay, our Special Numeral-Analogue Fuel Units - SNAFU for short - are sort of like normal numbers. You know how starting on the right, normal numbers have a ones place, a tens place, a hundreds place, and so on, where the digit in each place tells you how many of that value you have?" "SNAFU works the same way, except it uses powers of five instead of ten. Starting from the right, you have a ones place, a fives place, a twenty-fives place, a one-hundred-and-twenty-fives place, and so on. It's that easy!" You ask why some of the digits look like - or = instead of "digits". "You know, I never did ask the engineers why they did that. Instead of using digits four through zero, the digits are 2, 1, 0, minus (written -), and double-minus (written =). Minus is worth -1, and double-minus is worth -2." "So, because ten (in normal numbers) is two fives and no ones, in SNAFU it is written 20. Since eight (in normal numbers) is two fives minus two ones, it is written 2=." "You can do it the other direction, too. Say you have the SNAFU number 2=-01. That's 2 in the 625s place, = (double-minus) in the 125s place, - (minus) in the 25s place, 0 in the 5s place, and 1 in the 1s place. (2 times 625) plus (-2 times 125) plus (-1 times 25) plus (0 times 5) plus (1 times 1). That's 1250 plus -250 plus -25 plus 0 plus 1. 976!" "I see here that you're connected via our premium uplink service, so I'll transmit our handy SNAFU brochure to you now. Did you need anything else?" You ask if the fuel will even work in these temperatures. "Wait, it's how cold? There's no way the fuel - or any fuel - would work in those conditions! There are only a few places in the-- where did you say you are again?" Just then, you notice one of the Elves pour a few drops from a snowflake-shaped container into one of the fuel tanks, thank the support representative for their time, and disconnect the call. The SNAFU brochure contains a few more examples of decimal ("normal") numbers and their SNAFU counterparts: Decimal SNAFU 1 1 2 2 3 1= 4 1- 5 10 6 11 7 12 8 2= 9 2- 10 20 15 1=0 20 1-0 2022 1=11-2 12345 1-0---0 314159265 1121-1110-1=0 Based on this process, the SNAFU numbers in the example above can be converted to decimal numbers as follows: SNAFU Decimal 1=-0-2 1747 12111 906 2=0= 198 21 11 2=01 201 111 31 20012 1257 112 32 1=-1= 353 1-12 107 12 7 1= 3 122 37 In decimal, the sum of these numbers is 4890. As you go to input this number on Bob's console, you discover that some buttons you expected are missing. Instead, you are met with buttons labeled =, -, 0, 1, and 2. Bob needs the input value expressed as a SNAFU number, not in decimal. Reversing the process, you can determine that for the decimal number 4890, the SNAFU number you need to supply to Bob's console is 2=-1=0. The Elves are starting to get cold. What SNAFU number do you supply to Bob's console? Your puzzle answer was 2-==10--=-0101==1201. The first half of this puzzle is complete! It provides one gold star: * --- Part Two --- The hot air balloons quickly carry you to the North Pole. As soon as you land, most of the expedition is escorted directly to a small building attached to the reindeer stables. The head smoothie chef has just finished warming up the industrial-grade smoothie blender as you arrive. It will take 50 stars to fill the blender. The expedition Elves turn their attention to you, and you begin emptying the fruit from your pack onto the table. As you do, a very young Elf - one you recognize from the expedition team - approaches the table and holds up a single star fruit he found. The head smoothie chef places it in the blender. Only 49 stars to go. You have enough stars to Start The Blender. You make a smoothie with all fifty stars and deliver it to the reindeer! The sleigh is already warmed up by the time they finish eating. Congratulations! You've finished every puzzle in Advent of Code 2022! I hope you had as much fun solving them as I had making them for you. I'd love to hear about your adventure; you can get in touch with me via contact info on my website or through Twitter. If you'd like to see more things like this in the future, please consider supporting Advent of Code and sharing it with others. To hear about future projects, you can follow me on Twitter. I've highlighted the easter eggs in each puzzle, just in case you missed any. Hover your mouse over them, and the easter egg will appear. You can [Share] this moment with your friends, or [Go Check on Your Calendar]. """ TEST_MATRIX = { "1=-0-2": 1747, "12111": 906, "2=0=": 198, "21": 11, "2=01": 201, "111": 31, "20012": 1257, "112": 32, "1=-1=": 353, "1-12": 107, "12": 7, "1=": 3, "122": 37, } SAMPLE = TEST_MATRIX.keys() with open("day_25_input.txt") as fp: MY_INPUT = [line.strip() for line in fp] def snafu_to_decimal(raw: str) -> int: total = 0 pow = 1 for digit in reversed(raw): match digit: case "=": total += -2 * pow case "-": total += -1 * pow case "0": total += 0 * pow case "1": total += 1 * pow case "2": total += 2 * pow case _: raise Exception("Invalid digit") pow *= 5 return total def decimal_to_snafu(decimal: int) -> str: if decimal < 0: raise NotImplementedError remainders = [] while decimal > 0: remainder = decimal % 5 match remainder: case 4: remainders.append("-") decimal = (decimal // 5) + 1 pass case 3: remainders.append("=") decimal = (decimal // 5) + 1 pass case _: remainders.append(f"{remainder}") decimal = decimal // 5 return "".join(reversed(remainders)) def test_snafu_to_decimal(): for snafu, decimal in TEST_MATRIX.items(): assert snafu_to_decimal(snafu) == decimal def test_decimal_to_snafu(): for snafu, decimal in TEST_MATRIX.items(): assert decimal_to_snafu(decimal) == snafu def test_sample(): snafu_sum = sum(snafu_to_decimal(d) for d in SAMPLE) assert decimal_to_snafu(snafu_sum) == "2=-1=0" def test_my_input(): snafu_sum = sum(snafu_to_decimal(d) for d in MY_INPUT) assert decimal_to_snafu(snafu_sum) == "2-==10--=-0101==1201"
cdb0945d8a75534c693b3f7f98a33625ecb37013
jvano74/advent_of_code
/2021/day_14_test.py
6,582
3.6875
4
from collections import Counter class Puzzle: """ --- Day 14: Extended Polymerization --- The incredible pressures at this depth are starting to put a strain on your submarine. The submarine has polymerization equipment that would produce suitable materials to reinforce the submarine, and the nearby volcanically-active caves should even have the necessary input elements in sufficient quantities. The submarine manual contains instructions for finding the optimal polymer formula; specifically, it offers a polymer template and a list of pair insertion rules (your puzzle input). You just need to work out what polymer would result after repeating the pair insertion process a few times. For example: NNCB CH -> B HH -> N CB -> H NH -> C HB -> C HC -> B HN -> C NN -> C BH -> H NC -> B NB -> B BN -> B BB -> N BC -> B CC -> N CN -> C The first line is the polymer template - this is the starting point of the process. The following section defines the pair insertion rules. A rule like AB -> C means that when elements A and B are immediately adjacent, element C should be inserted between them. These insertions all happen simultaneously. So, starting with the polymer template NNCB, the first step simultaneously considers all three pairs: - The first pair (NN) matches the rule NN -> C, so element C is inserted between the first N and the second N. - The second pair (NC) matches the rule NC -> B, so element B is inserted between the N and the C. - The third pair (CB) matches the rule CB -> H, so element H is inserted between the C and the B. Note that these pairs overlap: the second element of one pair is the first element of the next pair. Also, because all pairs are considered simultaneously, inserted elements are not considered to be part of a pair until the next step. After the first step of this process, the polymer becomes NCNBCHB. Here are the results of a few steps using the above rules: Template: NNCB After step 1: NCNBCHB After step 2: NBCCNBBBCBHCB After step 3: NBBBCNCCNBBNBNBBCHBHHBCHB After step 4: NBBNBNBBCCNBCNCCNBBNBBNBBBNBBNBBCBHCBHHNHCBBCBHCB This polymer grows quickly. After step 5, it has length 97; After step 10, it has length 3073. After step 10, B occurs 1749 times, C occurs 298 times, H occurs 191 times, and N occurs 865 times; taking the quantity of the most common element (B, 1749) and subtracting the quantity of the least common element (H, 161) produces 1749 - 161 = 1588. Apply 10 steps of pair insertion to the polymer template and find the most and least common elements in the result. What do you get if you take the quantity of the most common element and subtract the quantity of the least common element? To begin, get your puzzle input. --- Part Two --- The resulting polymer isn't nearly strong enough to reinforce the submarine. You'll need to run more steps of the pair insertion process; a total of 40 steps should do it. In the above example, the most common element is B (occurring 2192039569602 times) and the least common element is H (occurring 3849876073 times); subtracting these produces 2188189693529. Apply 40 steps of pair insertion to the polymer template and find the most and least common elements in the result. What do you get if you take the quantity of the most common element and subtract the quantity of the least common element? """ RAW_SAMPLE = """NNCB CH -> B HH -> N CB -> H NH -> C HB -> C HC -> B HN -> C NN -> C BH -> H NC -> B NB -> B BN -> B BB -> N BC -> B CC -> N CN -> C""" with open('day_14_input.txt') as fp: RAW_INPUT = fp.read() class Polymerization: def __init__(self, replacements): self.insertions = dict() for r in replacements: base, insert = r.split(' -> ') self.insertions[base] = insert def run(self, initial_compound, steps): result = initial_compound for _ in range(steps): result = self.step(result) return result def step(self, initial_compound): result = [] for pos, left in enumerate(initial_compound): if pos + 1 == len(initial_compound): result.append(left) return ''.join(result) result.append(left) right = initial_compound[pos + 1] if f'{left}{right}' in self.insertions: result.append(self.insertions[f'{left}{right}']) def fast_steps(self, initial_compound, steps): fast_map = Counter() for pos, left in enumerate(initial_compound): if pos + 1 == len(initial_compound): fast_map[f'{left}*'] += 1 else: right = initial_compound[pos + 1] fast_map[f'{left}{right}'] += 1 for _ in range(steps): next_step = Counter() for n in fast_map: if n not in self.insertions: next_step[n] += fast_map[n] else: new = self.insertions[n] left, right = n next_step[f'{left}{new}'] += fast_map[n] next_step[f'{new}{right}'] += fast_map[n] fast_map = next_step data = Counter() for n in fast_map: left, _ = n data[left] += fast_map[n] frequency = data.most_common() return frequency[0][1] - frequency[-1][1] @staticmethod def analyze(compound): data = Counter(compound) frequency = data.most_common() return frequency[0][1] - frequency[-1][1] def test_polymerization(): base, raw_replacements = RAW_SAMPLE.split('\n\n') replacements = [rl.strip() for rl in raw_replacements.split('\n')] sample_polymerization = Polymerization(replacements) assert sample_polymerization.step('NNCB') == 'NCNBCHB' assert sample_polymerization.run('NNCB', 2) == 'NBCCNBBBCBHCB' assert sample_polymerization.run('NNCB', 3) == 'NBBBCNCCNBBNBNBBCHBHHBCHB' assert sample_polymerization.run('NNCB', 4) == 'NBBNBNBBCCNBCNCCNBBNBBNBBBNBBNBBCBHCBHHNHCBBCBHCB' assert Polymerization.analyze(sample_polymerization.run(base, 10)) == 1588 assert sample_polymerization.fast_steps(base, 40) == 2188189693529 def test_real_polymerization(): base, raw_replacements = RAW_INPUT.split('\n\n') replacements = [rl.strip() for rl in raw_replacements.split('\n')] sample_polymerization = Polymerization(replacements) assert Polymerization.analyze(sample_polymerization.run(base, 10)) == 3259 assert sample_polymerization.fast_steps(base, 40) == 3259
761eaf9b854f25f069f8d0914e05f8b4f8061a3e
jvano74/advent_of_code
/2017/day_01_test.py
4,078
3.625
4
class Problem: """ --- Day 1: Inverse Captcha --- The night before Christmas, one of Santa's Elves calls you in a panic. "The printer's broken! We can't print the Naughty or Nice List!" By the time you make it to sub-basement 17, there are only a few minutes until midnight. "We have a big problem," she says; "there must be almost fifty bugs in this system, but nothing else can print The List. Stand in this square, quick! There's no time to explain; if you can convince them to pay you in stars, you'll be able to--" She pulls a lever and the world goes blurry. When your eyes can focus again, everything seems a lot more pixelated than before. She must have sent you inside the computer! You check the system clock: 25 milliseconds until midnight. With that much time, you should be able to collect all fifty stars by December 25th. Collect stars by solving puzzles. Two puzzles will be made available on each day millisecond in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! You're standing in a room with "digitization quarantine" written in LEDs along one wall. The only door is locked, but it includes a small interface. "Restricted Area - Strictly No Digitized Users Allowed." It goes on to explain that you may only leave by solving a captcha to prove you're not a human. Apparently, you only get one millisecond to solve the captcha: too fast for a normal human, but it feels like hours to you. The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list. For example: 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit. 1111 produces 4 because each digit (all 1) matches the next. 1234 produces 0 because no digit matches the next. 91212129 produces 9 because the only digit that matches the next one is the last digit, 9. What is the solution to your captcha? --- Part Two --- You notice a progress bar that jumps to 50% completion. Apparently, the door isn't yet satisfied, but it did emit a star as encouragement. The instructions change: Now, instead of considering the next digit, it wants you to consider the digit halfway around the circular list. That is, if your list contains 10 items, only include a digit in your sum if the digit 10/2 = 5 steps forward matches it. Fortunately, your list has an even number of elements. For example: 1212 produces 6: the list contains 4 items, and all four digits match the digit 2 items ahead. 1221 produces 0, because every comparison is between a 1 and a 2. 123425 produces 4, because both 2s match each other, but no other digit has a match. 123123 produces 12. 12131415 produces 4. What is the solution to your new captcha? """ pass with open('day_01_input.txt') as f: for line in f: INPUTS = line.strip() def next_sum(digit_list): previous = digit_list[-1] sum = 0 for d in digit_list: if d == previous: sum += int(d) previous = d return sum def half_sum(digit_list): modulus = len(digit_list) delta = modulus//2 sum = 0 for pos in range(modulus): if digit_list[pos] == digit_list[(pos + delta) % modulus]: sum += int(digit_list[pos]) return sum def test_next_sum(): assert next_sum('1122') == 3 assert next_sum('1111') == 4 assert next_sum('1234') == 0 assert next_sum('91212129') == 9 assert next_sum(INPUTS) == 1228 def test_half_sum(): assert half_sum('1212') == 6 assert half_sum('1221') == 0 assert half_sum('123425') == 4 assert half_sum('123123') == 12 assert half_sum('12131415') == 4 assert half_sum(INPUTS) == 1238
31ed8b9e8c193dede6b06754ef6b90a4ae1ae1c6
jvano74/advent_of_code
/2016/day_23_test.py
7,593
4.03125
4
from collections import defaultdict import re class Puzzle: """ --- Day 23: Safe Cracking --- This is one of the top floors of the nicest tower in EBHQ. The Easter Bunny's private office is here, complete with a safe hidden behind a painting, and who wouldn't hide a star in a safe behind a painting? The safe has a digital screen and keypad for code entry. A sticky note attached to the safe has a password hint on it: "eggs". The painting is of a large rabbit coloring some eggs. You see 7. When you go to type the code, though, nothing appears on the display; instead, the keypad comes apart in your hands, apparently having been smashed. Behind it is some kind of socket - one that matches a connector in your prototype computer! You pull apart the smashed keypad and extract the logic circuit, plug it into your computer, and plug your computer into the safe. Now, you just need to figure out what output the keypad would have sent to the safe. You extract the assembunny code from the logic chip (your puzzle input). The code looks like it uses almost the same architecture and instruction set that the monorail computer used! You should be able to use the same assembunny interpreter for this as you did there, but with one new instruction: tgl x toggles the instruction x away (pointing at instructions like jnz does: positive means forward; negative means backward): - For one-argument instructions, inc becomes dec, and all other one-argument instructions become inc. - For two-argument instructions, jnz becomes cpy, and all other two-instructions become jnz. - The arguments of a toggled instruction are not affected. - If an attempt is made to toggle an instruction outside the program, nothing happens. - If toggling produces an invalid instruction (like cpy 1 2) and an attempt is later made to execute that instruction, skip it instead. - If tgl toggles itself (for example, if a is 0, tgl a would target itself and become inc a), the resulting instruction is not executed until the next time it is reached. For example, given this program: cpy 2 a tgl a tgl a tgl a cpy 1 a dec a dec a cpy 2 a initializes register a to 2. The first tgl a toggles an instruction a (2) away from it, which changes the third tgl a into inc a. The second tgl a also modifies an instruction 2 away from it, which changes the cpy 1 a into jnz 1 a. The fourth line, which is now inc a, increments a to 3. Finally, the fifth line, which is now jnz 1 a, jumps a (3) instructions ahead, skipping the dec a instructions. In this example, the final value in register a is 3. The rest of the electronics seem to place the keypad entry (the number of eggs, 7) in register a, run the code, and then send the value left in register a to the safe. What value should be sent to the safe? --- Part Two --- The safe doesn't open, but it does make several angry noises to express its frustration. You're quite sure your logic is working correctly, so the only other thing is... you check the painting again. As it turns out, colored eggs are still eggs. Now you count 12. As you run the program with this new input, the prototype computer begins to overheat. You wonder what's taking so long, and whether the lack of any instruction more powerful than "add one" has anything to do with it. Don't bunnies usually multiply? Anyway, what value should actually be sent to the safe? """ pass INPUT = ['cpy a b', 'dec b', 'cpy a d', 'cpy 0 a', 'cpy b c', 'inc a', 'dec c', 'jnz c -2', 'dec d', 'jnz d -5', 'dec b', 'cpy b c', 'cpy c d', 'dec d', 'inc c', 'jnz d -2', 'tgl c', 'cpy -16 c', 'jnz 1 c', 'cpy 73 c', 'jnz 82 d', 'inc a', 'inc d', 'jnz d -2', 'inc c', 'jnz c -5'] class Processor: def __init__(self, program): self.program = program self.execution = 0 self.registers = defaultdict(int) def step(self): if 0 <= self.execution < len(self.program): cmd, argv = self.program[self.execution].split(' ', 1) argv = argv.split(' ') values = [int(v) if re.match(r'^-?\d+$', v) else self.registers[v] for v in argv] if cmd == 'jnz': if values[0] != 0: self.execution += values[1] else: self.execution += 1 return 0 if cmd == 'tgl': tgl_loc = self.execution + values[0] if 0 <= tgl_loc < len(self.program): tgl_cmd, tgl_argv = self.program[tgl_loc].split(' ', 1) if len(tgl_argv) == 1: if tgl_cmd == 'inc': tgl_cmd = 'dec' else: tgl_cmd = 'inc' else: if tgl_cmd == 'jnz': tgl_cmd = 'cpy' else: tgl_cmd = 'jnz' self.program[tgl_loc] = f'{tgl_cmd} {tgl_argv}' self.execution += 1 return 0 self.execution += 1 if cmd == 'cpy': if type(argv[1]) != int: self.registers[argv[1]] = values[0] elif cmd == 'inc': self.registers[argv[0]] += 1 elif cmd == 'dec': self.registers[argv[0]] -= 1 return 0 return 1 def run(self): while self.step() == 0: pass return self.registers['a'] def test_processor(): sample_processor = Processor(['cpy 41 a', 'inc a', 'inc a', 'dec a', 'jnz a 2', 'dec a']) assert sample_processor.run() == 42 sample_processor = Processor(['cpy 2 a', 'tgl a', 'tgl a', 'tgl a', 'cpy 1 a', 'dec a', 'dec a']) assert sample_processor.run() == 3 def test_puzzle_processor(): puzzle_processor = Processor(INPUT) puzzle_processor.registers['a'] = 7 result = puzzle_processor.run() assert result == 11026 def xtest_puzzle_processor2(): # run time too long, manually reviewed code to determine calculation puzzle_processor = Processor(INPUT) puzzle_processor.registers['a'] = 12 result = puzzle_processor.run() assert result == 11026 """ Based on text hint just looking at code... 0 'cpy a b', 1 'dec b', 2 'cpy a d', a goes to d <======= when c is -16 3 'cpy 0 a', clears a 4 'cpy b c', <==== puts b in c 5 'inc a', <== 6 'dec c', 7 'jnz c -2', <== adds c to a 8 'dec d', 9 'jnz d -5', <==== repeats d times net effect of above is a gets b * d with c and d = 0 at end a * (a - 1) -> a = 12*11 = 132 10 'dec b', a-2 11 'cpy b c', 12 'cpy c d', 13 'dec d', <====== 14 'inc c', 15 'jnz d -2', <====== c + d = (a-2) + (a-2) -> c = 2(a-2) = 20 (vs 10) 16 'tgl c', 17 'cpy -16 c', 18 'jnz 1 c', << now cpy 1 to c <========== to c 19 'cpy 73 c', 20 'jnz 82 d', << now cpy 82 d <==X 21 'inc a', <=A 22 'inc d', << now dec d 23 'jnz d -2', <=A add d to a c times (e.g. add 73 * 82 to a) 24 'inc c', << now dec c 25 'jnz c -5' <==X Looks like this takes a * (a-1) * (a-2) * ... * 2 * 1 (e.g. factorial) and adds 73* 82 """ def test_by_hand1(): ans = 1 for a in range(1, 8): ans *= a ans += 73 * 82 assert ans == 11026 def test_by_hand2(): ans = 1 for a in range(1, 13): ans *= a ans += 73 * 82 assert ans == 479007586
826c7072cc6bada4b595106229046b138cf40f12
jvano74/advent_of_code
/2015/day_07_test.py
8,515
3.703125
4
import numpy as np import re from collections import defaultdict import pytest class Puzzle: """ --- Day 7: Some Assembly Required --- This year, Santa brought little Bobby Tables a set of wires and bitwise logic gates! Unfortunately, little Bobby is a little under the recommended age range, and he needs help assembling the circuit. Each wire has an identifier (some lowercase letters) and can carry a 16-bit signal (a number from 0 to 65535). A signal is provided to each wire by a gate, another wire, or some specific value. Each wire can only get a signal from one source, but can provide its signal to multiple destinations. A gate provides no signal until all of its inputs have a signal. The included instructions booklet describes how to connect the parts together: x AND y -> z means to connect wires x and y to an AND gate, and then connect its output to wire z. For example: 123 -> x means that the signal 123 is provided to wire x. x AND y -> z means that the bitwise AND of wire x and wire y is provided to wire z. p LSHIFT 2 -> q means that the value from wire p is left-shifted by 2 and then provided to wire q. NOT e -> f means that the bitwise complement of the value from wire e is provided to wire f. Other possible gates include OR (bitwise OR) and RSHIFT (right-shift). If, for some reason, you'd like to emulate the circuit instead, almost all programming languages (for example, C, JavaScript, or Python) provide operators for these gates. For example, here is a simple circuit: 123 -> x 456 -> y x AND y -> d x OR y -> e x LSHIFT 2 -> f y RSHIFT 2 -> g NOT x -> h NOT y -> i After it is run, these are the signals on the wires: d: 72 e: 507 f: 492 g: 114 h: 65412 i: 65079 x: 123 y: 456 In little Bobby's kit's instructions booklet (provided as your puzzle input), what signal is ultimately provided to wire a? """ pass class Signal: def __init__(self, data): self.data = data def output(self): return np.ushort(self.data) class Wire: def __init__(self, line_in=None): self.line_in = line_in if line_in is None: self.data = None else: self.data = line_in.output() def output(self): if self.data is not None: return self.data if self.line_in is None: return None self.data = self.line_in.output() if self.data is None: return None return np.ushort(self.data) class Gate: def __init__(self, operation=None, line1_in=None, line2_in=None): self.operation = operation self.line1_in = line1_in self.line2_in = line2_in self.data = None def output(self): if self.data is not None: return self.data if self.line1_in is None: return None line1 = self.line1_in.output() if line1 is None: return None if self.operation == "NOT": self.data = np.ushort(~line1) return self.data if self.line2_in is None: return None if self.operation == "RSHIFT": self.data = np.ushort(line1 >> self.line2_in) return self.data if self.operation == "LSHIFT": self.data = np.ushort(line1 << self.line2_in) return self.data line2 = self.line2_in.output() if line2 is None: return None if self.operation == "AND": self.data = np.ushort(line1 & line2) return self.data if self.operation == "OR": self.data = np.ushort(line1 | line2) return self.data return None class Kit: wires = defaultdict(Wire) def wire_in(self, instruction): parse = re.match(r"(?P<inputs>.*) -> (?P<out_wire>[a-z]+)", instruction) if not parse: raise NotImplementedError(f"Instruction {instruction} not implemented") out_wire_label = parse.group("out_wire") out_wire = self.wires[out_wire_label] if out_wire.line_in is not None: raise KeyError(f"Wire {out_wire} already connected in kit") parse = re.match(r"((?P<in_wire>[a-z]+)|(?P<in_signal>\d+)) ->", instruction) if parse and parse.group("in_signal"): value = int(parse.group("in_signal")) self.add_signal_to_wire(out_wire, value) return if parse and parse.group("in_wire"): out_wire.line_in = self.wires[parse.group("in_wire")] return parse = re.match(r"NOT (?P<in_wire>[a-z]+) ->", instruction) if parse: self.add_not_gate(out_wire, self.wires[parse.group("in_wire")]) return parse = re.match( r"(?P<in_wire>[a-z]+) (?P<direction>[RL])SHIFT (?P<bits>\d+) ->", instruction, ) if parse: self.add_shift_gate( out_wire, self.wires[parse.group("in_wire")], parse.group("direction"), int(parse.group("bits")), ) return parse = re.match( r"((?P<in1_wire>[a-z]+)|(?P<in1_signal>\d+)) (?P<gate>AND|OR) " r"((?P<in2_wire>[a-z]+)|(?P<in2_signal>\d+)) ->", instruction, ) if parse: self.add_gate( out_wire, parse.group("gate"), self.wires[parse.group("in1_wire")] if parse.group("in1_wire") else Signal(int(parse.group("in1_signal"))), self.wires[parse.group("in2_wire")] if parse.group("in2_wire") else Signal(int(parse.group("in2_signal"))), ) return raise NotImplementedError(f"Instruction {instruction} not implemented") @staticmethod def add_signal_to_wire(out_wire, data): out_wire.line_in = Signal(data) @staticmethod def add_not_gate(out_wire, in_wire): out_wire.line_in = Wire(Gate("NOT", in_wire)) @staticmethod def add_shift_gate(out_wire, in_wire, direction, bits): out_wire.line_in = Wire(Gate(f"{direction}SHIFT", in_wire, bits)) @staticmethod def add_gate(out_wire, gate, in1_wire, in2_wire): out_wire.line_in = Wire(Gate(gate, in1_wire, in2_wire)) def execute_directions(self): with open("./input_day_7.txt", "r") as fp: line = fp.readline() while line: self.wire_in(line) line = fp.readline() def test_signal(): s1 = Signal(123) s2 = Signal(333) assert s1.output() == 123 assert s2.output() == 333 def test_wire(): s1 = Signal(342) w1 = Wire() assert w1.output() is None w1.line_in = s1 assert w1.output() == 342 w2 = Wire(s1) assert w2.output() == 342 def test_gates(): s1 = Signal(12) g1 = Gate("NOT", s1) assert g1.output() == 65523 g2 = Gate("LSHIFT", s1, 3) assert g2.output() == 96 g3 = Gate("RSHIFT", g2, 3) assert g3.output() == 12 def test_kit(): kit_1 = Kit() kit_1.wire_in("123 -> a") assert kit_1.wires["a"].output() == 123 kit_1.wire_in("NOT a -> b") assert kit_1.wires["b"].output() == 65412 with pytest.raises(NotImplementedError): kit_1.wire_in("NOT 123 -> c") kit_1.wire_in("a LSHIFT 3 -> c") assert kit_1.wires["c"].output() == 984 kit_1.wire_in("c RSHIFT 3 -> d") assert kit_1.wires["d"].output() == 123 def test_kit2(): kit_2 = Kit() kit_2.wire_in("123 -> x") kit_2.wire_in("456 -> y") kit_2.wire_in("x AND y -> d") kit_2.wire_in("x OR y -> e") kit_2.wire_in("x LSHIFT 2 -> f") kit_2.wire_in("y RSHIFT 2 -> g") kit_2.wire_in("NOT x -> h") kit_2.wire_in("NOT y -> i") assert kit_2.wires["d"].output() == 72 assert kit_2.wires["e"].output() == 507 assert kit_2.wires["f"].output() == 492 assert kit_2.wires["g"].output() == 114 assert kit_2.wires["h"].output() == 65412 assert kit_2.wires["i"].output() == 65079 assert kit_2.wires["x"].output() == 123 assert kit_2.wires["y"].output() == 456 def test_submission(): kit_sub = Kit() kit_sub.execute_directions() assert kit_sub.wires["a"].output() == 3176 # assert kit_sub.wires['a'].output() == 14710
10d96b7f5971f9b28f49ec364b828da700e6d616
jvano74/advent_of_code
/2018/day_13_test.py
10,792
4.28125
4
from typing import NamedTuple class Puzzle: r""" --- Day 13: Mine Cart Madness --- A crop of this size requires significant logistics to transport produce, soil, fertilizer, and so on. The Elves are very busy pushing things around in carts on some kind of rudimentary system of tracks they've come up with. Seeing as how cart-and-track systems don't appear in recorded history for another 1000 years, the Elves seem to be making this up as they go along. They haven't even figured out how to avoid collisions yet. You map out the tracks (your puzzle input) and see where you can help. Tracks consist of straight paths (| and -), curves (/ and \), and intersections (+). Curves connect exactly two perpendicular pieces of track; for example, this is a closed loop: /----\ | | | | \----/ Intersections occur when two perpendicular paths cross. At an intersection, a cart is capable of turning left, turning right, or continuing straight. Here are two loops connected by two intersections: /-----\ | | | /--+--\ | | | | \--+--/ | | | \-----/ Several carts are also on the tracks. Carts always face either up (^), down (v), left (<), or right (>). (On your initial map, the track under each cart is a straight path matching the direction the cart is facing.) Each time a cart has the option to turn (by arriving at any intersection), it turns left the first time, goes straight the second time, turns right the third time, and then repeats those directions starting again with left the fourth time, straight the fifth time, and so on. This process is independent of the particular intersection at which the cart has arrived - that is, the cart has no per-intersection memory. Carts all move at the same speed; they take turns moving a single step at a time. They do this based on their current location: carts on the top row move first (acting from left to right), then carts on the second row move (again from left to right), then carts on the third row, and so on. Once each cart has moved one step, the process repeats; each of these loops is called a tick. For example, suppose there are two carts on a straight track: | | | | | v | | | | | v v | | | | | v X | | ^ ^ | ^ ^ | | | | | | | | First, the top cart moves. It is facing down (v), so it moves down one square. Second, the bottom cart moves. It is facing up (^), so it moves up one square. Because all carts have moved, the first tick ends. Then, the process repeats, starting with the first cart. The first cart moves down, then the second cart moves up - right into the first cart, colliding with it! (The location of the crash is marked with an X.) This ends the second and last tick. Here is a longer example: /->-\ | | /----\ | /-+--+-\ | | | | | v | \-+-/ \-+--/ \------/ /-->\ | | /----\ | /-+--+-\ | | | | | | | \-+-/ \->--/ \------/ /---v | | /----\ | /-+--+-\ | | | | | | | \-+-/ \-+>-/ \------/ /---\ | v /----\ | /-+--+-\ | | | | | | | \-+-/ \-+->/ \------/ /---\ | | /----\ | /->--+-\ | | | | | | | \-+-/ \-+--^ \------/ /---\ | | /----\ | /-+>-+-\ | | | | | | ^ \-+-/ \-+--/ \------/ /---\ | | /----\ | /-+->+-\ ^ | | | | | | \-+-/ \-+--/ \------/ /---\ | | /----< | /-+-->-\ | | | | | | | \-+-/ \-+--/ \------/ /---\ | | /---<\ | /-+--+>\ | | | | | | | \-+-/ \-+--/ \------/ /---\ | | /--<-\ | /-+--+-v | | | | | | | \-+-/ \-+--/ \------/ /---\ | | /-<--\ | /-+--+-\ | | | | | v | \-+-/ \-+--/ \------/ /---\ | | /<---\ | /-+--+-\ | | | | | | | \-+-/ \-<--/ \------/ /---\ | | v----\ | /-+--+-\ | | | | | | | \-+-/ \<+--/ \------/ /---\ | | /----\ | /-+--v-\ | | | | | | | \-+-/ ^-+--/ \------/ /---\ | | /----\ | /-+--+-\ | | | | X | | \-+-/ \-+--/ \------/ After following their respective paths for a while, the carts eventually crash. To help prevent crashes, you'd like to know the location of the first crash. Locations are given in X,Y coordinates, where the furthest left column is X=0 and the furthest top row is Y=0: 111 0123456789012 0/---\ 1| | /----\ 2| /-+--+-\ | 3| | | X | | 4\-+-/ \-+--/ 5 \------/ In this example, the location of the first crash is 7,3. --- Part Two --- There isn't much you can do to prevent crashes in this ridiculous system. However, by predicting the crashes, the Elves know where to be in advance and instantly remove the two crashing carts the moment any crash occurs. They can proceed like this for a while, but eventually, they're going to run out of carts. It could be useful to figure out where the last cart that hasn't crashed will end up. For example: />-<\ | | | /<+-\ | | | v \>+</ | | ^ \<->/ /---\ | | | v-+-\ | | | | \-+-/ | | | ^---^ /---\ | | | /-+-\ | v | | \-+-/ | ^ ^ \---/ /---\ | | | /-+-\ | | | | \-+-/ ^ | | \---/ After four very expensive crashes, a tick ends with only one cart remaining; its final location is 6,4. What is the location of the last cart at the end of the first tick where it is the only cart left? """ pass SAMPLE = ['/->-\\', '| | /----\\', '| /-+--+-\\ |', '| | | | v |', '\\-+-/ \\-+--/', ' \\------/'] class Pt(NamedTuple): x: int y: int def __add__(self, other): return Pt(self.x + other.x, self.y + other.y) def __lt__(self, other): return (self.y, self.x) < (other.y, other.x) class Track: train_delta = { 'v|': ('v', Pt(0, 1)), '^|': ('^', Pt(0, -1)), '>-': ('>', Pt(1, 0)), '<-': ('<', Pt(-1, 0)), 'v/': ('<', Pt(-1, 0)), '^/': ('>', Pt(1, 0)), '>/': ('^', Pt(0, -1)), '</': ('v', Pt(0, 1)), 'v\\': ('>', Pt(1, 0)), '^\\': ('<', Pt(-1, 0)), '>\\': ('v', Pt(0, 1)), '<\\': ('^', Pt(0, -1)), 'vl': ('>', Pt(1, 0)), 'vs': ('v', Pt(0, 1)), 'vr': ('<', Pt(-1, 0)), '^l': ('<', Pt(-1, 0)), '^s': ('^', Pt(0, -1)), '^r': ('>', Pt(1, 0)), '>l': ('^', Pt(0, -1)), '>s': ('>', Pt(1, 0)), '>r': ('v', Pt(0, 1)), '<l': ('v', Pt(0, 1)), '<s': ('<', Pt(-1, 0)), '<r': ('^', Pt(0, -1)), 'l': 's', 's': 'r', 'r': 'l', } def __init__(self, raw_lines): self.trains = {} self.track = {} self.x_max = 0 self.y_max = 0 self.time = 0 self.train_time = 0 for y, raw_line in enumerate(raw_lines): self.y_max = max(y, self.y_max) self.x_max = max(len(raw_line), self.x_max) for x, c in enumerate(raw_line): pt = Pt(x, y) if c in {'+', '|', '/', '-', '\\'}: self.track[pt] = c elif c in {'^', 'v'}: self.trains[pt] = (c, 'l') self.track[pt] = '|' elif c in {'<', '>'}: self.trains[pt] = (c, 'l') self.track[pt] = '-' def print_track(self, show_trains=True, x_min=0, y_min=0, x_max=None, y_max=None): if y_max is None: y_max = self.y_max if x_max is None: x_max = self.x_max result = [] for y in range(y_min, y_max + 1): line = [f'{y}'.rjust(3, '0')] for x in range(x_min, x_max + 1): pt = Pt(x, y) c = self.track[pt] if pt in self.track else ' ' if show_trains and pt in self.trains: c = self.trains[pt][0] line.append(c) result.append(''.join(line)) return result def train_tick(self, train, loc): train_dir, train_mem = train if loc in self.track: track = self.track[loc] else: track = '?' train_track = f'{train_dir}{track}' if track != '+' else f'{train_dir}{train_mem}' if train_track not in self.train_delta: raise Exception(f'No delta for {train_track} at {loc}') new_train_dir, delta = self.train_delta[train_track] new_loc = loc + delta if track == '+': train_mem = self.train_delta[train_mem] return (new_train_dir, train_mem), new_loc def tick(self, remove_crashes=False): self.time += 1 self.train_time = 0 for train_loc in sorted(pt for pt in self.trains): if train_loc not in self.trains: pass # crashed train else: train = self.trains.pop(train_loc) self.train_time += 1 new_train, new_train_loc = self.train_tick(train, train_loc) if new_train_loc not in self.trains: self.trains[new_train_loc] = new_train elif remove_crashes: self.trains.pop(new_train_loc) # remove collision if len(self.trains) == 1: return self.trains else: return new_train_loc # collision return None def test_sample_track(): track = Track(SAMPLE) result = track.tick() # print() while result is None: result = track.tick() # print('\n'.join(track.print_track())) assert result == Pt(7, 3) with open('day_13_input.txt') as fp: INPUT = [line for line in fp] def test_puzzle_track(): track = Track(INPUT) # print() # print('\n'.join(track.print_track())) result = None while result is None: result = track.tick() # print() # print(f'{track.time}.{track.train_time}') # print('\n'.join(track.print_track())) assert result == Pt(108, 60) def test_puzzle2_track(): track = Track(INPUT) result = None while result is None: result = track.tick(remove_crashes=True) assert result == {Pt(x=92, y=42): ('<', 'l')}
9e212907e1c525fc1bc1ae0fec938e50dad02ac7
jvano74/advent_of_code
/2019/day_05_test.py
13,527
3.953125
4
import pytest from typing import List class Puzzle: """ --- Day 5: Sunny with a Chance of Asteroids --- You're starting to sweat as the ship makes its way toward Mercury. The Elves suggest that you get the air conditioner working by upgrading your ship computer to support the Thermal Environment Supervision Terminal. The Thermal Environment Supervision Terminal (TEST) starts by running a diagnostic program (your puzzle input). The TEST diagnostic program will run on your existing Intcode computer after a few modifications: First, you'll need to add two new instructions: Opcode 3 takes a single integer as input and saves it to the position given by its only parameter. For example, the instruction 3,50 would take an input value and store it at address 50. Opcode 4 outputs the value of its only parameter. For example, the instruction 4,50 would output the value at address 50. Programs that use these instructions will come with documentation that explains what should be connected to the input and output. The program 3,0,4,0,99 outputs whatever it gets as input, then halts. Second, you'll need to add support for parameter modes: Each parameter of an instruction is handled based on its parameter mode. Right now, your ship computer already understands parameter mode 0, position mode, which causes the parameter to be interpreted as a position - if the parameter is 50, its value is the value stored at address 50 in memory. Until now, all parameters have been in position mode. Now, your ship computer will also need to handle parameters in mode 1, immediate mode. In immediate mode, a parameter is interpreted as a value - if the parameter is 50, its value is simply 50. Parameter modes are stored in the same value as the instruction's opcode. The opcode is a two-digit number based only on the ones and tens digit of the value, that is, the opcode is the rightmost two digits of the first value in an instruction. Parameter modes are single digits, one per parameter, read right-to-left from the opcode: the first parameter's mode is in the hundreds digit, the second parameter's mode is in the thousands digit, the third parameter's mode is in the ten-thousands digit, and so on. Any missing modes are 0. For example, consider the program 1002,4,3,4,33. The first instruction, 1002,4,3,4, is a multiply instruction - the rightmost two digits of the first value, 02, indicate opcode 2, multiplication. Then, going right to left, the parameter modes are 0 (hundreds digit), 1 (thousands digit), and 0 (ten-thousands digit, not present and therefore zero): ABCDE 1002 DE - two-digit opcode, 02 == opcode 2 C - mode of 1st parameter, 0 == position mode B - mode of 2nd parameter, 1 == immediate mode A - mode of 3rd parameter, 0 == position mode, omitted due to being a leading zero This instruction multiplies its first two parameters. The first parameter, 4 in position mode, works like it did before - its value is the value stored at address 4 (33). The second parameter, 3 in immediate mode, simply has value 3. The result of this operation, 33 * 3 = 99, is written according to the third parameter, 4 in position mode, which also works like it did before - 99 is written to address 4. Parameters that an instruction writes to will never be in immediate mode. Finally, some notes: It is important to remember that the instruction pointer should increase by the number of values in the instruction after the instruction finishes. Because of the new instructions, this amount is no longer always 4. Integers can be negative: 1101,100,-1,4,0 is a valid program (find 100 + -1, store the result in position 4). The TEST diagnostic program will start by requesting from the user the ID of the system to test by running an input instruction - provide it 1, the ID for the ship's air conditioner unit. It will then perform a series of diagnostic tests confirming that various parts of the Intcode computer, like parameter modes, function correctly. For each test, it will run an output instruction indicating how far the result of the test was from the expected value, where 0 means the test was successful. Non-zero outputs mean that a function is not working correctly; check the instructions that were run before the output instruction to see which one failed. Finally, the program will output a diagnostic code and immediately halt. This final output isn't an error; an output followed immediately by a halt means the program finished. If all outputs were zero except the diagnostic code, the diagnostic program ran successfully. After providing 1 to the only input instruction and passing all the tests, what diagnostic code does the program produce? Your puzzle answer was 7566643. --- Part Two --- The air conditioner comes online! Its cold air feels good for a while, but then the TEST alarms start to go off. Since the air conditioner can't vent its heat anywhere but back into the spacecraft, it's actually making the air inside the ship warmer. Instead, you'll need to use the TEST to extend the thermal radiators. Fortunately, the diagnostic program (your puzzle input) is already equipped for this. Unfortunately, your Intcode computer is not. Your computer is only missing a few opcodes: Opcode 5 is jump-if-true: if the first parameter is non-zero, it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing. Opcode 6 is jump-if-false: if the first parameter is zero, it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing. Opcode 7 is less than: if the first parameter is less than the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0. Opcode 8 is equals: if the first parameter is equal to the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0. Like all instructions, these instructions need to support parameter modes as described above. Normally, after an instruction is finished, the instruction pointer increases by the number of values in that instruction. However, if the instruction modifies the instruction pointer, that value is used and the instruction pointer is not automatically increased. For example, here are several programs that take one input, compare it to the value 8, and then produce one output: 3,9,8,9,10,9,4,9,99,-1,8 - Using position mode, consider whether the input is equal to 8; output 1 (if it is) or 0 (if it is not). 3,9,7,9,10,9,4,9,99,-1,8 - Using position mode, consider whether the input is less than 8; output 1 (if it is) or 0 (if it is not). 3,3,1108,-1,8,3,4,3,99 - Using immediate mode, consider whether the input is equal to 8; output 1 (if it is) or 0 (if it is not). 3,3,1107,-1,8,3,4,3,99 - Using immediate mode, consider whether the input is less than 8; output 1 (if it is) or 0 (if it is not). Here are some jump tests that take an input, then output 0 if the input was zero or 1 if the input was non-zero: 3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9 (using position mode) 3,3,1105,-1,9,1101,0,0,12,4,12,99,1 (using immediate mode) Here's a larger example: 3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31, 1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104, 999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99 The above example program uses an input instruction to ask for a single number. The program will then output 999 if the input value is below 8, output 1000 if the input value is equal to 8, or output 1001 if the input value is greater than 8. This time, when the TEST diagnostic program runs its input instruction to get the ID of the system to test, provide it 5, the ID for the ship's thermal radiator controller. This diagnostic test suite only outputs one number, the diagnostic code. What is the diagnostic code for system ID 5? Your puzzle answer was 9265694. """ pass HALT = 99 ADD = 1 MULTIPLY = 2 INPUT = 3 OUTPUT = 4 JIFTRUE = 5 JIFFALSE = 6 LESSTHAN = 7 EQUAL = 8 class Program: def __init__(self, program): self.head = 0 self.disk = list(program) self.memory = list(program) self.input = [] self.output = [] def reset(self): self.head = 0 self.memory = list(self.disk) self.input = [] self.output = [] def process(self): optcode = self.memory[self.head] % 100 modes = self.memory[self.head] // 100 if optcode in [INPUT, OUTPUT]: self.process_one_parameter_operation(modes, optcode) elif optcode in [JIFTRUE, JIFFALSE]: self.process_two_parameter_operation(modes, optcode) elif optcode in [ADD, MULTIPLY, LESSTHAN, EQUAL]: self.process_three_parameter_operation(modes, optcode) else: raise SyntaxError(f'Unknown optcode {optcode}') def process_one_parameter_operation(self, modes, optcode): aa = self.memory[self.head + 1] a = aa if modes % 10 else self.memory[aa] modes //= 10 if optcode == INPUT: self.memory[aa] = self.input.pop() elif optcode == OUTPUT: self.output.append(a) else: raise SyntaxError(f'Unknown optcode {optcode}') self.head += 2 def process_two_parameter_operation(self, modes, optcode): aa = self.memory[self.head + 1] a = aa if modes % 10 else self.memory[aa] modes //= 10 ab = self.memory[self.head + 2] b = ab if modes % 10 else self.memory[ab] modes //= 10 if optcode == JIFTRUE: if a: self.head = b return elif optcode == JIFFALSE: if not a: self.head = b return else: raise SyntaxError(f'Unknown optcode {optcode}') self.head += 3 def process_three_parameter_operation(self, modes, optcode): aa = self.memory[self.head + 1] a = aa if modes % 10 else self.memory[aa] modes //= 10 ab = self.memory[self.head + 2] b = ab if modes % 10 else self.memory[ab] modes //= 10 ac = self.memory[self.head + 3] if optcode == ADD: self.memory[ac] = a + b elif optcode == MULTIPLY: self.memory[ac] = a * b elif optcode == LESSTHAN: self.memory[ac] = 1 if a < b else 0 elif optcode == EQUAL: self.memory[ac] = 1 if a == b else 0 else: raise SyntaxError(f'Unknown optcode {optcode}') self.head += 4 def run(self, run_input: List[int]) -> List[int]: self.input = run_input while self.memory[self.head] != HALT: self.process() return self.output def test_program(): error_program = Program([555]) with pytest.raises(SyntaxError): error_program.run([]) p1 = Program([1, 0, 0, 0, 99]) assert p1.run([]) == [] and p1.memory == [2, 0, 0, 0, 99] p2 = Program([2, 3, 0, 3, 99]) assert p2.run([]) == [] and p2.memory == [2, 3, 0, 6, 99] p3 = Program([2, 4, 4, 5, 99, 0]) assert p3.run([]) == [] and p3.memory == [2, 4, 4, 5, 99, 9801] p4 = Program([1, 1, 1, 4, 99, 5, 6, 0, 99]) assert p4.run([]) == [] and p4.memory == [30, 1, 1, 4, 2, 5, 6, 0, 99] # IO TESTS io = Program([3, 0, 4, 0, 99]) assert io.run([12]) == [12] and io.memory == [12, 0, 4, 0, 99] # COMPARE TESTS p5 = Program([3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8]) assert p5.run([8]) == [1] p5.reset() assert p5.run([7]) == [0] p6 = Program([3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8]) assert p6.run([7]) == [1] p6.reset() assert p6.run([8]) == [0] p7 = Program([3, 3, 1108, -1, 8, 3, 4, 3, 99]) assert p7.run([8]) == [1] p8 = Program([3, 3, 1107, -1, 8, 3, 4, 3, 99]) assert p8.run([7]) == [1] p8.reset() assert p8.run([8]) == [0] # JUMP TESTS pjump1 = Program([3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9]) assert pjump1.run([0]) == [0] pjump1.reset() assert pjump1.run([4]) == [1] pjump2 = Program([3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1]) assert pjump2.run([0]) == [0] pjump2.reset() assert pjump2.run([7]) == [1] pbig = Program([3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99]) assert pbig.run([7]) == [999] pbig.reset() assert pbig.run([8]) == [1000] pbig.reset() assert pbig.run([9]) == [1001] def test_run_diagnosis(): with open('day_05_input.txt') as fp: raw = fp.read() raw_diag_prog = [int(d) for d in raw.split(',')] diag_prog = Program(raw_diag_prog) assert diag_prog.run([1]) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 7566643] diag_prog.reset() assert diag_prog.run([5]) == [9265694]
63e9319fbce60cfec3ce6606aa8b9969b5e68d13
jvano74/advent_of_code
/2015/day_11_test.py
3,667
4.21875
4
import re def new_password(pwd): """ --- Day 11: Corporate Policy --- Santa's previous password expired, and he needs help choosing a new one. To help him remember his new password after the old one expires, Santa has devised a method of coming up with a password based on the previous one. Corporate policy dictates that passwords must be exactly eight lowercase letters (for security reasons), so he finds his new password by incrementing his old password string repeatedly until it is valid. Incrementing is just like counting with numbers: xx, xy, xz, ya, yb, and so on. Increase the rightmost letter one step; if it was z, it wraps around to a, and repeat with the next letter to the left until one doesn't wrap around. Unfortunately for Santa, a new Security-Elf recently started, and he has imposed some additional password requirements: Passwords must include one increasing straight of at least three letters, like abc, bcd, cde, and so on, up to xyz. They cannot skip letters; abd doesn't count. Passwords may not contain the letters i, o, or l, as these letters can be mistaken for other characters and are therefore confusing. Passwords must contain at least two different, non-overlapping pairs of letters, like aa, bb, or zz. For example: hijklmmn meets the first requirement (because it contains the straight hij) but fails the second requirement requirement (because it contains i and l). abbceffg meets the third requirement (because it repeats bb and ff) but fails the first requirement. abbcegjk fails the third requirement, because it only has one double letter (bb). The next password after abcdefgh is abcdffaa. The next password after ghijklmn is ghjaabcc, because you eventually skip all the passwords that start with ghi..., since i is not allowed. Given Santa's current password (your puzzle input), what should his next password be? Your puzzle input is vzbxkghb. """ new_pwd = incrament(pwd) while not is_pwd_valid(new_pwd): new_pwd = incrament(new_pwd) return new_pwd def incrament(pwd): tail = 1 while pwd[-tail] == 'z': tail += 1 if tail == 1 + len(pwd): return 'a' * len(pwd) return pwd[:-tail] + chr(ord(pwd[-tail]) + 1) + ('a' * (tail-1)) def has_straight(pwd): run = 1 next = chr(ord(pwd[0]) + 1) for c in pwd[1:]: if c == next: run += 1 if run == 3: return True else: run = 1 next = chr(ord(c) + 1) return False def is_pwd_valid(pwd): if re.match(r'.*[iol]', pwd): return False doubles = re.findall(r'(.)\1', pwd) if doubles: if len(set(doubles)) < 2: return False if has_straight(pwd): return True return False def test_new_password(): assert incrament('aaa') == 'aab' assert incrament('abb') == 'abc' assert incrament('abz') == 'aca' assert incrament('czz') == 'daa' assert incrament('zzzz') == 'aaaa' assert has_straight('abceef') == True assert has_straight('abbcdd') == True assert has_straight('abbccdd') == False assert is_pwd_valid('aia') == False assert is_pwd_valid('hijklmmn') == False assert is_pwd_valid('abbceffg') == False assert is_pwd_valid('abbcegjk') == False assert new_password('abcdefgh') == 'abcdffaa' assert new_password('ghijklmn') == 'ghjaabcc' def test_submission(): assert new_password('vzbxkghb') == 'vzbxxyzz' assert new_password('vzbxxyzz') == 'vzcaabcc'
42b7050430419a715dc0091175975d929709c83b
jvano74/advent_of_code
/2019/day_20_test.py
15,353
4.09375
4
from typing import Set, Dict, List, NamedTuple from collections import deque, defaultdict class Puzzle: """ --- Day 20: Donut Maze --- You notice a strange pattern on the surface of Pluto and land nearby to get a closer look. Upon closer inspection, you realize you've come across one of the famous space-warping mazes of the long-lost Pluto civilization! Because there isn't much space on Pluto, the civilization that used to live here thrived by inventing a method for folding spacetime. Although the technology is no longer understood, mazes like this one provide a small glimpse into the daily life of an ancient Pluto citizen. This maze is shaped like a donut. Portals along the inner and outer edge of the donut can instantly teleport you from one side to the other. For example: A A #######.######### #######.........# #######.#######.# #######.#######.# #######.#######.# ##### B ###.# BC...## C ###.# ##.## ###.# ##...DE F ###.# ##### G ###.# #########.#####.# DE..#######...###.# #.#########.###.# FG..#########.....# ###########.##### Z Z This map of the maze shows solid walls (#) and open passages (.). Every maze on Pluto has a start (the open tile next to AA) and an end (the open tile next to ZZ). Mazes on Pluto also have portals; this maze has three pairs of portals: BC, DE, and FG. When on an open tile next to one of these labels, a single step can take you to the other tile with the same label. (You can only walk on . tiles; labels and empty space are not traversable.) One path through the maze doesn't require any portals. Starting at AA, you could go down 1, right 8, down 12, left 4, and down 1 to reach ZZ, a total of 26 steps. However, there is a shorter path: You could walk from AA to the inner BC portal (4 steps), warp to the outer BC portal (1 step), walk to the inner DE (6 steps), warp to the outer DE (1 step), walk to the outer FG (4 steps), warp to the inner FG (1 step), and finally walk to ZZ (6 steps). In total, this is only 23 steps. Here is a larger example: A A #################.############# #.#...#...................#.#.# #.#.#.###.###.###.#########.#.# #.#.#.......#...#.....#.#.#...# #.#########.###.#####.#.#.###.# #.............#.#.....#.......# ###.###########.###.#####.#.#.# #.....# A C #.#.#.# ####### S P #####.# #.#...# #......VT #.#.#.# #.##### #...#.# YN....#.# #.###.# #####.# DI....#.# #.....# #####.# #.###.# ZZ......# QG....#..AS ###.### ####### JO..#.#.# #.....# #.#.#.# ###.#.# #...#..DI BU....#..LF #####.# #.##### YN......# VT..#....QG #.###.# #.###.# #.#...# #.....# ###.### J L J #.#.### #.....# O F P #.#...# #.###.#####.#.#####.#####.###.# #...#.#.#...#.....#.....#.#...# #.#####.###.###.#.#.#########.# #...#.#.....#...#.#.#.#.....#.# #.###.#####.###.###.#.#.####### #.#.........#...#.............# #########.###.###.############# B J C U P P Here, AA has no direct path to ZZ, but it does connect to AS and CP. By passing through AS, QG, BU, and JO, you can reach ZZ in 58 steps. In your maze, how many steps does it take to get from the open tile marked AA to the open tile marked ZZ? Your puzzle answer was 644. --- Part Two --- Strangely, the exit isn't open when you reach it. Then, you remember: the ancient Plutonians were famous for building recursive spaces. The marked connections in the maze aren't portals: they physically connect to a larger or smaller copy of the maze. Specifically, the labeled tiles around the inside edge actually connect to a smaller copy of the same maze, and the smaller copy's inner labeled tiles connect to yet a smaller copy, and so on. When you enter the maze, you are at the outermost level; when at the outermost level, only the outer labels AA and ZZ function (as the start and end, respectively); all other outer labeled tiles are effectively walls. At any other level, AA and ZZ count as walls, but the other outer labeled tiles bring you one level outward. Your goal is to find a path through the maze that brings you back to ZZ at the outermost level of the maze. In the first example above, the shortest path is now the loop around the right side. If the starting level is 0, then taking the previously-shortest path would pass through BC (to level 1), DE (to level 2), and FG (back to level 1). Because this is not the outermost level, ZZ is a wall, and the only option is to go back around to BC, which would only send you even deeper into the recursive maze. In the second example above, there is no path that brings you to ZZ at the outermost level. Here is a more interesting example: Z L X W C Z P Q B K ###########.#.#.#.#######.############### #...#.......#.#.......#.#.......#.#.#...# ###.#.#.#.#.#.#.#.###.#.#.#######.#.#.### #.#...#.#.#...#.#.#...#...#...#.#.......# #.###.#######.###.###.#.###.###.#.####### #...#.......#.#...#...#.............#...# #.#########.#######.#.#######.#######.### #...#.# F R I Z #.#.#.# #.###.# D E C H #.#.#.# #.#...# #...#.# #.###.# #.###.# #.#....OA WB..#.#..ZH #.###.# #.#.#.# CJ......# #.....# ####### ####### #.#....CK #......IC #.###.# #.###.# #.....# #...#.# ###.### #.#.#.# XF....#.# RF..#.#.# #####.# ####### #......CJ NM..#...# ###.#.# #.###.# RE....#.# #......RF ###.### X X L #.#.#.# #.....# F Q P #.#.#.# ###.###########.###.#######.#########.### #.....#...#.....#.......#...#.....#.#...# #####.#.###.#######.#######.###.###.#.#.# #.......#.......#.#.#.#.#...#...#...#.#.# #####.###.#####.#.#.#.#.###.###.#.###.### #.......#.....#.#...#...............#...# #############.#.#.###.################### A O F N A A D M One shortest path through the maze is the following: Walk from AA to XF (16 steps) Recurse into level 1 through XF (1 step) Walk from XF to CK (10 steps) Recurse into level 2 through CK (1 step) Walk from CK to ZH (14 steps) Recurse into level 3 through ZH (1 step) Walk from ZH to WB (10 steps) Recurse into level 4 through WB (1 step) Walk from WB to IC (10 steps) Recurse into level 5 through IC (1 step) Walk from IC to RF (10 steps) Recurse into level 6 through RF (1 step) Walk from RF to NM (8 steps) Recurse into level 7 through NM (1 step) Walk from NM to LP (12 steps) Recurse into level 8 through LP (1 step) Walk from LP to FD (24 steps) Recurse into level 9 through FD (1 step) Walk from FD to XQ (8 steps) Recurse into level 10 through XQ (1 step) Walk from XQ to WB (4 steps) Return to level 9 through WB (1 step) Walk from WB to ZH (10 steps) Return to level 8 through ZH (1 step) Walk from ZH to CK (14 steps) Return to level 7 through CK (1 step) Walk from CK to XF (10 steps) Return to level 6 through XF (1 step) Walk from XF to OA (14 steps) Return to level 5 through OA (1 step) Walk from OA to CJ (8 steps) Return to level 4 through CJ (1 step) Walk from CJ to RE (8 steps) Return to level 3 through RE (1 step) Walk from RE to IC (4 steps) Recurse into level 4 through IC (1 step) Walk from IC to RF (10 steps) Recurse into level 5 through RF (1 step) Walk from RF to NM (8 steps) Recurse into level 6 through NM (1 step) Walk from NM to LP (12 steps) Recurse into level 7 through LP (1 step) Walk from LP to FD (24 steps) Recurse into level 8 through FD (1 step) Walk from FD to XQ (8 steps) Recurse into level 9 through XQ (1 step) Walk from XQ to WB (4 steps) Return to level 8 through WB (1 step) Walk from WB to ZH (10 steps) Return to level 7 through ZH (1 step) Walk from ZH to CK (14 steps) Return to level 6 through CK (1 step) Walk from CK to XF (10 steps) Return to level 5 through XF (1 step) Walk from XF to OA (14 steps) Return to level 4 through OA (1 step) Walk from OA to CJ (8 steps) Return to level 3 through CJ (1 step) Walk from CJ to RE (8 steps) Return to level 2 through RE (1 step) Walk from RE to XQ (14 steps) Return to level 1 through XQ (1 step) Walk from XQ to FD (8 steps) Return to level 0 through FD (1 step) Walk from FD to ZZ (18 steps) This path takes a total of 396 steps to move from AA at the outermost layer to ZZ at the outermost layer. In your maze, when accounting for recursion, how many steps does it take to get from the open tile marked AA to the open tile marked ZZ, both at the outermost layer? Your puzzle answer was 7798. """ pass class Pos(NamedTuple): x: int y: int DELTAS = {Pos(1, 0), Pos(-1, 0), Pos(0, 1), Pos(0, -1)} def signature(new_key, key_hx): return frozenset(new_key), frozenset(key_hx) class Maze: def __init__(self, grid: List[List[str]]): self.tiles = set() self.portals = defaultdict(set) self.portal_ends = {} self.start = None self.end = None raw_portals = {} for j, row in enumerate(grid): for i, c in enumerate(row): if c == '#' or c == ' ' or c == 'h' or c == 'e': continue if c == '.': self.tiles.add(Pos(i, j)) continue if 'A' <= c <= 'Z': raw_portals[Pos(i, j)] = c continue for pos1 in raw_portals: for d in DELTAS: pos2 = Pos(pos1.x + d.x, pos1.y + d.y) pos3 = Pos(pos2.x + d.x, pos2.y + d.y) if pos2 in raw_portals and pos3 in self.tiles: if d == Pos(-1,0) or d == Pos(0,-1): name = raw_portals[pos2] + raw_portals[pos1] else: name = raw_portals[pos1] + raw_portals[pos2] if name == 'AA': self.start = pos3 continue if name == 'ZZ': self.end = pos3 continue self.portals[name].add(pos3) self.portal_ends[pos2] = name def neighbors(self, pos: Pos) -> Set[Pos]: found = set() for d in DELTAS: possible_neighbor = Pos(pos.x + d.x, pos.y + d.y) if possible_neighbor in self.tiles: found.add(possible_neighbor) if possible_neighbor in self.portal_ends: portal_name = self.portal_ends[possible_neighbor] ends = set(self.portals[portal_name]) ends.remove(pos) other_end = ends.pop() found.add(other_end) return found def shortest_path(self, start: Pos, end: Pos) -> List: frontier = deque() visited = set() frontier.append((start, [start])) visited.add(start) while frontier: pos, path_hx = frontier.popleft() for nn in self.neighbors(pos): if nn not in visited: if nn == end: path_hx.append(nn) return path_hx new_hx = list(path_hx) new_hx.append(nn) frontier.append((nn, new_hx)) visited.add(nn) raise LookupError(f'Not {end} not part of {start}') MAZE_1 = """ A A #######.######### #######.........# #######.#######.# #######.#######.# #######.#######.# ##### B ###.# BC...## C ###.# ##.## ###.# ##...DE F ###.# ##### G ###.# #########.#####.# DE..#######...###.# #.#########.###.# FG..#########.....# ###########.##### Z Z """ MAZE_2 = """ A A #################.############# #.#...#...................#.#.# #.#.#.###.###.###.#########.#.# #.#.#.......#...#.....#.#.#...# #.#########.###.#####.#.#.###.# #.............#.#.....#.......# ###.###########.###.#####.#.#.# #.....# A C #.#.#.# ####### S P #####.# #.#...# #......VT #.#.#.# #.##### #...#.# YN....#.# #.###.# #####.# DI....#.# #.....# #####.# #.###.# ZZ......# QG....#..AS ###.### ####### JO..#.#.# #.....# #.#.#.# ###.#.# #...#..DI BU....#..LF #####.# #.##### YN......# VT..#....QG #.###.# #.###.# #.#...# #.....# ###.### J L J #.#.### #.....# O F P #.#...# #.###.#####.#.#####.#####.###.# #...#.#.#...#.....#.....#.#...# #.#####.###.###.#.#.#########.# #...#.#.....#...#.#.#.#.....#.# #.###.#####.###.###.#.#.####### #.#.........#...#.............# #########.###.###.############# B J C U P P """ with open('day_20_input.txt') as fp: SUBMISSION = fp.read() def help_test_maze_min(raw: str, expected_path_length: int): maze = Maze([list(row) for row in raw.split('\n')]) assert len(maze.shortest_path(maze.start, maze.end))-1 == expected_path_length def test_create_maze_details(): maze = Maze([list(row) for row in MAZE_1.split('\n')]) assert maze.start == Pos(9,3) assert maze.end == Pos(13,17) portal = set(maze.portals['BC']).pop() assert portal == Pos(2,9) assert maze.neighbors(portal) == {Pos(x=9, y=7), Pos(x=3, y=9)} def test_maze_min_length(): help_test_maze_min(MAZE_1, 23) help_test_maze_min(MAZE_2, 58) def test_submission(): help_test_maze_min(SUBMISSION, 644)
617d9049e16911c42ae49610f4c61a24fc045eb8
jvano74/advent_of_code
/2021/day_25_test.py
10,150
4
4
from typing import NamedTuple class Puzzle: """ --- Day 25: Sea Cucumber --- This is it: the bottom of the ocean trench, the last place the sleigh keys could be. Your submarine's experimental antenna still isn't boosted enough to detect the keys, but they must be here. All you need to do is reach the seafloor and find them. At least, you'd touch down on the seafloor if you could; unfortunately, it's completely covered by two large herds of sea cucumbers, and there isn't an open space large enough for your submarine. You suspect that the Elves must have done this before, because just then you discover the phone number of a deep-sea marine biologist on a handwritten note taped to the wall of the submarine's cockpit. "Sea cucumbers? Yeah, they're probably hunting for food. But don't worry, they're predictable critters: they move in perfectly straight lines, only moving forward when there's space to do so. They're actually quite polite!" You explain that you'd like to predict when you could land your submarine. "Oh that's easy, they'll eventually pile up and leave enough space for-- wait, did you say submarine? And the only place with that many sea cucumbers would be at the very bottom of the Mariana--" You hang up the phone. There are two herds of sea cucumbers sharing the same region; one always moves east (>), while the other always moves south (v). Each location can contain at most one sea cucumber; the remaining locations are empty (.). The submarine helpfully generates a map of the situation (your puzzle input). For example: v...>>.vv> .vv>>.vv.. >>.>v>...v >>v>>.>.v. v>v.vv.v.. >.>>..v... .vv..>.>v. v.v..>>v.v ....v..v.> Every step, the sea cucumbers in the east-facing herd attempt to move forward one location, then the sea cucumbers in the south-facing herd attempt to move forward one location. When a herd moves forward, every sea cucumber in the herd first simultaneously considers whether there is a sea cucumber in the adjacent location it's facing (even another sea cucumber facing the same direction), and then every sea cucumber facing an empty location simultaneously moves into that location. So, in a situation like this: ...>>>>>... After one step, only the rightmost sea cucumber would have moved: ...>>>>.>.. After the next step, two sea cucumbers move: ...>>>.>.>. During a single step, the east-facing herd moves first, then the south-facing herd moves. So, given this situation: .......... .>v....v.. .......>.. .......... After a single step, of the sea cucumbers on the left, only the south-facing sea cucumber has moved (as it wasn't out of the way in time for the east-facing cucumber on the left to move), but both sea cucumbers on the right have moved (as the east-facing sea cucumber moved out of the way of the south-facing sea cucumber): .......... .>........ ..v....v>. .......... Due to strong water currents in the area, sea cucumbers that move off the right edge of the map appear on the left edge, and sea cucumbers that move off the bottom edge of the map appear on the top edge. Sea cucumbers always check whether their destination location is empty before moving, even if that destination is on the opposite side of the map: Initial state: ...>... ....... ......> v.....> ......> ....... ..vvv.. After 1 step: ..vv>.. ....... >...... v.....> >...... ....... ....v.. After 2 steps: ....v>. ..vv... .>..... ......> v>..... ....... ....... After 3 steps: ......> ..v.v.. ..>v... >...... ..>.... v...... ....... After 4 steps: >...... ..v.... ..>.v.. .>.v... ...>... ....... v...... To find a safe place to land your submarine, the sea cucumbers need to stop moving. Again consider the first example: Initial state: v...>>.vv> .vv>>.vv.. >>.>v>...v >>v>>.>.v. v>v.vv.v.. >.>>..v... .vv..>.>v. v.v..>>v.v ....v..v.> After 1 step: ....>.>v.> v.v>.>v.v. >v>>..>v.. >>v>v>.>.v .>v.v...v. v>>.>vvv.. ..v...>>.. vv...>>vv. >.v.v..v.v After 2 steps: >.v.v>>..v v.v.>>vv.. >v>.>.>.v. >>v>v.>v>. .>..v....v .>v>>.v.v. v....v>v>. .vv..>>v.. v>.....vv. After 3 steps: v>v.v>.>v. v...>>.v.v >vv>.>v>.. >>v>v.>.v> ..>....v.. .>.>v>v..v ..v..v>vv> v.v..>>v.. .v>....v.. After 4 steps: v>..v.>>.. v.v.>.>.v. >vv.>>.v>v >>.>..v>.> ..v>v...v. ..>>.>vv.. >.v.vv>v.v .....>>vv. vvv>...v.. After 5 steps: vv>...>v>. v.v.v>.>v. >.v.>.>.>v >v>.>..v>> ..v>v.v... ..>.>>vvv. .>...v>v.. ..v.v>>v.v v.v.>...v. ... After 10 steps: ..>..>>vv. v.....>>.v ..v.v>>>v> v>.>v.>>>. ..v>v.vv.v .v.>>>.v.. v.v..>v>.. ..v...>v.> .vv..v>vv. ... After 20 steps: v>.....>>. >vv>.....v .>v>v.vv>> v>>>v.>v.> ....vv>v.. .v.>>>vvv. ..v..>>vv. v.v...>>.v ..v.....v> ... After 30 steps: .vv.v..>>> v>...v...> >.v>.>vv.> >v>.>.>v.> .>..v.vv.. ..v>..>>v. ....v>..>v v.v...>vv> v.v...>vvv ... After 40 steps: >>v>v..v.. ..>>v..vv. ..>>>v.>.v ..>>>>vvv> v.....>... v.v...>v>> >vv.....v> .>v...v.>v vvv.v..v.> ... After 50 steps: ..>>v>vv.v ..v.>>vv.. v.>>v>>v.. ..>>>>>vv. vvv....>vv ..v....>>> v>.......> .vv>....v> .>v.vv.v.. ... After 55 steps: ..>>v>vv.. ..v.>>vv.. ..>>v>>vv. ..>>>>>vv. v......>vv v>v....>>v vvv...>..> >vv.....>. .>v.vv.v.. After 56 steps: ..>>v>vv.. ..v.>>vv.. ..>>v>>vv. ..>>>>>vv. v......>vv v>v....>>v vvv....>.> >vv......> .>v.vv.v.. After 57 steps: ..>>v>vv.. ..v.>>vv.. ..>>v>>vv. ..>>>>>vv. v......>vv v>v....>>v vvv.....>> >vv......> .>v.vv.v.. After 58 steps: ..>>v>vv.. ..v.>>vv.. ..>>v>>vv. ..>>>>>vv. v......>vv v>v....>>v vvv.....>> >vv......> .>v.vv.v.. In this example, the sea cucumbers stop moving after 58 steps. Find somewhere safe to land your submarine. What is the first step on which no sea cucumbers move? To begin, get your puzzle input. --- Part Two --- Suddenly, the experimental antenna control console lights up: Sleigh keys detected! According to the console, the keys are directly under the submarine. You landed right on them! Using a robotic arm on the submarine, you move the sleigh keys into the airlock. Now, you just need to get them to Santa in time to save Christmas! You check your clock - it is Christmas. There's no way you can get them back to the surface in time. Just as you start to lose hope, you notice a button on the sleigh keys: remote start. You can start the sleigh from the bottom of the ocean! You just need some way to boost the signal from the keys so it actually reaches the sleigh. Good thing the submarine has that experimental antenna! You'll definitely need 50 stars to boost it that far, though. The experimental antenna control console lights up again: Energy source detected. Integrating energy source from device "sleigh keys"...done. Installing device drivers...done. Recalibrating experimental antenna...done. Boost strength due to matching signal phase: 1 star Only 49 stars to go. You have enough stars to Remotely Start The Sleigh. """ with open('day_25_input.txt') as fp: RAW_INPUT = fp.read() RAW_SAMPLE = '''v...>>.vv> .vv>>.vv.. >>.>v>...v >>v>>.>.v. v>v.vv.v.. >.>>..v... .vv..>.>v. v.v..>>v.v ....v..v.> ''' class Pt(NamedTuple): x: int y: int def __add__(self, other): return Pt(self.x + other.x, self.y + other.y) class SeaFloor: def __init__(self, raw_map): self.map = dict() self.max_x = 0 self.max_y = 0 for y, line in enumerate(raw_map.split('\n')): for x, c in enumerate(line): self.max_x, self.max_y = max(self.max_x, x), max(self.max_y, y) self.map[Pt(x, y)] = c def step(self, print_map=False): next_map = dict() for pt, c in self.map.items(): if c != '>': if pt not in next_map: next_map[pt] = c continue next_pt = pt + Pt(1, 0) if next_pt not in self.map: next_pt = Pt(0, pt.y) if self.map[next_pt] == '.': next_map[pt] = '.' next_map[next_pt] = c else: next_map[pt] = c final_map = dict() for pt, c in next_map.items(): if c != 'v': if pt not in final_map: final_map[pt] = c continue next_pt = pt + Pt(0, 1) if next_pt not in next_map: next_pt = Pt(pt.x, 0) if next_map[next_pt] == '.': final_map[pt] = '.' final_map[next_pt] = c else: final_map[pt] = c if print_map: image = [] for y in range(0, self.max_y + 1): line = [] for x in range(0, self.max_x + 1): line.append(final_map[Pt(x, y)]) image.append(''.join(line)) print('\n') print('\n'.join(image)) print('\n\n') changed = False if final_map == self.map else True self.map = final_map return changed def run(self, print_map=False): n = 0 while self.step(print_map): n += 1 return n + 1 def test_run_time(): sample = SeaFloor(RAW_SAMPLE) assert sample.run() == 58 my_map = SeaFloor(RAW_INPUT) assert my_map.run() == 400
7c3476b4ff2b1b25c2fa797ab8dd45713736aec7
jvano74/advent_of_code
/2019/day_10_test.py
10,979
3.875
4
from numpy import sin, cos, pi, arctan2 from collections import defaultdict from typing import List class Puzzle: """ --- Day 10: Monitoring Station --- You fly into the asteroid belt and reach the Ceres monitoring station. The Elves here have an emergency: they're having trouble tracking all of the asteroids and can't be sure they're safe. The Elves would like to build a new monitoring station in a nearby area of space; they hand you a map of all of the asteroids in that region (your puzzle input). The map indicates whether each position is empty (.) or contains an asteroid (#). The asteroids are much smaller than they appear on the map, and every asteroid is exactly in the center of its marked position. The asteroids can be described with X,Y coordinates where X is the distance from the left edge and Y is the distance from the top edge (so the top-left corner is 0,0 and the position immediately to its right is 1,0). Your job is to figure out which asteroid would be the best place to build a new monitoring station. A monitoring station can detect any asteroid to which it has direct line of sight - that is, there cannot be another asteroid exactly between them. This line of sight can be at any angle, not just lines aligned to the grid or diagonally. The best location is the asteroid that can detect the largest number of other asteroids. For example, consider the following map: .#..# ..... ##### ....# ...## The best location for a new monitoring station on this map is the highlighted asteroid at 3,4 because it can detect 8 asteroids, more than any other location. (The only asteroid it cannot detect is the one at 1,0; its view of this asteroid is blocked by the asteroid at 2,2.) All other asteroids are worse locations; they can detect 7 or fewer other asteroids. Here is the number of other asteroids a monitoring station on each asteroid could detect: .7..7 ..... 67775 ....7 ...87 Here is an asteroid (#) and some examples of the ways its line of sight might be blocked. If there were another asteroid at the location of a capital letter, the locations marked with the corresponding lowercase letter would be blocked and could not be detected: #......... ...A...... ...B..a... .EDCG....a ..F.c.b... .....c.... ..efd.c.gb .......c.. ....f...c. ...e..d..c Here are some larger examples: Best is 5,8 with 33 other asteroids detected: ......#.#. #..#.#.... ..#######. .#.#.###.. .#..#..... ..#....#.# #..#....#. .##.#..### ##...#..#. .#....#### Best is 1,2 with 35 other asteroids detected: #.#...#.#. .###....#. .#....#... ##.#.#.#.# ....#.#.#. .##..###.# ..#...##.. ..##....## ......#... .####.###. Best is 6,3 with 41 other asteroids detected: .#..#..### ####.###.# ....###.#. ..###.##.# ##.##.#.#. ....###..# ..#.#..#.# #..#.#.### .##...##.# .....#.#.. Best is 11,13 with 210 other asteroids detected: .#..##.###...####### ##.############..##. .#.######.########.# .###.#######.####.#. #####.##.#.##.###.## ..#####..#.######### #################### #.####....###.#.#.## ##.################# #####.##.###..####.. ..######..##.####### ####.##.####...##..# .#####..#.######.### ##...#.##########... #.##########.####### .####.#.###.###.#.## ....##.##.###..##### .#.#.###########.### #.#.#.#####.####.### ###.##.####.##.#..## Find the best location for a new monitoring station. How many other asteroids can be detected from that location? Your puzzle answer was 340. --- Part Two --- Once you give them the coordinates, the Elves quickly deploy an Instant Monitoring Station to the location and discover the worst: there are simply too many asteroids. The only solution is complete vaporization by giant laser. Fortunately, in addition to an asteroid scanner, the new monitoring station also comes equipped with a giant rotating laser perfect for vaporizing asteroids. The laser starts by pointing up and always rotates clockwise, vaporizing any asteroid it hits. If multiple asteroids are exactly in line with the station, the laser only has enough power to vaporize one of them before continuing its rotation. In other words, the same asteroids that can be detected can be vaporized, but if vaporizing one asteroid makes another one detectable, the newly-detected asteroid won't be vaporized until the laser has returned to the same position by rotating a full 360 degrees. For example, consider the following map, where the asteroid with the new monitoring station (and laser) is marked X: .#....#####...#.. ##...##.#####..## ##...#...#.#####. ..#.....X...###.. ..#.#.....#....## The first nine asteroids to get vaporized, in order, would be: .#....###24...#.. ##...##.13#67..9# ##...#...5.8####. ..#.....X...###.. ..#.#.....#....## Note that some asteroids (the ones behind the asteroids marked 1, 5, and 7) won't have a chance to be vaporized until the next full rotation. The laser continues rotating; the next nine to be vaporized are: .#....###.....#.. ##...##...#.....# ##...#......1234. ..#.....X...5##.. ..#.9.....8....76 The next nine to be vaporized are then: .8....###.....#.. 56...9#...#.....# 34...7........... ..2.....X....##.. ..1.............. Finally, the laser completes its first full rotation (1 through 3), a second rotation (4 through 8), and vaporizes the last asteroid (9) partway through its third rotation: ......234.....6.. ......1...5.....7 ................. ........X....89.. ................. In the large example above (the one with the best monitoring station location at 11,13): The 1st asteroid to be vaporized is at 11,12. The 2nd asteroid to be vaporized is at 12,1. The 3rd asteroid to be vaporized is at 12,2. The 10th asteroid to be vaporized is at 12,8. The 20th asteroid to be vaporized is at 16,0. The 50th asteroid to be vaporized is at 16,9. The 100th asteroid to be vaporized is at 10,16. The 199th asteroid to be vaporized is at 9,6. The 200th asteroid to be vaporized is at 8,2. The 201st asteroid to be vaporized is at 10,9. The 299th and final asteroid to be vaporized is at 11,1. The Elves are placing bets on which will be the 200th asteroid to be vaporized. Win the bet by determining which asteroid that will be; what do you get if you multiply its X coordinate by 100 and then add its Y coordinate? (For example, 8,2 becomes 802.) Your puzzle answer was 2628. """ pass def vector_angle(delta): return 1 - arctan2(delta[0], delta[1]) / pi def vec_length(v): return v[0]*v[0] + v[1]*v[1] def order_vectors(grid): by_angle = defaultdict(list) for vec in grid: by_angle[vector_angle(vec)].append(vec) for vec_list in by_angle: by_angle[vec_list].sort(key=vec_length) return by_angle def count_directions(deltas: List): return len(set([vector_angle(d) for d in deltas])) def find_deltas(x, asteroid_map): return [(k[0] - x[0], k[1] - x[1]) for k in asteroid_map if k != x] def build_map(map_str): map_dict = {} for y, line in enumerate(map_str.split('\n')): for x, c in enumerate(line): if c == '#': map_dict[(x, y)] = 1 return map_dict def eval_map(asteroid_map): map_with_numbers = {k: count_directions(find_deltas(k, asteroid_map)) for k in asteroid_map} max_loc = max(map_with_numbers.keys(), key=(lambda k: map_with_numbers[k])) return map_with_numbers, max_loc def test_vector_angles(): # assert [(vector_angle(v),v) for v in [(sin(2*pi*n/128),-cos(2*pi*n/128),) for n in range(129)]] == [] assert vector_angle((0, -1)) == 0.0 assert vector_angle((1, -1)) == 0.25 assert vector_angle((1, 0)) == 0.5 assert vector_angle((1, 1)) == 0.75 assert vector_angle((0, 1)) == 1.0 assert vector_angle((-1, 1)) == 1.25 assert vector_angle((-1, 0)) == 1.5 assert vector_angle((-1, -1)) == 1.75 def test_order_vectors(): test_grid = [(-1, 1), (0, 1), (1, 1), (2, 1), (-1, 0), (1, 0), (2, 0), (-1, -1), (0, -1), (1, -1), (2, -1)] ordered_grid = dict(order_vectors(test_grid)) assert ordered_grid[0] == [(0, 1)] assert ordered_grid[0.25] == [(1, 1)] assert ordered_grid[0.5] == [(1, 0), (2, 0)] assert ordered_grid[0.75] == [(1, -1)] assert ordered_grid[1] == [(0, -1)] assert ordered_grid[1.25] == [(-1, -1)] def test_count_directions(): assert count_directions([(0, 1), (0, 2)]) == 1 assert count_directions([(0, 1), (0, -2)]) == 2 assert count_directions([(-1, 1), (0, 1), (1, 1), (-1, 0), (0, 0), (1, 0), (-1, -1), (0, -1), (1, -1)]) == 8 def test_find_deltas(): asteroid_map = {(0, 0), (1, 0), (0, 1), (1, 1), } assert len(find_deltas((0, 0), asteroid_map)) == 3 assert count_directions(find_deltas((0, 0), asteroid_map)) == 3 def test_build_map(): map_str = '.#..#\n.....\n#####\n....#\n...##' map_dict = {(0, 2): 1, (1, 0): 1, (1, 2): 1, (2, 2): 1, (3, 2): 1, (3, 4): 1, (4, 0): 1, (4, 2): 1, (4, 3): 1, (4, 4): 1} assert build_map(map_str) == map_dict def test_eval_map(): map_str = '.#..#\n.....\n#####\n....#\n...##' map_with_numbers = {(0, 2): 6, (1, 0): 7, (1, 2): 7, (2, 2): 7, (3, 2): 7, (3, 4): 8, (4, 0): 7, (4, 2): 5, (4, 3): 7, (4, 4): 7} assert eval_map(build_map(map_str)) == (map_with_numbers, (3, 4)) def test_large_sample(): with open('day_10_input_sample.txt') as fp: map_str = fp.read() asteroid_map = eval_map(build_map(map_str)) assert asteroid_map[1] == (11, 13) assert asteroid_map[0][11, 13] == 210 ordered_list = order_vectors(find_deltas((11, 13), asteroid_map[0])) bet_angle = sorted(ordered_list)[199] # assert bet_angle == 0 bet_delta = ordered_list[bet_angle][0] # assert bet_delta == (0, -1) assert (bet_delta[0] + 11, bet_delta[1] + 13) == (8, 2) def test_submission(): with open('day_10_input.txt') as fp: map_str = fp.read() asteroid_map = eval_map(build_map(map_str)) assert asteroid_map[1] == (28, 29) assert asteroid_map[0][28, 29] == 340 ordered_list = order_vectors(find_deltas((28, 29), asteroid_map[0])) bet_angle = sorted(ordered_list)[199] # assert bet_angle == 0 bet_delta = ordered_list[bet_angle][0] # assert bet_delta == (0, -1) assert (bet_delta[0] + 28, bet_delta[1] + 29) == (26, 28)
febffbadb732ad0709cdba7239a369cb03565e71
jvano74/advent_of_code
/2018/day_15_test.py
23,610
4.09375
4
from typing import NamedTuple from queue import PriorityQueue class Puzzle: """ --- Day 15: Beverage Bandits --- Having perfected their hot chocolate, the Elves have a new problem: the Goblins that live in these caves will do anything to steal it. Looks like they're here for a fight. You scan the area, generating a map of the walls (#), open cavern (.), and starting position of every Goblin (G) and Elf (E) (your puzzle input). Combat proceeds in rounds; in each round, each unit that is still alive takes a turn, resolving all of its actions before the next unit's turn begins. On each unit's turn, it tries to move into range of an enemy (if it isn't already) and then attack (if it is in range). All units are very disciplined and always follow very strict combat rules. Units never move or attack diagonally, as doing so would be dishonorable. When multiple choices are equally valid, ties are broken in reading order: top-to-bottom, then left-to-right. For instance, the order in which units take their turns within a round is the reading order of their starting positions in that round, regardless of the type of unit or whether other units have moved after the round started. For example: would take their These units: turns in this order: ####### ####### #.G.E.# #.1.2.# #E.G.E# #3.4.5# #.G.E.# #.6.7.# ####### ####### Each unit begins its turn by identifying all possible targets (enemy units). If no targets remain, combat ends. Then, the unit identifies all of the open squares (.) that are in range of each target; these are the squares which are adjacent (immediately up, down, left, or right) to any target and which aren't already occupied by a wall or another unit. Alternatively, the unit might already be in range of a target. If the unit is not already in range of a target, and there are no open squares which are in range of a target, the unit ends its turn. If the unit is already in range of a target, it does not move, but continues its turn with an attack. Otherwise, since it is not in range of a target, it moves. To move, the unit first considers the squares that are in range and determines which of those squares it could reach in the fewest steps. A step is a single movement to any adjacent (immediately up, down, left, or right) open (.) square. Units cannot move into walls or other units. The unit does this while considering the current positions of units and does not do any prediction about where units will be later. If the unit cannot reach (find an open path to) any of the squares that are in range, it ends its turn. If multiple squares are in range and tied for being reachable in the fewest steps, the square which is first in reading order is chosen. For example: Targets: In range: Reachable: Nearest: Chosen: ####### ####### ####### ####### ####### #E..G.# #E.?G?# #E.@G.# #E.!G.# #E.+G.# #...#.# --> #.?.#?# --> #.@.#.# --> #.!.#.# --> #...#.# #.G.#G# #?G?#G# #@G@#G# #!G.#G# #.G.#G# ####### ####### ####### ####### ####### In the above scenario, the Elf has three targets (the three Goblins): Each of the Goblins has open, adjacent squares which are in range (marked with a ? on the map). Of those squares, four are reachable (marked @); the other two (on the right) would require moving through a wall or unit to reach. Three of these reachable squares are nearest, requiring the fewest steps (only 2) to reach (marked !). Of those, the square which is first in reading order is chosen (+). The unit then takes a single step toward the chosen square along the shortest path to that square. If multiple steps would put the unit equally closer to its destination, the unit chooses the step which is first in reading order. (This requires knowing when there is more than one shortest path so that you can consider the first step of each such path.) For example: In range: Nearest: Chosen: Distance: Step: ####### ####### ####### ####### ####### #.E...# #.E...# #.E...# #4E212# #..E..# #...?.# --> #...!.# --> #...+.# --> #32101# --> #.....# #..?G?# #..!G.# #...G.# #432G2# #...G.# ####### ####### ####### ####### ####### The Elf sees three squares in range of a target (?), two of which are nearest (!), and so the first in reading order is chosen (+). Under "Distance", each open square is marked with its distance from the destination square; the two squares to which the Elf could move on this turn (down and to the right) are both equally good moves and would leave the Elf 2 steps from being in range of the Goblin. Because the step which is first in reading order is chosen, the Elf moves right one square. Here's a larger example of movement: Initially: ######### #G..G..G# #.......# #.......# #G..E..G# #.......# #.......# #G..G..G# ######### After 1 round: ######### #.G...G.# #...G...# #...E..G# #.G.....# #.......# #G..G..G# #.......# ######### After 2 rounds: ######### #..G.G..# #...G...# #.G.E.G.# #.......# #G..G..G# #.......# #.......# ######### After 3 rounds: ######### #.......# #..GGG..# #..GEG..# #G..G...# #......G# #.......# #.......# ######### Once the Goblins and Elf reach the positions above, they all are either in range of a target or cannot find any square in range of a target, and so none of the units can move until a unit dies. After moving (or if the unit began its turn in range of a target), the unit attacks. To attack, the unit first determines all of the targets that are in range of it by being immediately adjacent to it. If there are no such targets, the unit ends its turn. Otherwise, the adjacent target with the fewest hit points is selected; in a tie, the adjacent target with the fewest hit points which is first in reading order is selected. The unit deals damage equal to its attack power to the selected target, reducing its hit points by that amount. If this reduces its hit points to 0 or fewer, the selected target dies: its square becomes . and it takes no further turns. Each unit, either Goblin or Elf, has 3 attack power and starts with 200 hit points. For example, suppose the only Elf is about to attack: HP: HP: G.... 9 G.... 9 ..G.. 4 ..G.. 4 ..EG. 2 --> ..E.. ..G.. 2 ..G.. 2 ...G. 1 ...G. 1 The "HP" column shows the hit points of the Goblin to the left in the corresponding row. The Elf is in range of three targets: the Goblin above it (with 4 hit points), the Goblin to its right (with 2 hit points), and the Goblin below it (also with 2 hit points). Because three targets are in range, the ones with the lowest hit points are selected: the two Goblins with 2 hit points each (one to the right of the Elf and one below the Elf). Of those, the Goblin first in reading order (the one to the right of the Elf) is selected. The selected Goblin's hit points (2) are reduced by the Elf's attack power (3), reducing its hit points to -1, killing it. After attacking, the unit's turn ends. Regardless of how the unit's turn ends, the next unit in the round takes its turn. If all units have taken turns in this round, the round ends, and a new round begins. The Elves look quite outnumbered. You need to determine the outcome of the battle: the number of full rounds that were completed (not counting the round in which combat ends) multiplied by the sum of the hit points of all remaining units at the moment combat ends. (Combat only ends when a unit finds no targets during its turn.) Below is an entire sample combat. Next to each map, each row's units' hit points are listed from left to right. Initially: ####### #.G...# G(200) #...EG# E(200), G(200) #.#.#G# G(200) #..G#E# G(200), E(200) #.....# ####### After 1 round: ####### #..G..# G(200) #...EG# E(197), G(197) #.#G#G# G(200), G(197) #...#E# E(197) #.....# ####### After 2 rounds: ####### #...G.# G(200) #..GEG# G(200), E(188), G(194) #.#.#G# G(194) #...#E# E(194) #.....# ####### Combat ensues; eventually, the top Elf dies: After 23 rounds: ####### #...G.# G(200) #..G.G# G(200), G(131) #.#.#G# G(131) #...#E# E(131) #.....# ####### After 24 rounds: ####### #..G..# G(200) #...G.# G(131) #.#G#G# G(200), G(128) #...#E# E(128) #.....# ####### After 25 rounds: ####### #.G...# G(200) #..G..# G(131) #.#.#G# G(125) #..G#E# G(200), E(125) #.....# ####### After 26 rounds: ####### #G....# G(200) #.G...# G(131) #.#.#G# G(122) #...#E# E(122) #..G..# G(200) ####### After 27 rounds: ####### #G....# G(200) #.G...# G(131) #.#.#G# G(119) #...#E# E(119) #...G.# G(200) ####### After 28 rounds: ####### #G....# G(200) #.G...# G(131) #.#.#G# G(116) #...#E# E(113) #....G# G(200) ####### More combat ensues; eventually, the bottom Elf dies: After 47 rounds: ####### #G....# G(200) #.G...# G(131) #.#.#G# G(59) #...#.# #....G# G(200) ####### Before the 48th round can finish, the top-left Goblin finds that there are no targets remaining, and so combat ends. So, the number of full rounds that were completed is 47, and the sum of the hit points of all remaining units is 200+131+59+200 = 590. From these, the outcome of the battle is 47 * 590 = 27730. Here are a few example summarized combats: ####### ####### #G..#E# #...#E# E(200) #E#E.E# #E#...# E(197) #G.##.# --> #.E##.# E(185) #...#E# #E..#E# E(200), E(200) #...E.# #.....# ####### ####### Combat ends after 37 full rounds Elves win with 982 total hit points left Outcome: 37 * 982 = 36334 ####### ####### #E..EG# #.E.E.# E(164), E(197) #.#G.E# #.#E..# E(200) #E.##E# --> #E.##.# E(98) #G..#.# #.E.#.# E(200) #..E#.# #...#.# ####### ####### Combat ends after 46 full rounds Elves win with 859 total hit points left Outcome: 46 * 859 = 39514 ####### ####### #E.G#.# #G.G#.# G(200), G(98) #.#G..# #.#G..# G(200) #G.#.G# --> #..#..# #G..#.# #...#G# G(95) #...E.# #...G.# G(200) ####### ####### Combat ends after 35 full rounds Goblins win with 793 total hit points left Outcome: 35 * 793 = 27755 ####### ####### #.E...# #.....# #.#..G# #.#G..# G(200) #.###.# --> #.###.# #E#G#G# #.#.#.# #...#G# #G.G#G# G(98), G(38), G(200) ####### ####### Combat ends after 54 full rounds Goblins win with 536 total hit points left Outcome: 54 * 536 = 28944 ######### ######### #G......# #.G.....# G(137) #.E.#...# #G.G#...# G(200), G(200) #..##..G# #.G##...# G(200) #...##..# --> #...##..# #...#...# #.G.#...# G(200) #.G...G.# #.......# #.....G.# #.......# ######### ######### Combat ends after 20 full rounds Goblins win with 937 total hit points left Outcome: 20 * 937 = 18740 What is the outcome of the combat described in your puzzle input? --- Part Two --- According to your calculations, the Elves are going to lose badly. Surely, you won't mess up the timeline too much if you give them just a little advanced technology, right? You need to make sure the Elves not only win, but also suffer no losses: even the death of a single Elf is unacceptable. However, you can't go too far: larger changes will be more likely to permanently alter spacetime. So, you need to find the outcome of the battle in which the Elves have the lowest integer attack power (at least 4) that allows them to win without a single death. The Goblins always have an attack power of 3. In the first summarized example above, the lowest attack power the Elves need to win without losses is 15: ####### ####### #.G...# #..E..# E(158) #...EG# #...E.# E(14) #.#.#G# --> #.#.#.# #..G#E# #...#.# #.....# #.....# ####### ####### Combat ends after 29 full rounds Elves win with 172 total hit points left Outcome: 29 * 172 = 4988 In the second example above, the Elves need only 4 attack power: ####### ####### #E..EG# #.E.E.# E(200), E(23) #.#G.E# #.#E..# E(200) #E.##E# --> #E.##E# E(125), E(200) #G..#.# #.E.#.# E(200) #..E#.# #...#.# ####### ####### Combat ends after 33 full rounds Elves win with 948 total hit points left Outcome: 33 * 948 = 31284 In the third example above, the Elves need 15 attack power: ####### ####### #E.G#.# #.E.#.# E(8) #.#G..# #.#E..# E(86) #G.#.G# --> #..#..# #G..#.# #...#.# #...E.# #.....# ####### ####### Combat ends after 37 full rounds Elves win with 94 total hit points left Outcome: 37 * 94 = 3478 In the fourth example above, the Elves need 12 attack power: ####### ####### #.E...# #...E.# E(14) #.#..G# #.#..E# E(152) #.###.# --> #.###.# #E#G#G# #.#.#.# #...#G# #...#.# ####### ####### Combat ends after 39 full rounds Elves win with 166 total hit points left Outcome: 39 * 166 = 6474 In the last example above, the lone Elf needs 34 attack power: ######### ######### #G......# #.......# #.E.#...# #.E.#...# E(38) #..##..G# #..##...# #...##..# --> #...##..# #...#...# #...#...# #.G...G.# #.......# #.....G.# #.......# ######### ######### Combat ends after 30 full rounds Elves win with 38 total hit points left Outcome: 30 * 38 = 1140 After increasing the Elves' attack power until it is just barely enough for them to win without any Elves dying, what is the outcome of the combat described in your puzzle input? """ pass with open('day_15_input.txt') as fp: INPUTS = [line.strip() for line in fp] class Pt(NamedTuple): x: int y: int def __add__(self, other): return Pt(self.x + other.x, self.y + other.y) def __lt__(self, other): """ Update ordering to use 'reading order' with y value 1st then x value """ if self.y < other.y: return True if self.y > other.y: return False if self.x < other.x: return True return False def test_pt(): assert Pt(5, 1) < Pt(3, 2) assert not Pt(5, 4) < Pt(3, 2) assert Pt(1, 2) < Pt(3, 2) class Unit(NamedTuple): hit_points: int attack_power: int @staticmethod def new(attack_power=3): return Unit(hit_points=200, attack_power=attack_power) def attacked_by(self, opponent): new_hp = self.hit_points - opponent.attack_power if new_hp <= 0: return None return Unit(hit_points=new_hp, attack_power=self.attack_power) class Board: def __init__(self, raw_board, super_powered_elfs=None): self.grid = set() self.elfs = {} self.super_powered_elfs = super_powered_elfs self.goblins = {} self.max_pt = Pt(0, 0) for y, raw_line in enumerate(raw_board): for x, c in enumerate(raw_line): pt = Pt(x, y) if self.max_pt < pt: self.max_pt = pt if c != '#': self.grid.add(pt) if c == 'E': if self.super_powered_elfs is None: self.elfs[pt] = Unit.new() else: self.elfs[pt] = Unit.new(super_powered_elfs) elif c == 'G': self.goblins[pt] = Unit.new() self.initial_elf_count = len(self.elfs) self.initial_goblin_count = len(self.goblins) def print_state(self): results = [] for y in range(self.max_pt.y + 1): line = [] stats = [] for x in range(self.max_pt.x + 1): pt = Pt(x, y) if pt not in self.grid: line.append('#') elif pt in self.elfs: line.append('E') stats.append(f'E({self.elfs[pt].hit_points})') elif pt in self.goblins: line.append('G') stats.append(f'G({self.goblins[pt].hit_points})') else: line.append('.') results.append(f"{''.join(line)} {', '.join(stats)}") print('\n'.join(results)) def neighbors(self, pt, obstacles=None): if obstacles is None: obstacles = set() results = [] for delta in [Pt(1, 0), Pt(-1, 0), Pt(0, 1), Pt(0, -1)]: new_pt = pt + delta if new_pt in self.grid and new_pt not in obstacles: results.append(pt + delta) return results def find_nearest_goal(self, pt, obstacles, goals): boundary = PriorityQueue() boundary.put((0, pt, None)) visited = {pt} max_distance = None possible_paths = set() while not boundary.empty(): distance, current_pt, first_step = boundary.get() if max_distance is not None and distance > max_distance: pass # too far elif current_pt in goals: # return distance, current_pt, first_step possible_paths.add((distance, current_pt, first_step)) max_distance = distance else: for potential in self.neighbors(current_pt, obstacles | visited): if first_step is None: boundary.put((distance + 1, potential, potential)) else: boundary.put((distance + 1, potential, first_step)) visited.add(potential) if len(possible_paths) > 0: sorted_goals = sorted(possible_paths) return sorted_goals[0] return -1, None, None def take_turn(self, pt, team, opposition): if pt not in team: # should not happen return False no_opponents = False if len(opposition) > 0 else True dist, target, first_step = self.find_nearest_goal(pt, set(team.keys()), set(opposition.keys())) if dist > 1: # move toward attack team[first_step] = team.pop(pt) pt = first_step dist -= 1 if dist == 1: # attack # could be multiple opponents in range to need to check target targets = [(opposition[pt + d].hit_points, pt + d) for d in [Pt(1, 0), Pt(-1, 0), Pt(0, 1), Pt(0, -1)] if pt + d in opposition] _, new_target = min(targets) opponent = opposition.pop(new_target) new_opponent = opponent.attacked_by(team[pt]) if new_opponent is not None: opposition[new_target] = new_opponent return no_opponents def run(self, print_round=False): rounds = 0 no_opponents = False if print_round: print() print(f'Initially:') self.print_state() while len(self.elfs) > 0 and len(self.goblins) > 0: if self.super_powered_elfs is not None and self.initial_elf_count > len(self.elfs): return -1, 0 units = [] for pt in self.elfs: units.append((pt, 'e')) for pt in self.goblins: units.append((pt, 'g')) for pt, unit_type in sorted(units): if unit_type == 'e' and pt in self.elfs: no_opponents = self.take_turn(pt, self.elfs, self.goblins) elif unit_type == 'g' and pt in self.goblins: no_opponents = self.take_turn(pt, self.goblins, self.elfs) if no_opponents: break if no_opponents: break rounds += 1 if print_round: print() print(f'After round{"s" if rounds > 0 else ""} {rounds}:') self.print_state() survivors = list(self.goblins.values()) survivors.extend(list(self.elfs.values())) return rounds, sum([s.hit_points for s in survivors]) SAMPLE_0 = ['#######', '#.G...#', '#...EG#', '#.#.#G#', '#..G#E#', '#.....#', '#######'] RESULT_0 = 47, 590 SAMPLE_1 = ['#######', '#G..#E#', '#E#E.E#', '#G.##.#', '#...#E#', '#...E.#', '#######'] RESULT_1 = 37, 982 SAMPLE_2 = ['#######', '#E..EG#', '#.#G.E#', '#E.##E#', '#G..#.#', '#..E#.#', '#######'] RESULT_2 = 46, 859 SAMPLE_3 = ['#######', '#E.G#.#', '#.#G..#', '#G.#.G#', '#G..#.#', '#...E.#', '#######'] RESULT_3 = 35, 793 SAMPLE_4 = ['#######', '#.E...#', '#.#..G#', '#.###.#', '#E#G#G#', '#...#G#', '#######'] RESULT_4 = 54, 536 SAMPLE_5 = ['#########', '#G......#', '#.E.#...#', '#..##..G#', '#...##..#', '#...#...#', '#.G...G.#', '#.....G.#', '#########'] RESULT_5 = 20, 937 def test_board(): board = Board(SAMPLE_0) observed = board.run(print_round=False) assert observed == RESULT_0 board = Board(SAMPLE_1) assert board.run() == RESULT_1 board = Board(SAMPLE_2) assert board.run() == RESULT_2 board = Board(SAMPLE_3) assert board.run() == RESULT_3 board = Board(SAMPLE_4) assert board.run() == RESULT_4 board = Board(SAMPLE_5) assert board.run() == RESULT_5 def test_puzzle_pt1_board(): board = Board(INPUTS) assert board.run() == (71, 2656) assert 71 * 2656 == 188576 def test_puzzle_pt2_board(): for super_power in range(4, 100): board = Board(INPUTS, super_powered_elfs=super_power) result = board.run() if result[0] != -1: break assert super_power == 15 assert result == (44, 1298) assert 44 * 1298 == 57112
df3bb88e5a4f240e8841920633f762bcb39f9212
jvano74/advent_of_code
/2022/day_07_test.py
9,057
4.0625
4
from typing import NamedTuple class Puzzle: """ --- Day 7: No Space Left On Device --- You can hear birds chirping and raindrops hitting leaves as the expedition proceeds. Occasionally, you can even hear much louder sounds in the distance; how big do the animals get out here, anyway? The device the Elves gave you has problems with more than just its communication system. You try to run a system update: $ system-update --please --pretty-please-with-sugar-on-top Error: No space left on device Perhaps you can delete some files to make space for the update? You browse around the filesystem to assess the situation and save the resulting terminal output (your puzzle input). For example: $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k The filesystem consists of a tree of files (plain data) and directories (which can contain other directories or files). The outermost directory is called /. You can navigate around the filesystem, moving into or out of directories and listing the contents of the directory you're currently in. Within the terminal output, lines that begin with $ are commands you executed, very much like some modern computers: cd means change directory. This changes which directory is the current directory, but the specific result depends on the argument: cd x moves in one level: it looks in the current directory for the directory named x and makes it the current directory. cd .. moves out one level: it finds the directory that contains the current directory, then makes that directory the current directory. cd / switches the current directory to the outermost directory, /. ls means list. It prints out all of the files and directories immediately contained by the current directory: 123 abc means that the current directory contains a file named abc with size 123. dir xyz means that the current directory contains a directory named xyz. Given the commands and output in the example above, you can determine that the filesystem looks visually like this: - / (dir) - a (dir) - e (dir) - i (file, size=584) - f (file, size=29116) - g (file, size=2557) - h.lst (file, size=62596) - b.txt (file, size=14848514) - c.dat (file, size=8504156) - d (dir) - j (file, size=4060174) - d.log (file, size=8033020) - d.ext (file, size=5626152) - k (file, size=7214296) Here, there are four directories: / (the outermost directory), a and d (which are in /), and e (which is in a). These directories also contain files of various sizes. Since the disk is full, your first step should probably be to find directories that are good candidates for deletion. To do this, you need to determine the total size of each directory. The total size of a directory is the sum of the sizes of the files it contains, directly or indirectly. (Directories themselves do not count as having any intrinsic size.) The total sizes of the directories above can be found as follows: The total size of directory e is 584 because it contains a single file i of size 584 and no other directories. The directory a has total size 94853 because it contains files f (size 29116), g (size 2557), and h.lst (size 62596), plus file i indirectly (a contains e which contains i). Directory d has total size 24933642. As the outermost directory, / contains every file. Its total size is 48381165, the sum of the size of every file. To begin, find all of the directories with a total size of at most 100000, then calculate the sum of their total sizes. In the example above, these directories are a and e; the sum of their total sizes is 95437 (94853 + 584). (As in this example, this process can count files more than once!) Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories? --- Part Two --- Now, you're ready to choose a directory to delete. The total disk space available to the filesystem is 70000000. To run the update, you need unused space of at least 30000000. You need to find a directory you can delete that will free up enough space to run the update. In the example above, the total size of the outermost directory (and thus the total amount of used space) is 48381165; this means that the size of the unused space must currently be 21618835, which isn't quite the 30000000 required by the update. Therefore, the update still requires a directory with total size of at least 8381165 to be deleted before it can run. To achieve this, you have the following options: Delete directory e, which would increase unused space by 584. Delete directory a, which would increase unused space by 94853. Delete directory d, which would increase unused space by 24933642. Delete directory /, which would increase unused space by 48381165. Directories e and a are both too small; deleting them would not free up enough space. However, directories d and / are both big enough! Between these, choose the smallest: d, increasing unused space by 24933642. Find the smallest directory that, if deleted, would free up enough space on the filesystem to run the update. What is the total size of that directory? """ with open("day_07_input.txt") as fp: RAW_INPUT = fp.read() RAW_SAMPLE = """$ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k""" class File(NamedTuple): name: str size: int def get_size(self): return self.size class Folder: def __init__(self, name) -> None: self.name = name self.size = None self.ls = [] def get_size(self): if self.size is None: total = sum(f.get_size() for f in self.ls) self.size = total return self.size def test_folders(): file1 = File(name="a", size=123) file2 = File(name="b", size=321) file3 = File(name="c", size=111) folder1 = Folder(name="") folder2 = Folder(name="f1") folder3 = Folder(name="f2") folder1.ls = [file1, folder2, folder3] folder2.ls = [file2, file3] assert folder1.get_size() == 555 def parse_terminal_output(raw_output): root = Folder("/") folders = {"/": root} def get_folder(key, name): if key == "": key = "/" if key not in folders: new_folder = Folder(name) folders[key] = new_folder return folders[key] ls_mode = False cwd = [""] for hx, line in enumerate(raw_output.split("\n")): arg = line.strip().split(" ") if line == "$ cd /": cwd = [""] current_dir = root continue if arg[0] == "$": if ls_mode: current_dir.ls = ls ls_mode = False if arg[1] == "cd": if arg[2] == "..": cwd = cwd[:-1] else: cwd.append(arg[2]) current_dir = get_folder("/".join(cwd), arg[2]) elif arg[1] == "ls": ls_mode = True ls = [] elif arg[0] == "dir": fdir = cwd[:] fdir.append(arg[1]) dir = get_folder("/".join(fdir), arg[1]) ls.append(dir) else: size = int(arg[0]) ls.append(File(name=arg[1], size=size)) # Check if we had a final ls to add if ls_mode: current_dir.ls = ls ls_mode = False return {k: f.get_size() for k, f in folders.items()} def test_parse_terminal_output(): dir_list = parse_terminal_output(RAW_SAMPLE) sample_dir_list = {"/": 48381165, "/a": 94853, "/d": 24933642, "/a/e": 584} # 70_000_000 >= dir_list["/"] + 30_000_000 - min_delete min_delete = dir_list["/"] + 30_000_000 - 70_000_000 assert dir_list == sample_dir_list assert sum(s for s in dir_list.values() if s <= 100000) == 95437 assert min(s for s in dir_list.values() if s >= min_delete) == 24933642 dir_list = parse_terminal_output(RAW_INPUT) # 70_000_000 >= dir_list["/"] + 30_000_000 - min_delete min_delete = dir_list["/"] + 30_000_000 - 70_000_000 assert sum(s for k, s in dir_list.items() if s <= 100000) == 1206825 assert min(s for s in dir_list.values() if s >= min_delete) == 9608311
8b9635f49f3109aeae2c325d575c1f54a19fb712
jvano74/advent_of_code
/2015/day_09_test_alt.py
3,804
4.1875
4
from typing import List from collections import defaultdict from heapq import heappush, heappop class Puzzle: """ --- Day 9: All in a Single Night --- Every year, Santa manages to deliver all of his presents in a single night. This year, however, he has some new locations to visit; his elves have provided him the distances between every pair of locations. He can start and end at any two (different) locations he wants, but he must visit each location exactly once. What is the shortest distance he can travel to achieve this? For example, given the following distances: London to Dublin = 464 London to Belfast = 518 Dublin to Belfast = 141 The possible routes are therefore: Dublin -> London -> Belfast = 982 London -> Dublin -> Belfast = 605 London -> Belfast -> Dublin = 659 Dublin -> Belfast -> London = 659 Belfast -> Dublin -> London = 605 Belfast -> London -> Dublin = 982 The shortest of these is London -> Dublin -> Belfast = 605, and so the answer is 605 in this example. What is the distance of the shortest route? """ class City: def __init__(self): self.neighbors = defaultdict(int) class Map: def __init__(self, distances: List): self.cities = defaultdict(City) for line in distances: city1, _, city2, _, distance = line.split(" ") self.cities[city1].neighbors[city2] = int(distance) self.cities[city2].neighbors[city1] = int(distance) def shortest_distance(self) -> List: city_count = len(self.cities) frontier = [] for cityName in self.cities: heappush(frontier, (0, cityName, [cityName])) routes = [] while frontier: dist, city, path_hx = heappop(frontier) for nn in self.cities[city].neighbors: if nn not in path_hx: new_dist = dist + self.cities[city].neighbors[nn] new_hx = path_hx[:] new_hx.append(nn) if len(new_hx) == city_count: heappush(routes, (new_dist, new_hx)) heappush(frontier, (new_dist, nn, new_hx)) return heappop(routes) def longest_distance(self) -> List: city_count = len(self.cities) frontier = [] for cityName in self.cities: heappush(frontier, (0, cityName, [cityName])) routes = [] while frontier: dist, city, path_hx = heappop(frontier) for nn in self.cities[city].neighbors: if nn not in path_hx: new_dist = dist - self.cities[city].neighbors[nn] new_hx = path_hx[:] new_hx.append(nn) if len(new_hx) == city_count: heappush(routes, (new_dist, new_hx)) heappush(frontier, (new_dist, nn, new_hx)) return heappop(routes) with open("day_09_input.txt") as fp: SUBMISSION = fp.read() def test_map(): map = Map( ["London to Dublin = 464", "London to Belfast = 518", "Dublin to Belfast = 141"] ) assert set(map.cities.keys()) == set(["London", "Dublin", "Belfast"]) assert map.shortest_distance()[0] == 605 assert map.longest_distance()[0] == -982 def test_submission(): my_map = Map([dist.strip() for dist in SUBMISSION.split("\n")]) assert set(my_map.cities.keys()) == set( [ "AlphaCentauri", "Arbre", "Faerun", "Norrath", "Snowdin", "Straylight", "Tambi", "Tristram", ] ) assert my_map.shortest_distance()[0] == 251 assert my_map.longest_distance()[0] == -898
aaeba59e40e36ad997bf7f236122964186d6a022
tohkev/Data-Analytics
/Analyzing Data in Python/PyBank/main.py
1,898
3.703125
4
import os import csv path = os.path.join("Resources", "budget_data.csv") # Tracking various parameters used in calculations total_months = 0 total_profit = 0 change_total = 0 net_change_list = [] month_of_change_list = [] # reads csv file with financial data with open(path, "r") as datafile: reader = csv.reader(datafile, delimiter=",") header = next(reader) first_row = next(reader) prev_num = int(first_row[1]) for row in reader: # Getting total number of months total_months += 1 # Getting total profit from the period total_profit += int(row[1]) # creating the list of monthly changes and the months they occur in net_change = int(row[1]) - int(prev_num) net_change_list.append(net_change) month_of_change_list.append(row[0]) prev_num = row[1] # Getting average change between months for num in net_change_list: change_total += num average = change_total/total_months # Locating index number of highest increase and decrease max_index = net_change_list.index(max(net_change_list)) min_index = net_change_list.index(min(net_change_list)) # creates a aggregate list with month and change agg_change_list = list(zip(month_of_change_list, net_change_list)) max_increase = agg_change_list[max_index] max_decrease = agg_change_list[min_index] output = (f""" Financial Analysis ---------------------------- Total Months: {total_months} Total: ${total_profit} Average Change: ${average} Greatest Increase in Profits: {max_increase[0]} (${max_increase[1]}) Greatest Decrease in Profits: {max_decrease[0]} (${max_decrease[1]})""") print(output) # exporting results into a text file export_path = os.path.join("analysis", "analysis.txt") with open(export_path, 'w') as report_file: report_file.write(output)
c6ace3025009418d4f7558034c4d9723055c8078
DaishanHuang/Canopy
/MITx6001/Lec4Problems.py
700
3.671875
4
def clip(lo, x, hi): ''' Takes in three numbers and returns a value based on the value of x. Returns: - lo, when x < lo - hi, when x > hi - x, otherwise ''' s = max(lo, x) return(min(s, hi)) def clip(lo, x, hi): return min(max(x, lo), hi) def square(x): return x*x def fourthPower(x): return square(x) * square(x) def odd(x): return x % 2 != 0 def isVowel(char): v = str(char.lower()) if v == 'a' or v == 'e' or v == 'i' or v == 'o' or v == 'u': return True else: return False def isVowel(char): v = str(char.lower()) if v in ('aeiou'): return True else: return False
eeb051007e9b7363d36b3819e7e44a0e4aec3471
DaishanHuang/Canopy
/MITx6001/L3Problem5c.py
104
3.890625
4
end = int(raw_input('Enter an integer ')) y = 0 for x in range(end + 1): y = x + y print y
6c8cdb28620babdc883269c0a6a56a8d1b172d57
RoshaniPatel10994/ITCS1140---Python-
/Quiz's/quiz 4/quiz 4 before program/product in Main() function.py
781
3.875
4
# 3/9/2020 # Product # Multiply 2 number together using python fuctions # Define Main module def main(): # Declare variables x = 0.0 y = 0.0 Answer = 0.0 # Call GetInput function X, Y = GetInput() # Call CalProduct function Answer = CalcProduct(X, Y) # Calculate DisplayProduct function DisplayProduct(Answer) # Define GetInput function def GetInput(): X = float(input("Enter 1st number: ")) Y = float(input("Enter 2st number: ")) return X, Y # Define CalProduct function def CalcProduct(inX, inY): Answer = inX * inY return Answer # Define DisplayProduct function def DisplayProduct(inAnswer): print("Product is: ", inAnswer) return # Call main main()
a69ae0606cc01d496905c9111bb1b5461db4b828
RoshaniPatel10994/ITCS1140---Python-
/Array/Lab.py
1,502
3.90625
4
# Patel Roshani # InClassLabLists # Def Main Module def main(): # Declare Variables NumHomes = 0 AvgPrice = 0.0 NumAbove = 0 NumBelow = 0 Prices = [0.0] # Call GetInput NumHomes, Prices = GetInput() #Call CalAvg AvgPrice = CalcAvg(NumHomes, Prices) # Call CountAboveBelow NumAbove, NumBelow = CountAboveBelow(NumHomes, AvgPrice, Prices) # Call Display output DisplayOutput(AvgPrice, NumAbove, NumBelow) # Define GetInput def GetInput(): NumHomes = int(input("Enter Number of homes sold:")) Prices =[0.0]* NumHomes for Index in range(0, NumHomes): Prices[Index] = float(input("Enter Prices: ")) return NumHomes, Prices # Define CalAvg def CalcAvg(NumHomes, Prices): Total = 0.0 for Index in range(0, NumHomes): Total = Total + Prices[Index] AvgPrice = Total/NumHomes return AvgPrice # Define CountAboveBelow def CountAboveBelow(NumHomes, AvgPrice, Prices): NumAbove = 0 NumBelow = 0 for Index in range(0, NumHomes): if Prices[Index] < AvgPrice: NumBelow = NumBelow + 1 elif Prices[Index] > AvgPrice: NumAbove = NumAbove + 1 return NumAbove, NumBelow # Define Display Output def DisplayOutput(AvgPrice, NumAbove, NumBelow): print("Average: $ ", format(AvgPrice, '.2f')) print("Number above : ", NumAbove) print("Number Below: ", NumBelow) # Call main main()
1147eb7a1190460f976c5a5134c66f97410a836d
RoshaniPatel10994/ITCS1140---Python-
/Quiz's/quiz 4/Quiz 4 ans.py
825
3.828125
4
def main(): #define variables numorders = int() amt = int() coupon = str() #getinputs numorders = int(input("Enter number of orders: ")) amt = int(input("Enter total spent: ")) #call function CalcCoupon(numorders, amt) #define function def CalcCoupon(numorders, amt): #logic determine order if numorders >= 6: #logic determine coupon if amt >=10 and amt <=20: coupon = "Customer Coupon: 10% off coupon" elif amt >20 and amt <=30: coupon = "Customer Coupon: 20% off coupon" elif amt>30: coupon = "Customer Coupon: 30% off coupon" else: coupon = "Customer Coupon: no coupon" else: coupon = "Customer Coupon: no coupon" #print output print(coupon) #define main main()
7b85a1c7233bec1ac0f6a7df5eba4eb82aa46d96
RoshaniPatel10994/ITCS1140---Python-
/Array/Practice/rainfall right ans.py
332
3.84375
4
days = int() def Rainfall(days): rain_log = float() rain_log = [] dayss=int(days) for I in range (0,dayss): rain_log.append(float(input())) return(rain_log) def main(): days = int() days = int(input()) myRain = [0.0] * days myRain = Rainfall(days) print(myRain) main()
db59ee60efb684c780262407c276487760cca73c
RoshaniPatel10994/ITCS1140---Python-
/Array/Practice/Beginin array in lecture.py
1,815
4.5
4
# Create a program that will allow the user to keep track of snowfall over the course 5 months. # The program will ask what the snowfall was for each week of each month ans produce a total number # of inches and average. It will also print out the snowfall values and list the highest amount of snow and the lowest amount of snow. # Declare variables snowfall = [0,0,0,0,0] index = int() one_month = float() total_inches = float() ave_inches = float() highest_inches = float() lowest_inches = float() ## #For loop ##for index in range(0, 5): ## #ask use for months snowfall ## one_month = float(input("Enter months of snowfall: ")) ## snowfall[index] = one_month ##print() snowfall = [10, 12, 14, 16, 18] for index in range(0, len(snowfall)): one_month = snowfall[index] print("Monthly snow fall : ", one_month) print() # Determin the total inches of snow fall for index in range(0, len(snowfall)): one_month = snowfall[index] total_inches = total_inches + one_month print(" total snowfall : ", total_inches) # average snowfall ave_inches = total_inches / (index + 1) print("Average snowfall: - " , ave_inches ) # Determine heighest value highest_inches = snowfall[0] for index in range(0, len(snowfall)): one_month = snowfall[index] if one_month > highest_inches : highest_inches = one_month #endif print("highest snowfall: - " , highest_inches ) # Determine Lowest value lowest_inches = snowfall[0] for index in range(0, len(snowfall)): one_month = snowfall[index] if one_month < lowest_inches : lowest_inches = one_month print("lowest snowfall: - " , lowest_inches )
78aa868973b7170d260593511b44ae410b9978be
RoshaniPatel10994/ITCS1140---Python-
/final exam/Final Exam.py
1,483
3.703125
4
#Define main def main(): #sales array from Professor SalesData=[2010.45,5500.00,1170.65, 550.25, 50.95,3650.45] #Print space print() #Call PrintSales sales = PrintSales(SalesData) print() #Find profit profit = DetermineProfits(SalesData) #Print space print() #Find lowest sale lowestsale = FindLowestSale(SalesData) print("Lowest Sales: $","{:,.2f}".format(lowestsale)) #Define PrintSales function def PrintSales(sales = []): #Print wording and star print("Sales by Store") print("**************************") #Loop to print sales data and format SalesData=sales for i in range(0,len(SalesData)): print("$", "{:,.2f}".format(SalesData[i])) #Define DetermineProfits function def DetermineProfits(sales2 = []): #Print word and star print("Store Profit Amounts") print("**************************") salesdata2=sales2 #Loop to print sale * 0.2 for i in range(0,len(salesdata2)): profit = salesdata2[i]*0.2 print("$", "{:,.2f}".format(profit)) #Define FindLowest Sale def FindLowestSale(sales3 = []): salesdata3=sales3 #Define lowest variable lowest = salesdata3[0] #Loop to compare lowest to next element and find lowest for i in range(0,len(salesdata3)): if lowest > salesdata3[i]: lowest = salesdata3[i] return lowest #Call main function main()
09104914632843b275485f1258c2fa6399ba7339
RoshaniPatel10994/ITCS1140---Python-
/Loop Repetition structure And Decison Structure/num of cookies.py
853
3.953125
4
answer = str() num_cookies = int() rate = float() discount = float() subtotal = float() total = float() while answer != 'quit': num_cookies = int(input("Enter the number of cookies: ")) if num_cookies <= 6: rate = 0.0 elif num_cookies <= 12: rate = 0.5 elif num_cookies <= 24: rate = 0.1 else: rate = 0.2 #determining the subtotal subtotal = num_cookies * 0.5 #determining the discount discount = subtotal * rate #determining the total total = subtotal - discount #print out subtotal, discount and total print("Subtotal: $", subtotal) print("Discount: $", discount) print("Total: $", total) #ask the user if they want to enter another batch answer = input("Enter 'quit' to end the program: ")
c3869c3a16815c7934e88768d75ee77a4bcc207d
RoshaniPatel10994/ITCS1140---Python-
/Quiz's/quiz 5/LookingForDatesPython.py
1,479
4.40625
4
#Looking For Dates Program #Written by: Betsy Jenaway #Date: July 31, 2012 #This program will load an array of names and an array of dates. It will then #ask the user for a name. The program will then look for the user in the list. #If the name is found in the list the user will get a message telling them #the name was found and the person's birthdate. Otherwise they will get a #message telling them the name #was not found and to try again. NOTE: this #program differs from the Raptor program in that it continually asks the user #for a name until one is found in the list. #Declare Variables #Loading the array with names Friends = ["Matt", "Susan", "Jim", "Bob"] Dates = ["12/2/99", "10/15/95", "3/7/95", "6/24/93"] SearchItem = "nothing" FoundDate = "nothing" FoundIndex = 0 Index = 0 Flag = False #Look for the name and tell the user if the program found it #Keep asking the user for a name until one is found. while Flag == False: #Ask the user for the name to search for SearchItem = input("What is the name you are looking for? ") if SearchItem in Friends: #Find out what the index is for the Found Name FoundIndex = Friends.index(SearchItem) FoundDate = Dates[FoundIndex] Flag = True print("We found your name!") print(SearchItem, "'s Birthday is: ", FoundDate) else: print("Sorry we did not find your name. Please try again.") Flag = False
c4a91a468b3c96852d1365870230b15433f8007c
RoshaniPatel10994/ITCS1140---Python-
/Quiz's/quiz 2/chips.py
989
4.15625
4
# Roshani Patel # 2/10/20 # Chips # This program Calculate the cost of an order of chips. # Display program that will ask user how many bags of chips they want to buy. #In addition ask the user what size of bag. #If the bag is 8 oz the cost is 1.29 dollar if the bag is 16 oz then the cost is 3.59 dollars. #If bag is 32 oz then cost is $5.50. calculate the total cost of the order including tax at 6%. ## Declare Variable Size = 0 Qty = 0 Price = 0.0 Cost = 0.0 # Display Menu print("1 - 8 oz\t$1.29") print("2 - 16 oz\t$3.59") print("3 - 32 0z\t$5.50") # Bet Input Size = int(input("Enter size: ")) if Size == 1 or Size == 2 or Size == 3: Qty = int(input("Enter quantity: ")) # Calculate the COst if Size == 1: Price = 1.29 elif Size == 2: Price = 3.59 elif Size == 3: Price = 5.50 else: print("Enter 1, 2, or 3") Cost = Price * Qty * 1.06 # Display Cost print("Cost = $",format(Cost, '.2f'))
dbcbd1dfe444464583ef6d6949c17588031b0cdc
Cluedrew/little-scribe
/scribbler/primitive.py
722
3.828125
4
#!/usr/bin/env python3 """Translating primitives into values. Primitives are not defined, but have an intrinsic value and type based on the tokens used.""" from base_types import ( IntegerType, ) from scope import ( Definition, ) from tokenization import ( IntegerToken, ) def primitive_integer(sentence): value = int(sentence[0].text) return Definition(sentence, value, IntegerType()) def primitive_lookup(sentence): if not sentence.is_primitive(): raise Exception('May not translate non-primitive.') elif isinstance(sentence[0], IntegerToken): return primitive_integer(sentence) else: raise Exception('Unknown token type. Token: ' + repr(token))
0e27d9b7fdb232557d90760be79213e7fff55b9d
tijohask/Covering_Arrays
/Full_Hill_Climbing.py
4,416
3.5
4
import sys import numpy import random import itertools import time #Found on stack overflow def choose(n, k): """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 #Mathematically proven that the size of the covering array will be no larger #than what is returned by this function def find_size(t, k, v): top = numpy.log(choose(k, t)) + (t * numpy.log(v)) bottom = numpy.log( (v**t) / (v**t - 1) ) return int( top / bottom ) + 1 #Code returns a 2D array, giving every row gotten by counting. #uses the input array as a base for its indices #Example: 2,2,3 #Returns: """ [0 0 0] [0 0 1] [0 0 2] [0 1 0] [0 1 1] [0 1 2] [1 0 0] [1 0 1] [1 0 2] [1 1 0] [1 1 1] [1 1 2] """ #General algorithm is to iteratively create all possible tuples up to the #maximum value of the input array, then remove the ones that don't fit our #established pattern. def create_full_array(input_array): give = [] for i in k_level: give.append(list(numpy.arange(i))) arr = [] for i in itertools.product(*give): arr.append(list(i)) return numpy.asarray(arr) #Get every combination, check to make sure the right number of unique #interactions are in there. #If there are enough in all, then success! #else, false. def check_interactions(test, k_level, num_inter): #get all existing combinations (interactions) from the data for p in itertools.combinations(numpy.arange(len(k_level)), num_inter): #Mul represents the number of unique iterations we expect for the exerpt mul = 1 for i in p: mul = mul*k_level[i] #check if every possible interaction is represented if(numpy.unique(test[:,p], axis=0).shape[0] < mul): #if not, return false return False #if we made it through the whole for loop, return true return True #Create an array with random, non-duplicate elements based on # The input array, and # The size given to the function def create_test_array(array, size): #Sorted for readability #random.sample to prevent duplicate elements #min to make sure that we don't run into a sample error ii = sorted(random.sample(range(array.shape[0]), size)) return array[ii,:] def setup(): #Take the system arguments #get the desired number of interactions num_inter = int(sys.argv[1]) #get the array k_level = sys.argv[2] k_level = k_level.split(',') k_level = numpy.asarray(sorted(list(map(int, k_level)))) print(k_level) print("Max Level: " + str(max(k_level))) print("Length of array: " + str(len(k_level))) return ( num_inter, k_level ) def create_cover(k_level, num_inter): full = create_full_array(k_level) cov_size = min( find_size( num_inter, len(k_level), max(k_level) ), full.shape[0] ) running = 100 test = [] working_test = numpy.arange(0) while(True): #Create a new test array test = create_test_array(full, cov_size) #check if all interactions are represented in this test array if(check_interactions(test, k_level, num_inter)): #save the working test #cov_size = cov_size - 1 working_test = test break else: #else, iterate down if we have a working test running = running - 1 if(running == 0): cov_size = min(mul_array(k_level), cov_size+1) running = 100 return working_test def mul_array(k_level): mul = 1 for i in range(len(k_level)): mul = mul*k_level[i] return mul #Recursively improve the CA by finding the rows that can be removed # and removing them. def hill_climbing(pre_hill, k_level, num_inter, step): for i in range(step, len(pre_hill)): if(check_interactions(numpy.delete(pre_hill, i, 0), k_level, num_inter)): #print("We have to go deeper..." + str(i)) return hill_climbing(numpy.delete(pre_hill, i, 0), k_level, num_inter, i) return pre_hill #END METHOD #BEGIN CODE start = time.process_time() num_inter, k_level = setup() #pre_hill = create_cover(k_level, num_inter) #print(pre_hill) #print(pre_hill.shape) post_hill = hill_climbing(create_full_array(k_level), k_level, num_inter, 0) print(post_hill) print(post_hill.shape) print((mul_array(k_level), len(k_level))) end = time.process_time() print("Elapsed Time: " + str(end - start))
8473efd6c1430d1b981a4f4e1c0ba742691c3572
DenzolRamen/Data-Structures-and-Algorithms
/Data Structures - Arrays/Reversing a string.py
1,309
3.875
4
# Reverse string 'Hi I am Denzel' # Solution 1 def reverse1(string): counter = len(string)-1 newStr = [] # Section for input checking.Start # Section for input checking.End while counter >= 0: newStr.append(string[counter]) counter -= 1 return ''.join(newStr) # Solution 2 def reverse2(string): counter = len(string)-1 newStr = '' # Section for input checking.Start # Section for input checking.End while counter >= 0: newStr+=string[counter] counter -= 1 return newStr # Solution 3 def reverse3(string): newStr = [] # Section for input checking.Start # Section for input checking.End for i in range(len(string)-1, -1, -1): #range(start, stop, step) newStr.append(string[i]) return ''.join(newStr) # Solution 4 - Pythonic Way 1 def reverse4(string): # Section for input checking.Start # Section for input checking.End return string[::-1] # Solution 5 - Pythonic Way 2 (Lambda Function) reverse5 = lambda string: string[::-1] # Test print('Solution 1') print(reverse1('Hi I am Denzel')) print('\nSolution 2') print(reverse2('Hi I am Denzel')) print('\nSolution 3') print(reverse3('Hi I am Denzel')) print('\nSolution 4') print(reverse4('Hi I am Denzel')) print('\nSolution 5') print(reverse5('Hi I am Denzel'))
dcd86820d01321bad0912528a99a19eab34a72c7
gptjddldi/oembed_backend
/utils.py
2,514
3.671875
4
import requests import urllib3 import urllib def get_json(url): """ example url = https://www.youtube.com/watch?v=dBD54EZIrZo url 을 받아서 도메인 추출 https://www.youtube.com/ json file 에서 해당 도메인 이름있는 컬럼 확인 해당 칼럼의 schema 에 url 이 매칭되는 지 확인 url_name 추출 `{url_name}+format=json&url=url` 으로 request 요청, 리턴 값 받아와서 전달함. """ json_url = "https://oembed.com/providers.json" data = requests.get(json_url).json() domain = extract_domain(url) for i in data: # print(i["provider_name"]) if i["provider_name"].lower() == domain: base = i["endpoints"][0]["url"] endpoint = base + "/?format=json&url=" + url return requests.get(endpoint).json() else: return {"error": "해당 url 은 oEmbed 에 등록된 Provider 가 아닙니다."} def extract_domain(url): return url.split('/')[2].split('.')[1] # 인스타 api :https://api.instagram.com/oembed/ # facebook 에서 oembed 를 사용하는 게 이제 안되나? # print(get_endpoint("https://www.instagram.com/p/BUawPlPF_Rx/")) print(requests.get("https://graph.facebook.com/v10.0/instagram_oembed?format=json&url=https://www.instagram.com/p/BUawPlPF_Rx/&access_token=1233543173748276|910614243ff1caaf7f37b4a7f5f1981d").json()) # token 910614243ff1caaf7f37b4a7f5f1981d # id 1233543173748276 # print(urllib3.parse_url("https://www.instagram.com/p/BUawPlPF_Rx/")) # print(urllib.parse.urlparse("https://www.instagram.com/p/BUawPlPF_Rx/").netloc) """ if "schemes" not in endpoint: continue for scheme in endpoint['schemes']: scheme = scheme.replace('?', '\?') pattern = scheme.replace('*', r'[^\*&]+?') if re.findall(pattern, url): base_url = endpoint['url'] if ".{format}" in base_url: base = base_url.replace("{format}", "json") endpoint = base + "?url=" + url else: endpoint = base_url + "?format=json&url=" + url print(endpoint) return requests.get(endpoint).json() # if domain_name in item["provider_name"].lower(): # domain name 이 정확히 일치하지 않는 경우도 있음 else: return {"error": "해당 url 은 oEmbed 에 등록된 Provider 가 아닙니다."} """
a95bdaa18d1b88eb8d178998f6af8f1066939c81
Lin-HsiaoJu/StanCode-Project
/stanCode Project/Wheather Master/weather_master.py
1,463
4.34375
4
""" File: weather_master.py Name: Jeffrey.Lin 2020/07 ----------------------- This program should implement a console program that asks weather data from user to compute the average, highest, lowest, cold days among the inputs. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ # This number controls when to stop the weather_master EXIT = -100 def main(): """ This program find and calculate the highest temperature, the lowest temperature, the average of daily temperature and the total days of cold day among the user inputs of everyday's temperature. """ print('stanCode "Weather Master 4.0"!') data = int(input('Next Temperature:(or '+str(EXIT)+' to quit)?')) if data == EXIT: print('No temperature were entered.') else: maximum = int(data) minimum = int(data) num = 1 sum = int(data) if maximum < 16: cold = 1 else: cold = 0 while True: data = int(input('Next Temperature:(or -100 to quit)?')) if data == EXIT: break else: sum += data num += 1 if data < 16: cold += 1 if data >= maximum: maximum = data if data <= minimum: minimum = data average = float(sum/num) print('Highest Temperature = ' + str(maximum)) print('Lowest Temperature = ' + str(minimum)) print('Average = ' + str(average)) print(str(cold) + ' cold day(s)') ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
92e0031f054add61799cd4bfcd81a835e705af0d
ruthvika-mohan/python_scripts-
/merge_yearly_data.py
1,002
4.125
4
# Import required modules # Glob module finds all the pathnames matching a specified pattern # Pandas required to do merge operation # chdir() method in Python used to change the current working directory to specified path. from os import chdir from glob import glob import pandas as pdlib # Move to the path that holds our CSV files csv_file_path = 'C:\folder_containing_csv_files' chdir(csv_file_path) # List all CSV files in the working directory list_of_files = [file for file in glob('*.csv')] print(list_of_files) """ Function: Produce a single CSV after combining all files """ def produceOneCSV(list_of_files,file_out): # Consolidate all CSV files into one object result_obj = pdlib.concat([pdlib.read_csv(file,header = 0,encoding = 'cp1252') for file in list_of_files],ignore_index = True) # Convert the above object into a csv file and export result_obj.to_csv(file_out) file_out = "MergedOutput.csv" produceOneCSV(list_of_files,file_out)
8b5be8bebb6295fa681c58b73248d7bb8f92fb0f
aleenaadnan15/Class-work
/revise.py
527
3.671875
4
class student(): def __init__(self, name,age,rollno,gender): self.name = name self.age = age self.rollno = rollno self.gender = gender def print_details(self): print('name:',self.name,'age:',self.age, 'rollno:',self.rollno, 'gender:',self.gender) student1 = student('Ailn', 22, 55,'female') student2 = student('jaisha' , 23, 56 , 'female') student3 = student('Kanwal', 22, 57 , 'female') student1.print_details() student2.print_details() student3.print_details()
eb43a005624bf51961a25f749f9b61ee8da7322b
christinapomykal/python-challenge
/PyBank/main.py
2,643
3.65625
4
# Import os and csv modules import os import csv csvpath = os.path.join("Resources", "budget_data.csv") # print(csvpath) # Lists to store data date = [] profitLoss = [] with open(csvpath) as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=",") # print(csvreader) # Read header row csv_header = next(csvreader) # print(f"CSV Header: {csv_header}") # Read each row of data after the header for row in csvreader: # Add date date.append(row[0]) # Add profitLoss profitLoss.append(row[1]) # Done reading csvreader. Data in lists. # for x in profitLoss: # print(x) netTotal = 0 biggestDelta = 0 biggestDeltaDate = "" biggestLoss = 0 biggestLossDate = "" deltaList = [] for i in range(len(profitLoss)): # print(str(i) + "--" + str(profitLoss[i]) + "-- On: " + date[i]) # is the same as: netTotal = netTotal + int(profitLoss[i]) netTotal += int(profitLoss[i]) # print(str(netTotal)) if i > 0: # conditional to start at index 1, calculate delta from month to month currentDelta = int(profitLoss[i]) - int(profitLoss[i - 1]) # adding values to deltaList deltaList.append(currentDelta) # print("Current Delta: " + str(currentDelta)) # compare the deltas and keep the larger for profits if currentDelta > biggestDelta: biggestDelta = currentDelta biggestDeltaDate = date[i] # compare the deltas and keep the smaller for losses if currentDelta < biggestLoss: biggestLoss = currentDelta biggestLossDate = date[i] avgChange = sum(deltaList) / len(deltaList) total_months = len(date) print("Financial Analysis") print("--------------------------------") print(f"Total Months: {total_months}") print(f"Grand Total: ${netTotal}") print(f"Average Change: $ {round(avgChange, 2)}") print(f"Greatest Increase in Profits: {biggestDeltaDate} (${biggestDelta})") print(f"Greatest Decrease in Profits: {biggestLossDate} (${biggestLoss})") output_textfile = ( "Financial Analysis\n" "--------------------------------\n" f"Total Months: {total_months}\n" f"Grand Total: ${netTotal}\n" f"Average Change: $ {round(avgChange, 2)}\n" f"Greatest Increase in Profits: {biggestDeltaDate} (${biggestDelta})\n" f"Greatest Decrease in Profits: {biggestLossDate} (${biggestLoss})\n" ) output_path = os.path.join("Analysis", "Analysis_PyBank.txt") with open(output_path, "w") as txtfile: txtfile.write(output_textfile)
835f465eaa293f4d862f99d8e786394d31e78845
PierrotAWB/ProjectEuler
/Misc. Programs/permutator.py
589
3.6875
4
import math, time # permutation generator t = time.time() def createPermutation(numberList, permutationIndex): digit = [] k = len(numberList) # numberList = [i for i in xrange(1, n + 1)] # n numbers, 1 to n total = permutationIndex - 1 # "nth permutation" for i in xrange(k - 1, -1, -1): digit.append(numberList[total // math.factorial(i)]) numberList.remove(digit[k - i - 1]) total = total % math.factorial(i) string = "" for i in xrange(0, len(digit)): string += str(digit[i]) + " " return string print "Finished in: " + str(time.time() - t) + " seconds"
553f6b3c6cc172192dd935e4322ab478d01c34fd
quano2/MATLAB-to-Python-Translator
/node.py
6,376
3.59375
4
from functions import * def printVar(var): ''' Will return the printed version of var if it is a Node, otherwise will return var. :param var: :return: ''' if isinstance(var,Node): var = var.print() return var class Node: type = "NODE" def __init__(self,m = ""): self.msg = m #used for error messages def print(self): return self.msg class Top(Node): def __init__(self,t,f): self.top = printVar(t) self.func = printVar(f) def print(self): return self.top + "\n" + self.func class Number(Node): type = "NUMBER" def __init__(self,n): self.num = n def print(self): return self.num class String(Node): type = "STRING" def __init__(self,s): self.string = s def print(self): return self.string class Identifier(String): type = "IDENTIFER" def __init__(self,i,check=False): self.ident = i if check: self.ident = convertOp(i) def print(self): return self.ident class Transpose(Node): type="TRANSPOSE" def __init__(self,e): self.expr = printVar(e) def print(self): return self.expr+".T" class Range(Node): def __init__(self,e1,e2,s=""): self.expr1 = printVar(e1) self.expr2 = printVar(e2) self.step = s if s is not "": self.step = ","+s if isinstance(e1,Range): self.expr1 = e1.expr1 self.expr2 = e1.expr2 self.step = ","+self.expr2 def print(self): return "arange(%s,%s%s)"%(self.expr1,self.expr2,self.step) class Expr(Node): type = "EXPR" def __init__(self,e1,op,e2): self.expr1 = printVar(e1) self.operator = convertOp(op) self.expr2 = printVar(e2) def print(self): return self.expr1+self.operator+self.expr2 class Bracket_Expr(Node): type = "BRACKET_EXPR" def __init__(self,e): self.expr = printVar(e) def print(self): return "("+self.expr+")" class Stmt_List(Node): type = "STMT_LIST" def __init__(self,e1,e2): self.expr1 = printVar(e1) self.expr2 = printVar(e2) def print(self): return self.expr1+"\n"+self.expr2 class Global_List(Node): type = "GLOBAL_LIST" def __init__(self,i,g=None): self.iden = i self.glist = g def print(self): if self.glist is None: return self.iden else: return self.glist.print()+", "+self.iden class Global_Stmt(Node): type = "GLOBAL_STMT" def __init__(self,i=None,e=None,g=None): self.glist = g self.iden = i self.expr = e def print(self): if self.glist is None: return "global "+self.ident+"="+self.expr.print() else : return "global "+self.glist.print() class Try_Catch(Node): def __init__(self,s1,s2=""): self.stmtlist1 = printVar(s1) self.stmtlist2 = printVar(s2) if s2 != "": #to make it return ":" after exception self.stmtlist2 = self.stmtlist2.split("\n") self.ex = self.stmtlist2[0] self.stmtlist2 = "\n".join(self.stmtlist2[1:]) def print(self): if self.stmtlist2 == "": return "try:\n"+self.stmtlist1 else: return "try:\n"+self.stmtlist1+"\nexcept %s:\n"%self.ex+self.stmtlist2 class Function(Node): def __init__(self,e1,a): self.args = printVar(a) self.func = convertFunc(printVar(e1)) def print(self): return self.func+"(%s)"%self.args class Function_Dec(Node): def __init__(self,r,n,a,sl=""): self.ret = "\treturn "+printVar(r) self.name = printVar(n) self.args = printVar(a) self.stmtlist = printVar(sl) def addStmt(self,sl): self.stmtlist = printVar(sl)+"\n" def print(self): return "def %s%s:\n"%(self.name,self.args)+self.stmtlist+self.ret class Loop(Node): pass class For(Loop): type = "FOR" def __init__(self,i,e,s): self.item = i e.operator = "," self.expr = printVar(e) #print("here is expr ",self.expr, "type",type(e),e.func,e.args) self.stmt = s def print(self): return "for %s in %s:"%(self.item,self.expr)+'\n'+self.stmt.print() class If(Loop): type = "IF" def __init__(self,e,s,ef): self.expr = printVar(e) self.stmt = printVar(s) self.elseif = printVar(ef) def print(self): if self.elseif == "": return "if "+self.expr+ ":\n" + self.stmt else: return "if "+self.expr+":\n"+self.stmt+"\n"+self.elseif class ElseIf(Loop): type = "ELSE_IF" def __init__(self,e,s,ef): self.expr = e self.stmt = s self.elseif = ef def print(self): return "elif "+self.expr.print()+":\n"+self.stmt.print()+"\n"+self.elseif.print() class Else(Loop): type = "ELSE" def __init__(self,s): self.stmt = s def print(self): return "else:\n"+self.stmt.print() class Switch(Loop): type = "SWITCH" def __init__(self,e,cl): self.expr = printVar(e) self.caselist = cl def print(self): return self.caselist.print(self.expr) class Case_List(Loop): type = "CASE_LIST" def __init__(self,e=None,s=None,c=None,o=False): self.expr = printVar(e) self.stmtlist = s self.caselist = c self.otherwise = o def print(self,e,iselif=False): start = "if" if iselif: start = "elif" output = "%s %s == "%(start,e) +self.expr+":" if self.stmtlist is not None: output += "\n"+self.stmtlist.print() if self.caselist is not None: output+= "\n"+self.caselist.print(e,True) if self.otherwise: return "else:\n"+self.expr return output class While(Loop): type = "WHILE" def __init__(self,e,s): self.expr = printVar(e) self.stmt = s def print(self): return "while %s:\n"%self.expr+self.stmt.print()
1e60b41b66e944478c8d207a96b7ee3d34c1e835
elionoula/PythonCalculatorHW
/src/Calculator.py
1,343
3.90625
4
def addition(a, b): a = float(a) b = float(b) return a + b def subtraction(a, b): a = float(a) b = float(b) return a - b def multiplication(a, b): a = float(a) b = float(b) return a * b def division(a, b, c): a = float(a) b = float(b) if (b == 0): return None else: return round(a / b / c) def squaring(a): a = float(a) return a ** 2 def squareRoot(a, b): a = float(a) if (a < 0): return None else: return round(a**(1/2), b) def lenth(a): if (len(a.split('.')) > 1): return len(a.split('.')[1]) else: return 0 class Calculator: result = 0 def add(self, a, b): self.result = addition(a, b) return self.result def subtract(self, a, b): self.result = subtraction(b, a) return self.result def multiply(self, a, b): self.result = multiplication(a, b) return self.result def divide(self, a, b, c): self.result = division(a, b, c) return self.result def square(self, a): self.result = squaring(a) return self.result def sqrt(self, a, b): self.result = squareRoot(a, b) return self.result def getLength(self, a): return lenth(a) def __init__(self): pass
51d5ae57627ed7795ab41bd809f776e702a33920
yseakshay77/Udacity-data-structures-and-algorithms-nanodegree
/Assignment 3/Problem 2.py
2,229
3.78125
4
def Search(arr, key): n = len(arr) pivot = pivotFind(arr, 0, n - 1); if pivot == -1: return binarySearch(arr, 0, n - 1, key); if arr[pivot] == key: return pivot if arr[0] <= key: return binarySearch(arr, 0, pivot - 1, key); return binarySearch(arr, pivot + 1, n - 1, key); def pivotFind(arr, low, high): if high < low: return -1 if high == low: return low # low + (high - low)/2; mid = int((low + high) / 2) if mid < high and arr[mid] > arr[mid + 1]: return mid if mid > low and arr[mid] < arr[mid - 1]: return (mid - 1) if arr[low] >= arr[mid]: return pivotFind(arr, low, mid - 1) return pivotFind(arr, mid + 1, high) def binarySearch(arr, low, high, key): if high < low: return -1 # low + (high - low)/2; mid = int((low + high) / 2) if key == arr[mid]: return mid if key > arr[mid]: return binarySearch(arr, (mid + 1), high, key); return binarySearch(arr, low, (mid - 1), key); def linear_search(input_list, number): for index, element in enumerate(input_list): if element == number: return index return -1 def test_function(test_case): input_list = test_case[0] # print(type(input_list)) number = test_case[1] re = Search(input_list, number) ree = linear_search(input_list, number) if re == ree : if re != -1: print("Pass") else: print("Given number not found") else: print("Fail") # arr1 = [6, 7, 8, 9, 10, 1, 2, 3, 4] # arr2 = [6, 7, 8, 1, 2, 3, 4] test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 100]) # Given number not found test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1]) #Pass test_function([[6, 7, 8, 1, 2, 3, 4], 8]) #Pass test_function([[6, 7, 8, 1, 2, 3, 4], 1]) #Pass test_function([[6, 7, 8, 1, 2, 3, 4], 1]) #Pass # Edge Cases test_function([[], -1]) # Given number not found test_function([[1], 0]) # Given number not found test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 22]) # Given number not found
b3db986e17b830ef3d69cc2c93eb18de20b5ce0f
likebe/TurtleRace
/TurtleRace/Card.py
5,045
3.6875
4
# Liwei Jiang, Yin Li, Kebing Li # CS269 JP17 # Computer Game Design # Card.py # Jan. 15th 2017 import pygame class Card: def __init__(self, screen, type = 0, image = "card1.png" ): self.type = type self.tag = None self.step = 0 self.category = 0 self.image = image self.image2 = "card.png" self.bigImage = None self.screen = screen self.setTag() self.setBigImage() def setType(self, type): self.type = type self.setTag() def getType(self): return self.type def setStep(self, step): self.step = step def getStep(self): return self.step def setImage(self, image): self.image = image def setImageFloat(self, image): self.image2 = image def getImage(self): return self.image def getImageFloat(self): return self.image2 def setBigImage(self, scale = 0.3): self.bigImage = pygame.transform.scale(self.bigImage, (int(self.bigImage.get_size()[0] * scale * 0.9), int(self.bigImage.get_size()[1] * scale * 0.9)) ) def drawBigImage(self, position = (0,0)): self.screen.blit( self.bigImage, position ) def setTag(self): self.bigImage = str(self.type) + ".png" self.bigImage = pygame.image.load( self.bigImage ) if -1 < self.type < 24: self.category = 0 else: self.category = 1 self.step = 0 if self.type == 0: self.step = 2 self.tag = "Choose a Turtle +2" if self.type == 1: self.step = 1 self.tag = "Choose a Turtle +1" if self.type == 2: self.step = -1 self.tag = "Choose a Turtle -1" if self.type == 3: self.step = -2 self.tag = "Choose a Turtle -2" if self.type == 4: self.step = 2 self.tag = "Yellow Turtle +2" if self.type == 5: self.step = 1 self.tag = "Yellow Turtle +1" if self.type == 6: self.step = -1 self.tag = "Yellow Turtle -1" if self.type == 7: self.step = -2 self.tag = "Yellow Turtle -2" if self.type == 8: self.step = 2 self.tag = "Purple Turtle +2" if self.type == 9: self.step = 1 self.tag = "Purple Turtle +1" if self.type == 10: self.step = -1 self.tag = "Purple Turtle -1" if self.type == 11: self.step = -2 self.tag = "Purple Turtle -2" if self.type == 12: self.step = 2 self.tag = "Red Turtle +2" if self.type == 13: self.step = 1 self.tag = "Red Turtle +1" if self.type == 14: self.step = -1 self.tag = "Red Turtle -1" if self.type == 15: self.step = -2 self.tag = "Red Turtle -2" if self.type == 16: self.step = 2 self.tag = "Green Turtle +2" if self.type == 17: self.step = 1 self.tag = "Green Turtle +1" if self.type == 18: self.step = -1 self.tag = "Green Turtle -1" if self.type == 19: self.step = -2 self.tag = "Green Turtle -2" if self.type == 20: self.step = 2 self.tag = "Blue Turtle +2" if self.type == 21: self.step = 1 self.tag = "Blue Turtle +1" if self.type == 22: self.step = -1 self.tag = "Blue Turtle -1" if self.type == 23: self.step = -2 self.tag = "Blue Turtle -2" if self.type == 24: self.tag = "The Fastest -2" if self.type == 25: self.tag = "The Fastest -1" if self.type == 26: self.tag = "The Slowest +1" if self.type == 27: self.tag = "The Slowest +2" if self.type == 28: self.tag = "Flip the Fastest Turtle" if self.type == 29: self.tag = "Switch the Second Turtle and the Second Last Turtle" if self.type == 30: self.tag = "Show the Position of a Random Pitfall" if self.type == 31: self.tag = "Remove a Random Pitfall" if self.type == 32: self.tag = "Play a Random Card" if self.type == 33: self.tag = "Set a Random Pitfall" if self.type == 34: self.tag = "Set a Visible Pitfall" if self.type == 35: self.tag = "Move a Turtle in a Stack to the Top" if self.type == 36: self.tag = "Move a Turtle in a Stack to the Bottom" if self.type == 37: self.tag = "Move Two Turtles to the Midpoint of Their Positions" if self.type == 38: self.tag = "Exchange the Positions of Two Adjacent Turtles" if self.type == 39: self.tag = "Exchange the Positions of the Second Turtle and the last but one turtle" if self.type == 40: self.tag = "The Selected Turtle is Not Affected by the Next Pitfall" if self.type == 41: self.tag = "Flip a Turtle" if self.type == 42: self.tag = "Flip the Fastest Turtle" if self.type == 43: self.tag = "Play a Random Spell Card" if self.type == 44: self.tag = "Select a Grid and the Turtles Will Take One Step Back When Reach That Grid (One-off) " def getTag(self): return self.tag def getCategory(self): return self.category if __name__ == "__main__": card = Card(12) print "Tag: ", card.getTag() print "Type: ", card.getType() print "Step: ", card.getStep() print "Category: ", card.getCategory() card.setType(40) print "Tag: ", card.getTag() print "Type: ", card.getType() print "Step: ", card.getStep() print "Category: ", card.getCategory()
ff485ccb47b4acd337c0996ed69e407858a06460
hilarymelroy/Ai_Labs_intern
/Ai_DS_intern_assessment_top_genres.py
1,007
3.890625
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 20 18:05:58 2018 @author: hrm1886 """ import pandas as pd from collections import Counter ''' This function saves movie data in a pandas dataframe and creates a dictionary with genres as keys and frequency of occurances of genres as values. It outputs the top 5 genres in the movie data. It assumes a file type of csv. ''' movie_data = pd.read_csv('movie_data.csv') def top_genres(df): genres_dict = {} genre_list = movie_data['genres'].tolist() for genre in genre_list: genre=genre.replace("-","") genre=genre.replace('[',"") genre=genre.replace('"',"") genre=genre.replace("]","") genre=genre.split(",") for word in genre: word=word.strip() if word in genres_dict.keys(): genres_dict[word] += 1 else: genres_dict[word] = 1 return dict(Counter(genres_dict).most_common(5)) top_5_genres = print(top_genres(movie_data))
0587f599b6c6a488ae85f35ef57726dd76154768
diego-coder/golf_maintenance
/golf_maintenance.py
2,597
3.625
4
from math import pi from math import ceil from math import floor def calculate_rough_sod_area(length, width): rough_sod_area = ((length * width) - (calculate_smooth_sod_area(course_width) + calculate_sandtrap_area(course_width))) rough_sod_area_rounded_up = ceil(rough_sod_area) return rough_sod_area_rounded_up def calculate_smooth_sod_area(width): radius_of_smooth_sod = ((width / 2) / 2) one_smooth_sod_area = pi * radius_of_smooth_sod ** 2 total_smooth_sod_area = ceil(one_smooth_sod_area * 2) return total_smooth_sod_area def calculate_sandtrap_area(width): radius_of_sand_trap = ((width / 3) / 2) sand_trap_area = pi * radius_of_sand_trap ** 2 return sand_trap_area def calculate_tons_of_sand(area_of_sand): area_of_trap_in_feet = area_of_sand * 9 volume_of_sand = area_of_trap_in_feet * 1 amount_of_sand_needed_in_lbs = volume_of_sand * 100 sand_in_tons = ceil(amount_of_sand_needed_in_lbs / 2000) return sand_in_tons def calculate_number_of_bricks(width): radius_of_sand_trap = ((width / 3) / 2) circumference_of_sand_trap = 2 * pi * radius_of_sand_trap circumference_in_feet = circumference_of_sand_trap * 3 half_circumference = circumference_in_feet / 2 number_of_bricks_needed = ceil(half_circumference * 3) return number_of_bricks_needed def calculate_number_of_bushes(length, width): perimeter = 2 * (length + width) width_of_trails = 1 + 1 number_of_bushes = floor(perimeter - width_of_trails) return number_of_bushes def calculate_time_to_mow(): smooth_sod_time_to_mow_in_minutes = calculate_smooth_sod_area(course_width) / 60 rough_sod_area_time_to_mow_in_minutes = (calculate_rough_sod_area(course_length, course_width) * .5) / 60 total_time_to_mow = ceil(smooth_sod_time_to_mow_in_minutes + rough_sod_area_time_to_mow_in_minutes) return total_time_to_mow course_length = float(input("Enter course length in yards: ")) course_width = float(input("Enter course width in yards: ")) print("Total square yards of rough sod: " + str(calculate_rough_sod_area(course_length, course_width)) + ".") print("Total square yards of smooth sod: " + str(calculate_smooth_sod_area(course_width)) + ".") print("Tons of sand: " + str(calculate_tons_of_sand(calculate_sandtrap_area(course_width))) + ".") print("Number of retaining wall bricks: " + str(calculate_number_of_bricks(course_width)) + ".") print("Number of bushes: " + str(calculate_number_of_bushes(course_length, course_width)) + ".") print("Total mowing time (mins): " + str(calculate_time_to_mow()) + ".")
88850cc9a63540a8a779968fb94d5f6a1915631a
wikimedia-research/floccus
/floccus/check.py
1,292
3.578125
4
import regexes import re """ A generic function for checking whether a regular expression matched a row. Returns True or False """ def generic_check(regex, row): if(re.search(regex, row)): return True return False """ Check whether a row returned zero results or not. """ def check_zero(row): return generic_check(regexes.check_zero_regex, row) """ Check whether a row is valid or not. """ def check_valid(row): return generic_check(regexes.check_valid_regex, row) """ Check whether a request came from the API. """ def check_api(row): return generic_check(regexes.check_api_regex, row) """ Check whether a request came from the web interface. """ def check_web(row): return generic_check(regexes.check_web_regex, row) """ Check whether a request was a prefix search request. The alternative is full text (check_full_search()) but please be aware that there are other options in the logfiles. """ def check_prefix_search(row): return generic_check(regexes.check_prefix_search_regex, row) """ Check whether a request was a full text request """ def check_full_search(row): return generic_check(regexes.check_full_search_regex, row) """ Check whether a suggestion was provided """ def check_suggestion(row): return generic_check(regexes.get_suggestion_regex, row)
9351659f89ade591fe87bba333d0310ac417e5c0
calumroy/tf_htm
/src/conv2d_tf.py
3,109
3.96875
4
import tensorflow as tf # This shows an example of using the convolve 2d tensorflow function and how to pad the input # and adjust the kernel ''' paddings is an integer tensor with shape [n, 2], where n is the rank of tensor. For each dimension D of input, paddings[D, 0] indicates how many values to add before the contents of tensor in that dimension, and paddings[D, 1] indicates how many values to add after the contents of tensor in that dimension. t = tf.constant([[1, 2, 3], [4, 5, 6]]) paddings = tf.constant([[1, 1,], [2, 2]]) # 'constant_values' is 0. # rank of 't' is 2. tf.pad(t, paddings, "CONSTANT") # [[0, 0, 0, 0, 0, 0, 0], # [0, 0, 1, 2, 3, 0, 0], # [0, 0, 4, 5, 6, 0, 0], # [0, 0, 0, 0, 0, 0, 0]] tf.pad(t, paddings, "REFLECT") # [[6, 5, 4, 5, 6, 5, 4], # [3, 2, 1, 2, 3, 2, 1], # [6, 5, 4, 5, 6, 5, 4], # [3, 2, 1, 2, 3, 2, 1]] tf.pad(t, paddings, "SYMMETRIC") # [[2, 1, 1, 2, 3, 3, 2], # [2, 1, 1, 2, 3, 3, 2], # [5, 4, 4, 5, 6, 6, 5], # [5, 4, 4, 5, 6, 6, 5]] ''' k = tf.constant([ [1, 1, 1], [1, 1, 1], [1, 1, 1] ], dtype=tf.float32, name='k') i = tf.constant([ [1, 2, 1, 0], [1, 1, 0, 1], [0, 0, 0, 1], [1, 1, 0, 2] ], dtype=tf.float32, name='i') s = tf.constant([1, 1, 1, 1] , dtype=tf.float32, name='s') kernel = tf.reshape(k, [3, 3, 1, 1], name='kernel') image = tf.reshape(i, [1, 4, 4, 1], name='image') stride = [1, 1, 1, 1] # We will add our own padding so we can reflect the input. # This prevents the edges from being unfairly hindered due to a smaller overlap with the kernel. paddings = tf.constant([[0, 0], [1, 1], [1, 1], [0, 0]]) padded_input = tf.pad(image, paddings, "REFLECT") # tf.squeeze Removes dimensions of size 1 from the shape of a tensor. # "VALID" only ever drops the right-most columns (or bottom-most rows). # "SAME" tries to pad evenly left and right, but if the amount of columns to be added is odd, it will add the extra column to the right, as is the case in this example (the same logic applies vertically: there may be an extra row of zeros at the bottom). res = tf.squeeze(tf.nn.conv2d(padded_input, kernel, stride, "VALID")) # VALID means no padding # "SAME" means use padding logs_path = '/tmp/tensorflow_logs/example/tf_htm/' with tf.Session() as sess: #sess.run(res) session = sess.run(res) print(padded_input) print(i.eval()) print(session) #print(image.eval()) # op to write logs to Tensorboard summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph()) # Write logs at every iteration # summary_writer.add_summary(summary, epoch * total_batch + i) print("\nRun the command line:\n" "--> tensorboard --logdir=/tmp/tensorflow_logs " "\nThen open http://0.0.0.0:6006/ into your web browser")
99f9cdc93c69fcd8beac52d0d16ecd7faccd69c7
fontes99/pvf-language
/Classes/Tokenizer.py
4,450
3.53125
4
from .Token import Token class Tokenizer: def __init__(self, origin, position, actual): self.origin = origin self.position = position self.actual = actual self.balance_paren = 0 self.balance_brace = 0 self.builtIns = ["printo", "reado", "ifo", "whilo", "elso", "returno"] self.types = ["int", "bool", "string"] self.tokenPosition = 0 def selectNext(self): self.tokenPosition += 1 def next_(): self.position += 1 char = lambda : self.origin[self.position] while self.position < len(self.origin) and (char() == ' ' or char() == '\n' or char() == '\t'): next_() if self.position == len(self.origin): self.actual = Token('EOF', '"') if self.balance_paren != 0: raise ValueError("Error in balancing '(' and ')'") if self.balance_brace != 0: raise ValueError("Error in balancing '{' and '}'") return elif char() == ',': self.actual = Token('SEP', char()) next_() elif char() == '/': self.actual = Token('DIV', char()) next_() elif char() == '*': self.actual = Token('MULT', char()) next_() elif char() == '+': self.actual = Token('SUM', 1) next_() elif char() == '-': self.actual = Token('SUB', -1) next_() elif char() == '>': self.actual = Token('GRT', '>') next_() elif char() == '<': self.actual = Token('LSS', '<') next_() elif char() == '!': self.actual = Token('NEG', '!') next_() elif char() == '&': next_() if char() != '&' : raise ValueError("Syntax error: &&") else: self.actual = Token('AND', '&&') next_() elif char() == '|': next_() if char() != '|' : raise ValueError("Syntax error: ||") else: self.actual = Token('OR', '||') next_() elif char() == '(': self.actual = Token('OPN', '(') self.balance_paren += 1 next_() elif char() == ')': self.actual = Token('CLS', ')') self.balance_paren -= 1 next_() if self.balance_paren < 0: raise ValueError elif char() == '{': self.actual = Token('BEG', '{') self.balance_brace += 1 next_() elif char() == '}': self.actual = Token('END', '}') self.balance_brace -= 1 next_() if self.balance_brace < 0: raise ValueError("Error in balancing '{' and '}'") elif char().isalpha(): name = char() next_() while char().isalpha() or char().isnumeric() or char() == "_": name += char() next_() if name in self.builtIns: self.actual = Token('builtin', name) elif name in self.types: self.actual = Token('TYP', name) elif name == "true": self.actual = Token('BOOL', 1) elif name == "false": self.actual = Token('BOOL', 0) else : self.actual = Token('cons', name) elif char() == "=": next_() if char() != "=": self.actual = Token('atrib', '=') else: self.actual = Token('EQL', '==') next_() elif char() == ";": if self.balance_paren != 0: raise ValueError("Error in balancing '(' and ')'") self.actual = Token('end_line', ";") next_() elif char() == '"': next_() string = char() next_() while char() != '"': string += char() next_() self.actual = Token("STR", string) next_() else: if self.position > 0 and self.actual.tipo == 'INT': raise ValueError("Can't have two INTs in a row") val = "" while(self.position < len(self.origin) and char().isnumeric()): val += char() next_() self.actual = Token('INT', int(val))
a9b38b6888c9e6dc623a6d61bb6d22736623c077
TopperTips/PySpark-By-Example
/rearrange-column-in-dataframe.py
1,267
3.5625
4
#toppertips.com #http://toppertips.com/pyspark-data-frame-rearrange-columns #import necessary files from pyspark.sql.types import StructType, StructField, IntegerType, StringType tips_list = [[1,"item 1" , 2], [2 ,"item 2", 3], [1 ,"item 3" ,2], [3 ,"item 4" , 5]] tips_schema = StructType( [StructField("Item_ID",IntegerType(), True),StructField("Item_Name",StringType(), True ), StructField("Quantity",IntegerType(), True)]) #create dataframe using spark session tips_df = spark.createDataFrame(tips_list, tips_schema) #the schema tips_df.printSchema() ''' root |-- Item_ID: integer (nullable = true) |-- Item_Name: string (nullable = true) |-- Quantity: integer (nullable = true) ''' #register as table tips_df.createOrReplaceTempView("tips_table") tips_new_df = spark.sql("select Item_Name, Item_ID, Quantity from tips_table") tips_new_df.printSchema() ''' root |-- Item_Name: string (nullable = true) |-- Item_ID: integer (nullable = true) |-- Quantity: integer (nullable = true) ''' #using the dataframe approach #create dataframe using spark session tips_df = spark.createDataFrame(tips_list, tips_schema) #use the select function from the dataframe tips_new_df = tips_df.select("Item_Name","Item_ID","Quantity") tips_new_df.printSchema()
65b63c669f8ea96182c3a662a968142803040192
AianaG/Codewars
/Simple maze.py
2,605
3.578125
4
def has_exit(maze): check_mutliple_kate = sum([a.count('k') for a in maze]) if check_mutliple_kate != 1: raise Error kate_position = find_original_position(maze) reached_edge = check_if_on_edge(maze, kate_position[0], kate_position[1]) possible_way_outs = way_outs(maze, kate_position) lengths = max([len(i) for i in maze]) print(lengths) for i in range(len(maze)): if len(maze[i]) < lengths: print(maze[i]) print((lengths - len(maze[i]))) maze[i] = maze[i] + (lengths - len(maze[i]))*' ' if reached_edge : return True elif possible_way_outs == 0: return False else: val = recursive_movement(maze, [kate_position]) return val def find_original_position(maze): for i in range(len(maze)): if 'k' in maze[i]: return [i, [j for j in range(len(maze[i])) if maze[i][j] =='k'][0]] def check_if_on_edge(maze, i, j): if i ==0 or j ==0 or i == len(maze)-1 or j == len(maze[i])-1: return True else: return False def way_outs(maze, current_position): way_outs = [[current_position[0]-1, current_position[1]], [current_position[0]+1, current_position[1]], [current_position[0], current_position[1] -1], [current_position[0], current_position[1] +1]] # print(way_outs) possible_way_outs = [i for i in way_outs if i[0] >=0 and i[1] >=0 and i[0] < len(maze) and i[1] < len(maze[i[0]]) and maze[i[0]][i[1]] == ' '] # print(possible_way_outs) return possible_way_outs def recursive_movement(maze, start_positions): all_possible_positions = [] for start_position in start_positions: previous_allpos = way_outs(maze, start_position) all_possible_positions.extend(previous_allpos) maze[start_position[0]] = list(maze[start_position[0]]) maze[start_position[0]][start_position[1]] = '#' maze[start_position[0]] = ''.join(maze[start_position[0]]) all_possible_positions = [list(x) for x in set(tuple(x) for x in all_possible_positions)] print(all_possible_positions) check_if_any_pos_reached_edge = [1 for i in all_possible_positions if check_if_on_edge(maze, i[0], i[1])] if len(all_possible_positions) == 0: print("here") print(all_possible_positions) return False elif sum(check_if_any_pos_reached_edge) >=1: print("yes") return True else: return recursive_movement(maze, all_possible_positions)
a2a27c35261880040b4014ae6a0fee5992a5937f
AianaG/Codewars
/Valid Spacing.py
256
3.78125
4
def valid_spacing(s): print(s) count_space = list(s).count(' ') count_words = len([a for a in s.split(' ') if a != '']) if s == '': return True elif count_space > count_words-1: return False else: return True
a5be29fe097f3794dd5ddc4bc5f99f49f7ed2815
buckleypj84/Data-Files-and-Reports
/Checkup.py
277
4.0625
4
#Check up print("Hello User!") ans = input("What is your name? ") print(f"hi {ans}!") print("Hi " + ans + "!") age = input("what is your age? ") if (int(age) < 8): print("Aww! you are just a baby!") if (int(age) >= 8): print("ah...a well traveled soul are ye!")
75325fc8ed1e39c7171e1018a343208be713cc6a
Int-TRUE/2021knupython
/2. variables+datatypes/number_datatypes.py
443
3.6875
4
# 숫자 자료형 # 정수형 a = 154 print(type(a)) a = 0 print(type(a)) a=-25 print(type(a)) # 실수형 b = 181.34 print(type(b)) b = -22.22 print(type(b)) # 복소수형 - 'complex' c = 1 + 4j print(type(c)) print(c.real) # 실수부 print(c.imag) # 허수부 print(c.conjugate()) print(abs(c)) # 루트(1 + 4*4 = 17) = 4.12XX # 예제 : 스스로 사칙연산을 활용해가며 확인해보자 a=5 b=3.14 c=3+4j print(10*a + 3*b + c)
9923aca618c6b67c988b6233e2bd6c50ef87c834
Leyka/Advent-2015
/day5/day5b.py
1,171
3.9375
4
def main(): with open('data.txt', 'r') as f: data = f.read() rows = data.split('\n') count = 0 for text in rows: if has_pair_twice(text) and has_sandwich_letters(text): count += 1 print(count) def has_pair_twice(text): """ It contains a pair of any two letters that appears at least twice in the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but not like aaa (aa, but it overlaps). """ i = 1 while i < len(text): first_two_letters = text[i-1] + text[i] remaining = text[i+1:] if first_two_letters in remaining: return True i += 1 return False def has_sandwich_letters(text): """ It contains at least one letter which repeats with exactly one letter between them, like xyx, abcdefeghi (efe), or even aaa. """ i = 0 while i < len(text): try: letter = text[i] same_letter = text[i+2] except: return False if letter == same_letter: return True i += 1 if __name__ == '__main__': main()
48f272b3b5c02aa5cf76427e0fc0dc85fa7e35f4
RafaelTosetto/Python_Exercices
/Modulo_2/Atividade04.py
492
3.984375
4
'''Return the input string, backward''' contrario = "" word1 = str(raw_input("Insira uma palavra: ")) ''' O tipo len eh igual a lengh, ou seja, comprimento. Logo a variavel contador recebe o tamanho da quantidade de letras da variavel word1''' contador = len(word1) while contador != 0: contrario += word1 [contador-1] contador -= 1 print "A palavra inserida ao contrario fica: " print contrario '''A sintaxe abaixo faz a mesma coisa de maneira encurtada print word1[::-1] '''
c5c91f7073894be5d58e17685749b19fc51f9cd5
pgallo725/IPCV-Camera-Calculator
/calculator.py
3,621
4.3125
4
"""Module for parsing and evaluating arithmetic expressions""" OPERATORS = ['+', '-', '*', '/'] def compute(symbols): """ Solve an arithmetical expression, given an array containing the digits and the operator :param symbols: an array of *strings* with the symbols (digits and operators) :return: tuple containing the outcome (SUCCESS/ERROR) and the result or the error description """ if not symbols or len(symbols) == 0: return ('ERROR', 'Empty expression') # The last symbol of an expression must be the '=' sign assert symbols[-1] == '=', "The expression must be terminated by '='" value = "" expression = [] result = 0 i = 0 while i < len(symbols): symbol = symbols[i] # If the current symbol is part of a number if symbol.isdigit() or symbol == '.' or (len(value) == 0 and symbol in ('+', '-')): # Append the symbol to a string containing the value that's being parsed value += symbol # If the current symbol is a mathematical operator elif symbol in OPERATORS or symbol == '=': # Finish parsing the previous token by converting it to a number if len(value) > 0: # Parse numerical value and check if any errors try: num = float(value) expression.append(num) except ValueError: return ('ERROR', 'Invalid value: ' + value) # Reset the token variable value = "" else: # Unexpected mathematical operator return ('ERROR', 'Invalid expression') # Then append the operator to the list expression.append(symbol) else: # Unexpected symbol return ('ERROR', 'Unknown symbol: ' + symbol) i += 1 # Increment index # Apply all operations in the correct order apply_operators(['*', '/'], expression) apply_operators(['+', '-'], expression) # Make sure that the expression has been properly solved assert len(expression) == 2, "Unable to solve the expression" result = expression[0] return ('SUCCESS', result) def apply_operators(operators, expression): """ Find all occurrences of the provided operators in the provided expression, and replace each one with the result obtained by applying the operation to the surrounding values :param operators: a list of values between +, -, * and / which are the operators to apply :param expression: list of math elements (numbers, operators) obtained after parsing :return: nothing, the expression list is modified by reference """ i = 1 while i < len(expression) - 1: if expression[i] in operators: operator = expression[i] op1 = expression[i - 1] op2 = expression[i + 1] # Apply the operation between the previous and following values if operator == '+': res = op1 + op2 elif operator == '-': res = op1 - op2 elif operator == '*': res = op1 * op2 elif operator == '/': res = op1 / op2 else: raise Exception("apply_operator() should only be called with valid operators!") # Replace the 3 items (op1, operator, op2) with the operation result expression[i-1] = res del expression[i+1] del expression[i] else: i += 1 # Increment index
a7fc8315e51cf013a448c21fd401738350345fe5
mgranemann/Curso-Python-Fundamentos
/section5/activities/activity3.py
385
3.59375
4
# Atividade 3 - Criar arquivo novo - argumento 'a' # Crie uma funcao para salvar uma placa de veiculo # A funcao deve receber a placa por parametro # A funcao deverá armazenar em arquivo texto # cada placa deve ser armazenada em uma linha def estacionamento(placa): arquivo = open('placas.txt', 'a') arquivo.write(f'{placa}\n') arquivo.close() estacionamento('MMM-0909')
5390f60e16856cc705318e82421c907efc34f285
mgranemann/Curso-Python-Fundamentos
/section5/activities/activity10.py
1,077
3.59375
4
# Crie uma funcao para listar os instrumentos salvos na atividade anterior # A funcao deve converter cada linha em um dicionário, # A funcao deve tratar os caracteres de quebra de linha # Caso ocorra algum erro durante a leitura, a funcao deve exibir a mensagem de erro (Exception) def ler(): try: lista_instrumentos = [] with open('instrumentos.csv', 'x') as arquivo: for linha in arquivo: # funcao strip retira \n\t\r de uma string, espacos em branco antes e depois linha_limpa = linha.strip() lista_dados = linha_limpa.split(';') instrumento = {'nome': lista_dados[0], 'descricao': lista_dados[1], 'valor':lista_dados[2] } lista_instrumentos.append(instrumento) return lista_instrumentos except Exception as error: msg_erro = f'Não foi possivel ler o arquivo (nstrumentos.csv), verifique se ele existe' raise Exception(msg_erro) try: lista = ler() for l in lista: print(l) except Exception as e: print(e)
053215ffa980a71cf11572584ccf5dc25a6a0e0f
sermanzanedo/2fbigdataEOI
/encriptacion.py
2,095
3.828125
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 17 17:52:57 2016 @author: Sergio """ print "Este es un programa para encriptar frases. Consiste en indicar primero una frase a encriptar y luego dar dos valores numericos que sirvan para:" print "Primero alterar el orden de las palabras en la frase introducida" print "Segundo cambia las letras por la letra en la posion del alfabeto que sea igual a la original + el numero indicado" print "El alfabeto se considera de 26 letras y al llegar al fin comienza de nuevo" x = raw_input ("Dime la frase a Encriptar \n") lista = x.split () rango = len(lista) print print "Antes de introducir el numero para cambiar el orden entre palabras ten en cuenta que el numero debe estar entre 0 y ", len(lista)-1 orden = raw_input("¿Dime un numero para cambiar orden palabras:\n") orden = int(orden) claveLetras= raw_input ("¿Dime un numero para encriptar letras? ") claveLetras = int(claveLetras) #print "tu clave usada para encritar las letras es:", claveLetras fclaveLetras = claveLetras -((claveLetras/26) * 26) #print lista #print len(lista) ListaN = [] for variable in lista: Indice = lista.index(variable) #print Indice Nindice = Indice + orden #print Nindice if Nindice >= len(lista): correccion = Nindice - len(lista) ListaN.insert(correccion,variable) elif Nindice < len(lista): ListaN.insert(Nindice,variable) #print " El nuevo orden es:", " ".join(ListaN) #print ListaN #print ListaN NuevaFrase = [] for word in ListaN: variable = word Acumular = "" for letra in variable: Nletra = ord(letra) + fclaveLetras if Nletra < 122: nPalabras = str (chr(Nletra)) Acumular = Acumular + nPalabras elif Nletra > 122: Cletra = (Nletra - 122) + 97 nPalabras = str (chr(Cletra)) Acumular = Acumular + nPalabras #print Acumular NuevaFrase.append(Acumular) print "Tu frase Encriptada es:\n", " ".join(NuevaFrase)
d6c1dd48d0c1b6bdc9c5bd7ebd936b30201112e5
febikamBU/string-matching
/bmh.py
2,182
4.03125
4
from collections import defaultdict from sys import argv, exit from comparer import Comparer def precalc(pattern): """ Create the precalculation table: a dictionary of the number of characters after the last occurrence of a given character. This provides the number of characters to shift by in the case of a mismatch. Defaults to the length of the string. """ table = defaultdict(lambda: len(pattern)) for i in range(len(pattern) - 1): table[pattern[i]] = len(pattern) - i - 1 return table def run_bmh(table, text, pattern, compare): """ Using the precalculated table, yield every match of the pattern in the text, making comparisons with the provided compare function. """ # Currently attempted offset of the pattern in the text skip = 0 # Keep going until the pattern overflows the text while skip + len(pattern) <= len(text): # Start matching from the end of the string i = len(pattern) - 1 # Match each element in the pattern, from the end to the beginning while i >= 0 and compare(text, skip+i, pattern, i): i -= 1 # If the start of the string has been reached (and so every comparison # was successful), then yield the position if i < 0: yield skip # Shift by the precalculated offset given by the character in the text # at the far right of the pattern, so that it lines up with an equal # character in the pattern, if posssible. Otherwise the pattern is # moved to after this position. skip += table[text[skip + len(pattern) - 1]] if __name__ == "__main__": try: pattern = argv[1] text = argv[2] except IndexError: print("usage: python3 bmh.py PATTERN TEXT") exit() print(f'Searching for "{pattern}" in "{text}".') print() compare = Comparer() table = precalc(pattern) print(f'Precomputed shift table: {dict(table)}') print() for match in run_bmh(table, text, pattern, compare): print(f"Match found at position {match}") print(f"{compare.count} comparisons")
a20404427609f97a1f6e841efe0674371a2e5fbd
yangcongtougg/interview-question
/tree/binary_tree.py
3,182
4
4
# _*_ coding: utf-8 _*_ # @Time :2018/3/13 12:33 # @Author :maxzhangcong # @Email :maxzhangcong@163.com """ *************模块文档注释************** 二叉树的实现 树节点的添加 """ class Node(object): """节点类""" def __init__(self, item): self.item = item self.lchild = None self.rchild = None class Tree(object): """树类""" def __init__(self): self.root_node = None def add(self, item): """ 添加节点 :param item: :return: """ node = Node(item) if self.root_node is None: self.root_node = node return queue = [] queue.append(self.root_node) while queue: cur_node = queue.pop(0) if cur_node.lchild is None: cur_node.lchild = node return else: queue.append(cur_node.lchild) if cur_node.rchild is None: cur_node.rchild = node return else: queue.append(cur_node.rchild) def breadth_travel(self): """ 广度遍历 :return: """ if self.root_node is None: return queue = [] queue.append(self.root_node) while queue: cur_node = queue.pop(0) print(cur_node.item, end='') if cur_node.lchild is not None: queue.append(cur_node.lchild) if cur_node.rchild is not None: queue.append(cur_node.rchild) def preorder_travel(self, root_node): """ 先序遍历 root>>>left>>>right :return: """ if root_node is None: return print(root_node.item, end='') self.preorder_travel(root_node.lchild) self.preorder_travel(root_node.rchild) def inorder_travel(self, root_node): """ 中序遍历 left>>>root>>>right :param root_node: :return: """ if root_node is None: return self.inorder_travel(root_node.lchild) print(root_node.item, end='') self.inorder_travel(root_node.rchild) def postorder_travel(self, root_node): """ 后序遍历 left>>>right>>>root :param root_node: :return: """ if root_node is None: return self.postorder_travel(root_node.lchild) self.postorder_travel(root_node.rchild) print(root_node.item, end='') if __name__ == "__main__": tree = Tree() tree.add(0) tree.add(1) tree.add(2) tree.add(3) tree.add(4) tree.add(5) tree.add(6) tree.add(7) tree.add(8) tree.add(9) tree.add(10) print('*' * 20 + '广度遍历' + '*' * 20) tree.breadth_travel() print('') print('*' * 20 + '先序遍历' + '*' * 20) tree.preorder_travel(tree.root_node) print('') print('*' * 20 + '中序遍历' + '*' * 20) tree.inorder_travel(tree.root_node) print('') print('*' * 20 + '后序遍历' + '*' * 20) tree.postorder_travel(tree.root_node)
cb861120122dc196b56827aaab8b8b7357088d99
MathKode/Decrypt
/test liste.py
158
3.578125
4
import io print(file.read()) file.close() i = True while i : mot = input('Mot : ') if mot in z : print('Non') else : print('Oui')
a6759b87027f5300ccc05b231ed20757e6237d31
JongSeokJang/Sogang_ConputingThinking
/t1.py
1,816
3.578125
4
def cal_kor_avg(students): kor_total=0 for i in students: kor_total+=students['kor'] return kor_total/len(students) def cal_eng_avg(students): kor_total=0 for i in students: eng_total+=students['eng'] return eng_total/len(students) def cal_mat_avg(students): mat_total=0 for i in students: mat_total+=students['mat'] return mat_total/len(students) def cal_total_avg(students): total=0 for i in students: total+=students['total'] return total/len(students) def print_students(students): for i in range(len(students)): kor=students[i].get('kor') eng=students[i].get('eng') mat=students[i].get('mat') students[i]['total']=(kor+eng+mat) students[i]['avg']=((kor+eng+mat)/3) print('num: %s, name: %s, kor: %d, eng: %d, mat: %d, total: %d, avg: %.2f' %(students[i]['num'],students[i]['name'],students[i]['kor'],students[i]['eng'],students[i]['mat'],students[i]['total'],students[i]['avg'])) def print_avg(t,k,e,m): print('\n: %.2f'%(t/5)) print(': %.2f'%(k/5)) print(': %.2f'%(e/5)) print(': %.2f'%(m/5)) #main def main(): students=[{"num":"1", "name":"a", "kor":90, "eng":80, "mat":85,"total":0,"avg":0.0}, {"num":"2", "name":"b", "kor":90,"eng":85, "mat":90,"total":0,"avg":0.0}, {"num":"3", "name":"c","kor":80, "eng":80, "mat":80,"total":0,"avg":0.0}, {"num":"4", "name":"d", "kor":90, "eng":92, "mat":83,"total":0,"avg":0.0}, {"num":"5", "name":"e", "kor":85, "eng":85, "mat":90,"total":0,"avg":0.0}] print_students(students) t=cal_total_avg(students) k=cal_kor_avg(students) e=cal_eng_avg(students) m=cal_mat_avg(students) print_avg(t,k,e,m) if __name__=='__main__': main()
e5f98ee519d4232018d9a4d9da50e31370f562dc
JongSeokJang/Sogang_ConputingThinking
/p10_2.py
267
3.984375
4
while(1): instr = input("input:") if( instr == "STOP"): print("Bye") break outstr = "" for c in instr: if c.islower(): outstr = outstr + c.upper() elif c.isupper(): outstr = outstr + c.lower() else: outstr = outstr + c print(outstr)
e1e2d2ec351944b25fd779eccf98fbf0e5c677c5
gkelty/Sorry
/boardButton.py
511
3.59375
4
import pygame #Invisible buttons behind the image of our board to add functionality TRANSPARENT = (0, 0, 0, 0) class BoardButton(): #Creates the object giving it a tile numberand a location from the list of pawn locations def __init__(self,tileNum,locationX,locationY): self.tileNum = str(tileNum) self.location = (locationX,locationY) #Returns the corresponding values def getLocation(self): return(self.location) def getTileNum(self): return(self.tileNum)
40861069dd3ced07748ff731e7115d04a00a8d3f
gkelty/Sorry
/Pawn.py
995
3.625
4
import Image #Pawn class class Pawn: #Possible colors with there corresponding images colors = ['yellow', 'green', 'red', 'blue'] pawnImages = {'yellow': Image.getImage('images\sorryPawnYellow.png'), 'green': Image.getImage('images\sorryPawnGreen.png'), 'red': Image.getImage('images\sorryPawnRed.png'), 'blue': Image.getImage('images\sorryPawnBlue.png')} #Creates a pawn with a name, color, player tile name and image def __init__(self, name, color, player, tileName): self.name = name self.color = color self.player = player self.tileName = tileName # This is tiles dictionary key to look up tile attributes (found in board class) self.image = Pawn.pawnImages[color] #Returns the pawn image def getPawnImage(self): return self.image #Displays the pawn image to pygame def displayPawn(self, screen, location): screen.blit(self.image, location)
b4f49b1373a9b61f07be12559435764f62091d8e
Sonaiofficial/FizzBuzz-Solution-
/main.py
452
4.0625
4
#Write your code below this row 👇 #take i as a veriable and start from 0 i=0 # here we take the range for fizz buzz is 1-100 for numbers in range(1, 101): # we tart i from 1 and check if the i is divisble by 3 , 5 or both at a time ad the print statement derive as per the condition matched i += 1 if (i % 3==0 and i % 5==0): print("FizzBuzz") elif i % 3==0: print("Fizz") elif i % 5==0: print("Buzz") else: print(i)
2964d50c7d834e0ac94f16de5ea497ebe9ed932d
dinulade101/ECE322Testing
/post_requests/post_req.py
1,117
3.578125
4
import sqlite3 class PostReq: def __init__(self, cursor): #assume cursor is already setup self.cursor = cursor def validate_location(self, loc_code): """ Checks if the location code is in the locations db :param loc_code: location code that we want to validate :returns: boolean value whether or not the location is in the db """ self.cursor.execute('SELECT * FROM locations WHERE lcode = ? COLLATE NOCASE;', (loc_code,)) return len(self.cursor.fetchall()) != 0 def insert_req(self, values): """ Inserts the request with a unique id :param values: key value pair of values to write. Keys are all the same name as the names of requests columns :returns: None """ self.cursor.execute('SELECT MAX(rid) FROM requests;') try: rid = self.cursor.fetchone()[0] + 1 except(TypeError): rid = 1 values['rid'] = rid self.cursor.execute('INSERT INTO requests VALUES (:rid, :email, :rdate, :pickup, :dropoff, :amount);',values)
a29e29d8f4e58d67a3d7cf38132b587cb8c27822
dinulade101/ECE322Testing
/command/cancelBookingCommand.py
2,224
4.3125
4
''' This file deals with all the commands to allow the user to cancel bookings. It will initially display all the user's bookings. Then the user will select the number of the booking displayed to cancel. The row of the booking in the db will be removed. The member who's booking was canceled will get an automated message as well. ''' import sqlite3 import re import sys from command.command import Command from book_rides.cancel_booking import CancelBooking class CancelBookingCommand(Command): def __init__(self, cursor, email): super().__init__(cursor) self.email = email self.cb = CancelBooking(cursor) def menu(self): print(''' Cancel bookings:\n Press Ctrl-c to return to menu\n''') rows = self.cb.get_member_bookings(self.email) if len(rows) == 0: print("You do not have any bookings!") return valid_bno = set() for row in rows: valid_bno.add(row[0]) print("\nYour bookings:\n") self.display_page(0, rows, valid_bno) def cancel_booking(self,bno): # delete the booking and create a message for the booker self.cb.cancel_booking(self.email, bno) print('Booking canceled successfully!') def display_page(self, page_num, rows, valid_bno): page = rows[page_num*5: min(page_num*5+5, len(rows))] for row in page: print("Booking No. {0} | User: {1} | Cost: {2} | Seats: {3} | Pick up: {4} | Drop off: {5}".format(row[0], row[1], row[3], row[4], row[5], row[6])) if (page_num*5+5 < len(rows)): user_input = input("To delete a booking, please enter the booking number. To see more bookings enter (y/n): ") if (user_input == 'y'): self.display_page(page_num+1, rows, valid_bno) return else: print() user_input = input("To cancel a booking, please enter the booking number: ") if user_input.isdigit() and int(user_input) in valid_bno: print("Canceled the following booking with bno: " + user_input) self.cancel_booking(user_input) else: print("Invalid number entered")
3e50850a1e24cc243739578057737517782f1df2
ThePavolC/An-Introduction-to-Interactive-Programming-in-Python
/Pong.py
5,363
3.75
4
# Implementation of classic arcade game Pong import simplegui import random # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH / 2 HALF_PAD_HEIGHT = PAD_HEIGHT / 2 LEFT = False RIGHT = True ball_pos = [WIDTH / 2, HEIGHT / 2] ball_vel = [0, 0] paddle1_pos = [0 , HEIGHT / 2] paddle2_pos = [WIDTH, HEIGHT / 2] paddle1_vel = 0 paddle2_vel = 0 score1 = 0 score2 = 0 paddle_acc = 4 # initialize ball_pos and ball_vel for new bal in middle of table # if direction is RIGHT, the ball's velocity is upper right, else upper left def spawn_ball(direction): global ball_pos, ball_vel # these are vectors stored as lists horizontal = random.randrange(120, 240) / 60 vertical = random.randrange(60, 180) / 60 ball_pos = [WIDTH / 2, HEIGHT / 2] if direction == RIGHT: ball_vel[0] = horizontal ball_vel[1] = - vertical elif direction == LEFT: ball_vel[0] = - horizontal ball_vel[1] = - vertical # define event handlers def new_game(): global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel, score1, score2 # reset paddles to center paddle1_pos = [0 , (HEIGHT / 2) - HALF_PAD_HEIGHT] paddle2_pos = [WIDTH, (HEIGHT / 2) - HALF_PAD_HEIGHT] paddle1_vel = 0 paddle2_vel = 0 score1 = 0 score2 = 0 # randomly pick which side ball goes first direction = random.randint(0,1) if direction == 1: spawn_ball(RIGHT) else: spawn_ball(LEFT) def draw(c): global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel, paddle1_vel, paddle2_vel # draws field c.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White") c.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White") c.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White") # calculate ball position ball_pos[0] += ball_vel[0] ball_pos[1] += ball_vel[1] ##################################### # Decide what to do on sides of field ##################################### # left side if ball_pos[0] <= (BALL_RADIUS + PAD_WIDTH): """ if ball_pos[1] >= paddle1_pos[1] and ball_pos[1] <= (paddle1_pos[1] + PAD_HEIGHT): ball_vel[0] = - ball_vel[0] * 1.1 """ # added BALL_RADIUS/2 which kind of extend paddle. It looks more realistic :-D if ball_pos[1] >= (paddle1_pos[1] - BALL_RADIUS/2) and ball_pos[1] <= (paddle1_pos[1] + PAD_HEIGHT + BALL_RADIUS/2): ball_vel[0] = - ball_vel[0] * 1.1 else: spawn_ball(RIGHT) score2 += 1 # right side elif ball_pos[0] >= (WIDTH - (BALL_RADIUS + PAD_WIDTH)): """ if ball_pos[1] >= paddle2_pos[1] and ball_pos[1] <= (paddle2_pos[1] + PAD_HEIGHT): ball_vel[0] = - ball_vel[0] * 1.1 """ # added BALL_RADIUS/2 if ball_pos[1] >= (paddle2_pos[1] - BALL_RADIUS/2) and ball_pos[1] <= (paddle2_pos[1] + PAD_HEIGHT + BALL_RADIUS/2): ball_vel[0] = - ball_vel[0] * 1.1 else: spawn_ball(LEFT) score1 += 1 # top side elif ball_pos[1] <= BALL_RADIUS: ball_vel[1] = - ball_vel[1] # bottom side elif ball_pos[1] >= HEIGHT - BALL_RADIUS: ball_vel[1] = - ball_vel[1] c.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White") # update paddle's vertical position, keep paddle on the screen paddle1_pos[1] += paddle1_vel paddle2_pos[1] += paddle2_vel # this make sure that paddles stay in screen if paddle1_pos[1] <= 0: paddle1_pos[1] = 0 if paddle1_pos[1] + PAD_HEIGHT >= HEIGHT: paddle1_pos[1] = HEIGHT - PAD_HEIGHT if paddle2_pos[1] <= 0: paddle2_pos[1] = 0 if paddle2_pos[1] + PAD_HEIGHT >= HEIGHT: paddle2_pos[1] = HEIGHT - PAD_HEIGHT # draw paddles c.draw_line([paddle1_pos[0],paddle1_pos[1]],[paddle1_pos[0],paddle1_pos[1] + PAD_HEIGHT], PAD_WIDTH , "White") c.draw_line([paddle2_pos[0],paddle2_pos[1]],[paddle2_pos[0],paddle2_pos[1] + PAD_HEIGHT], PAD_WIDTH , "White") # draw scores c.draw_text(str(score1), [WIDTH / 2 - 90, 80], 50, 'White') c.draw_text(str(score2), [WIDTH / 2 + 70, 80], 50, 'White') def keydown(key): global paddle1_vel, paddle2_vel, paddle_acc acc = paddle_acc if key==simplegui.KEY_MAP["w"]: paddle1_vel -= acc elif key==simplegui.KEY_MAP["s"]: paddle1_vel += acc elif key==simplegui.KEY_MAP["down"]: paddle2_vel += acc elif key==simplegui.KEY_MAP["up"]: paddle2_vel -= acc def keyup(key): global paddle1_vel, paddle2_vel, paddle_acc acc = paddle_acc if key==simplegui.KEY_MAP["w"]: paddle1_vel += acc elif key==simplegui.KEY_MAP["s"]: paddle1_vel -= acc elif key==simplegui.KEY_MAP["down"]: paddle2_vel -= acc elif key==simplegui.KEY_MAP["up"]: paddle2_vel += acc # create frame frame = simplegui.create_frame("Pong", WIDTH, HEIGHT) frame.set_draw_handler(draw) frame.set_keydown_handler(keydown) frame.set_keyup_handler(keyup) frame.add_button('Reset', new_game, 200) # start frame new_game() frame.start()
7d77f122017030431417902d4d298ddbf6953b90
soniabliss/Itunes
/hw1pr2.py
6,471
3.546875
4
# # hw1pr2 ~ CS181 spring 2021 # # # Name(s): Sonia Bliss # import requests import string import json import time # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # Problem 2 starter code # # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # # # # starting function: getting an artist id from a name-lookup # def get_id_from_name(artist_name): """ This function takes in artist_name: a string, e.g., "Lizzo" or "Taylor Swift" or ... and currently returns an entire json-found dictionary Your task is to change it to return only the artist's id# Return -1 to signal an error if there was no match. There may be many """ # it's good to keep in mind: you don't _have_ to re-download data, if you already have it! # a hand-created table of already-found ids (to save API calls) # if name == "Taylor Swift": return 159260351 # if name == "Kendrick Lamar": return 368183298 # if name == "The Beatles": return 136975 # if name == "Lizzo": return 472949623 # Here, use the itunes search API to get an artist's itunes ID search_url = "https://itunes.apple.com/search" parameters = {"term":artist_name,"entity":"musicArtist", "media":"music","limit":200} result = requests.get(search_url, params=parameters) #print(result.url) #print(f"result.status_code is {result.status_code}") if result.status_code == 200: data = result.json() # this is _ALL_ the data #print(f"full url: {result.url}") return data['results'][0]['artistId'] #print("data is", data) # you'll want to work with this data at the command-line (or print it here) else: print("returning {}") return {} # return no data # # Testing the not-quite-correct-yet get_id_from_name # if True: print() print("Calling for Lizzo:") id = get_id_from_name("Lizzo") # 472949623 print(f"id is {id}") time.sleep(2) print() print("Calling for Taylor Swift:") id = get_id_from_name("Taylor Swift") print(f"id is {id}") # you'll want to fix the function to return the id only # # Then, the second function: get_albums_from_id(id) # # You'll need to implement this. Here's a single-url example from which to build # The itunes documentation (linked in the hw) will help, too if False: pass # try pasting this into your browser address bar: # https://itunes.apple.com/lookup?entity=album&id=472949623&limit=200 # # Note: that url does use Lizzo's id... # My browser actually downloads the result as a txt file, but it is json # You'll need to use the API documentation (and this example) to make this a more general function # (Plus, use the first function as a guide...) def get_albums_from_id(id): """takes the id from def_get_id_from_name assembles the url, the parameters into a dictionary for requests, and makes the API call return the whole json-obtained dictionary of data """ search_url = "https://itunes.apple.com/lookup" parameters = {"entity":"album", "id":id, "limit":200} result = requests.get(search_url, params=parameters) if result.status_code == 200: data = result.json() #print(data) return data else: print("returning {}") return {} # Then, the question-answering function: more_productive( artist_name1, artist_name2 ) def more_productive( artist_name1, artist_name2 ): """Takes two arguments that are two strings of arists names. Looks up the id number for each to make a list of albums for each. Counts the albums and returns with artist was more productive (which artist has the higher album count) """ winner = '' albums1 =[] albums2 = [] id1 = get_id_from_name(artist_name1) id2 = get_id_from_name(artist_name2) albumdic1 = get_albums_from_id(id1) albumdic2 = get_albums_from_id(id2) for result in albumdic1["results"]: if result["wrapperType"] == 'collection': albums1 += [result] for result in albumdic2["results"]: if result["wrapperType"] == 'collection': albums2 += [result] if len(albums1) > len(albums2): winner = artist_name1 if len(albums2) > len(albums1): winner = artist_name2 print("Who's more productive between", artist_name1, "and", artist_name2,"??") print(artist_name1, "had", len(albums1), "results") print(artist_name2, "had", len(albums2), "results") print(winner, "is more productive!") # Finally, ask - and answer - another question using the itunes data from the album lookup... def another_inquiry( artist_name1, artist_name2 ): """Takes two arguments that are two strings of arists names. Looks up the id number for each and gets the album dictinaries for an explicit rating. Counts the explicit albums and returns with the artist who has more explicit content """ winner = '' dirtyalbums1 =[] dirtyalbums2 = [] id1 = get_id_from_name(artist_name1) id2 = get_id_from_name(artist_name2) albumdic1 = get_albums_from_id(id1) albumdic2 = get_albums_from_id(id2) for result in albumdic1["results"]: if result["wrapperType"] == 'collection': if result["collectionExplicitness"] == 'explicit': dirtyalbums1 += [result] for result in albumdic2["results"]: if result["wrapperType"] == 'collection': if result["collectionExplicitness"] == 'explicit': dirtyalbums2 += [result] if len(dirtyalbums1) > len(dirtyalbums2): winner = artist_name1 if len(dirtyalbums2) > len(dirtyalbums1): winner = artist_name2 print("Who has more explicit music between", artist_name1, "and", artist_name2,"??") print(artist_name1, "had", len(dirtyalbums1), "results") print(artist_name2, "had", len(dirtyalbums2), "results") print(winner, "has more explicit music!") if True: print("\n") print("Dictionary of data for queen Megan Thee Stallion:") id = get_id_from_name("Megan Thee Stallion") get_albums_from_id(id) print("\n") more_productive( "Cardi B", "Megan Thee Stallion" ) print("\n") another_inquiry( "Kirk Franklin", "Saweetie" ) print("\n") another_inquiry( "Young Thug", "Lil Baby" ) print("\n") another_inquiry( "Amy Winehouse", "Tay Money" )