书生大模型实战营第4期——入门篇2 Python

145 阅读1分钟

task1: 383. 赎金信

题目:给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。如果可以,返回 true ;否则返回 false 。magazine 中的每个字符只能在 ransomNote 中使用一次。

思路:使用hash表记录magazine中字符和出现次数的映射char2cnt,然后迭代ransomNote的每个字符,看看该字符是否出现在char2cnt并且数量>0。

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        char2cnt = {} # 记录magazine中字符数量
        # 词频统计
        for c in magazine:
            char2cnt[c] = char2cnt.get(c, 0) + 1

        # 迭代判断ransomNote的字符是否在magazine里面
        for c in ransomNote:
            if c in char2cnt and char2cnt[c] > 0:
                char2cnt[c] -= 1
            else:
                return False

        return True
        

提交结果:

f2636c4187e1c751d1f98fe484b8eac.png

task2: Vscode连接InternStudio debug

1 首先安装python扩展:

image.png

2 然后点击VSCode侧边栏的“Run and Debug”(运行和调试),单击"create a lauch.json file"。

image.png

选择python debugger: image.png

debug发现输出是```json ```格式的内容,需要去掉后再用json.loads把json字符串转为字典: image.png

添加如下代码后,结果正确:

res = res.replace("```json","").replace("```","").strip()

image.png

task3: pip安装到指定目录

首先启动一个conda环境,并且使用-t参数安装numpy到机/root/myenvs目录下:

image.png

接下来切换到没有安装numpy的环境test,执行包含numpy的脚本,其中在开头将myenvs目录临时动态的添加到python环境变量中:

import sys
#import numpy as np # 直接导入会报错
npy_dir = "/root/myenvs/"
if npy_dir not in sys.path:
    sys.path.append(npy_dir)

import numpy
val = numpy.mean([1,2,3])
print(val)

执行结果如下:

image.png

总结

本次课程熟悉了python的基础用法、pip和conda的包管理、vscode的两种debug方法,和InternLM的api调用方式,受益颇多,加油~