首页 > 编程语言 >Advent of Code 2023 solution [Mathematica/Python]

Advent of Code 2023 solution [Mathematica/Python]

时间:2023-12-02 14:32:21浏览次数:34  
标签:Code end Python positions Mathematica start num dict word

Day 1

Part 1

(*读取文件*)lines = ReadList["E:\\ExplorerDownload\input.txt", String];

(*计算校准值*)
calibrationValues = 
  ToExpression[
     StringJoin[#[[1]], #[[-1]]]] & /@ (StringCases[#, 
       DigitCharacter] & /@ lines);

(*打印总和*)
Print[Total[calibrationValues]]

Part 2

import re

# 英文数字词对应的字典
word_to_num = {
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4,
    'five': 5,
    'six': 6,
    'seven': 7,
    'eight': 8,
    'nine': 9
    # ,
    # 'ten': 10,
    # 'eleven': 11,
    # 'twelve': 12,
    # 'thirteen': 13,
    # 'fourteen': 14,
    # 'fifteen': 15,
    # 'sixteen': 16,
    # 'seventeen': 17,
    # 'eighteen': 18,
    # 'nineteen': 19,
    # 'twenty': 20,
    # 'thirty': 30,
    # 'forty': 40,
    # 'fifty': 50,
    # 'sixty': 60,
    # 'seventy': 70,
    # 'eighty': 80,
    # 'ninety': 90,
    # 'hundred': 100,
    # 'thousand': 1000,
    # 'million': 1000000,
    # 'billion': 1000000000,
}

# 输入的字符串
# input_strs = [
#     'two1nine',
#     'eightwothree',
#     'abcone2threexyz',
#     'xtwone3four',
#     '4nineeightseven2',
#     'zoneight234',
#     '7pqrstsixteen'
# ]
# 从文件中读取输入的字符串
with open('input_part2.txt', 'r') as f:
    input_strs = [line.strip() for line in f]


# 抽取英文数字词和它们的位置
word_num_positions = []
for i, s in enumerate(input_strs):
    for word, num in word_to_num.items():
        for match in re.finditer(word, s):
            start, end = match.span()
            word_num_positions.append((i, start, end, word, num))

# 抽取所有的数字和它们的位置
digit_positions = []
for i, s in enumerate(input_strs):
    for match in re.finditer(r'\d', s):
        start, end = match.span()
        digit_positions.append((i, start, end, int(s[start:end])))

# 输出结果
# print('Word numbers and their positions:')
# for pos in word_num_positions:
#     print(f'String index: {pos[0]}, Start: {pos[1]}, End: {pos[2]}, Word: {pos[3]}, Number: {pos[4]}')
#
# print('\nDigits and their positions:')
# for pos in digit_positions:
#     print(f'String index: {pos[0]}, Start: {pos[1]}, End: {pos[2]}, Digit: {pos[3]}')

# for [StringIndex, Start, End, Word, Number] in word_num_positions:
#     print(f"{StringIndex=} {Start=} {End=} {Number=}")
# for [StringIndex, Start, End, Digit] in digit_positions:
#     print(f"{StringIndex=} {Start=} {End=} {Digit=}")

# 英文数字词和数字的位置
word_num_positions.sort()
digit_positions.sort()

# 创建存储每个StringIndex最小Start和最大End的字典
start_dict = {}
end_dict = {}

# 找到每个StringIndex的最小Start
for i, s, e, w, n in word_num_positions:
    if i in start_dict:
        start_dict[i] = min(start_dict[i], (s, n))
    else:
        start_dict[i] = (s, n)

for i, s, e, d in digit_positions:
    if i in start_dict:
        start_dict[i] = min(start_dict[i], (s, d))
    else:
        start_dict[i] = (s, d)

# 找到每个StringIndex的最大End
for i, s, e, w, n in word_num_positions[::-1]:
    if i in end_dict:
        end_dict[i] = max(end_dict[i], (e, n))
    else:
        end_dict[i] = (e, n)

for i, s, e, d in digit_positions[::-1]:
    if i in end_dict:
        end_dict[i] = max(end_dict[i], (e, d))
    else:
        end_dict[i] = (e, d)

# 输出每个StringIndex的二位数
total=0
for i in range(len(input_strs)):
    start_num = start_dict.get(i, (None, 0))[1]
    end_num = end_dict.get(i, (None, 0))[1]
    total+=(start_num * 10 + end_num)
    print(f'String index: {i}, Number: {start_num * 10 + end_num}')
print(f"{total=}")



标签:Code,end,Python,positions,Mathematica,start,num,dict,word
From: https://blog.51cto.com/u_15247503/8656922

相关文章

  • 【python笔记】弱引用weakref
    参考书籍:《深度学习入门——自制框架》[日]斋藤康毅强引用会出现循环引用的情况classobj(): passa=obj()#使用赋值运算,引用计数加1b=obj()c=obj()#执行到这里,a、b、c的引用计数都为1a.b=b#被对象强引用,引用计数加1b.c=cc.a=a#执行到这里,a、b、......
  • 【pwn】shellcode revenge --0~9,A~Z字符的shellcode
    查一下保护拖进ida看主要逻辑这里的代码逻辑为mmap开辟一段有执行的地址,可以写入shellcode,但这次写入的shellcode有限制if(buf>90||buf<=47||buf>57&&buf<=64) break;这里的限制shellcode的十六进制数对应的字符只能是0~9,A~Z,这些十六进制数对应的shellcode......
  • # yyds干货盘点 # Python如何通过input输入一个键,然后自动打印对应的值?
    大家好,我是皮皮。一、前言前几天在Python最强王者交流群【冯诚】问了一个Python基础的问题,一起来看看吧。问题描述:大佬们,我有个字典如下:dict={'b':2,'a':4,'c':3}如何通过input输入一个键,然后自动打印对应的值?二、实现过程这里【巭孬......
  • Python报错:performance hint: av/logging.pyx:232:5: the GIL to be acquired
     参考:https://stackoverflow.com/questions/77410272/problems-installing-python-av-in-windows-11https://github.com/PyAV-Org/PyAV/issues/1177  ================================  报错信息:C:\Windows.old\Users\chris>pipinstallavDefaultingtouser......
  • [LeetCode Hot] LeetCode283. 移动零
    题目描述方法一:时间复杂度O(n2)classSolution{publicvoidmoveZeroes(int[]nums){for(inti=0;i<nums.length;i++){//指针i为0的时候停止if(nums[i]==0){//遍历[i+1,nums.length-1],如果遇......
  • [LeetCode Hot 100] LeetCode11. 盛最多的水
    题目描述方法一:暴力,超出时间限制模拟所有情况,记录最大的体积值。体积=Math.min(height[i],height[j])*(j-i)classSolution{publicintmaxArea(int[]height){intres=Integer.MIN_VALUE;for(inti=0;i<height.length;i++){......
  • conda环境下Python报错:raise MissingCUDAException("CUDA_HOME does not exist, unabl
    conda环境下Python报错:(pytorch)devil@Monster:~$pipinstalldeepspeedCollectingdeepspeedUsingcacheddeepspeed-0.12.4.tar.gz(1.2MB)Preparingmetadata(setup.py)...errorerror:subprocess-exited-with-error×pythonsetup.pyegg_infodid......
  • Python报错:pkg-config could not find libraries ['avformat', 'avcodec', 'avdev
    参考:https://github.com/PyAV-Org/PyAV/issues/238https://pyav.org/docs/6.1.2/installation.html#mac-os-x  =====================  报错信息:C:\Users\liuxue>pipinstallavCollectingavUsingcachedav-0.3.3.tar.gzInstallingcollectedpackages:av......
  • Python正则表达式(小结)
    1.什么是正则表达式?正则表达式(regularexpression,有时简写为RegEx或regex)就是用一组由字母和符号组成的“表达式”来描述一个特征,然后去验证另一个“字符串”是否符合/匹配这个特征。2.应用场景?(1)验证字符串是否符合指定特征,比如验证邮件地址是否符合特定要求等;(2)用来查找字......
  • 无涯教程-Python - 泊松分布
    泊松分布是显示事件在预定时间段内可能发生的次数的分布,它用于独立事件,这些事件在给定的时间间隔内以恒定的速率发生,泊松分布是一个离散函数,意味着该事件只能按发生或不发生的方式进行度量,这意味着该变量只能按整数进行度量。无涯教程使用具有内置功能的seabornpython库来创建......