🐞

Python Debug

 

Situation: Intro2musictech project

01 librosa.display has no attribute “waveplot"
has changed to waveshow.....
重新打开jupyter notebook的时候说找不到了?

报错内容

Jupyter command jupyter-notebook not found.

原因

unknown

解决措施

重新安装jupyter,好像安装也失败了,重启terminal,重新打开好几次,突然自己好了
每一次在notebook里打开一个新的jpynb文件在import的时候都会报错

报错内容

librosa import的过程中会在某个地方 xxx package not found

原因

?

解决措施

在code上方加一个cell重新下载一遍librosa
下载jpynb插件

报错内容

不显示extension

原因

解决措施

# 下载以后发现不显示extension $ conda install -c conda-forge jupyter_contrib_nbextensions $ jupyter nbextension enable # 还是不显示,中途用conda remove把上面两个都删了,把terminal退出了,从base进jupyter notebook,就莫名其妙可以了,这次进去才有conda/extension两个界面
00-hello 使用librosa.load出现warning
00-hello 里面import librosa出错

报错内容

No module named 'numpy.core._multiarray_umath'

原因

numpy版本不够

解决措施

notion image
 

Situation: Data Structure and Algorithms

509用哈希表library的时候编码问题报错

报错内容

import hashlib # Message Digest hashlib.md5('hello,world!').hexdigest() # Secure Hash Algorithm hashlib.sha1('hello,world!').hexdigest()
TypeError: Unicode-objects must be encoded before hashing

原因

python3中字符对象是unicode对象,而hash传递时需要的是utf-8类型,不能直接加密,需要先类型转换。
 

解决措施

在每个string后面加encode("utf-8")
503冒泡排序递归和选择排序答案错误

报错内容

没报错,但每次排出来并不是从大到小。
# recursion method def bSort2(list): round = len(list) if round > 1: # go through 1 loop then shrink the list size for i in range(round - 1): if list[i] > list[i + 1]: list[i], list[i + 1] = list[i + 1], list[i] bSort2(list[:-1]) test1 = [3,5,1,6,20,4,3,17] import time t1 = time.process_time() bSort2(test1) t2 = time.process_time() print(test1) print(t2 - t1) # selection sort as an enhanced bubble sort def sSort(list): round = len(list) exchange = True while round > 1 and exchange: # if exchange happens, resume. if not, stop. round -= 1 exchange = False # initiate: no exchanges happen when each loop starts max_index = 0 for j in range(round): if list[j] >= list[max_index]: max_index = j else: exchange = True # if current item is smaller than previous max, exchange hanppens list[max_index], list[round] = list[round], list[max_index] import time test1 = [3,5,1,6,20,4,3,17] t1 = time.process_time() sSort(test1) t2 = time.process_time() print(test1) print(t2 - t1)

原因

  1. debug冒泡的时候发现当round = 1了程序不会进入if但是还是会直接执行if里面的bsort2???
  1. debug选择的时候发现,有时候即使列表里最后一个已经是最大,还是会被交换,比如会出现[3,3,1,4]被换成[3,4,1,3]的情况。反过去想循环原理,这肯定是因为我们循环了j in range(round)找最大值的时候,没有比到最后一项,找的最大值是前3项最大值。
  1. 其次看exchange这个bool有没有问题,它代表的含义是是否要继续对比,也就是排序是否完全排好,在compare的过程中是每一项都和max进行了compare的,但凡有一次max没更新,也就是发现后面还有更小值的情况,就说明还要继续,如果全程max一直更新到最后一位,说明已经排好了exchange继续等于false。这里exchange位置正确。
 

解决措施

  1. 递归的内容不正确,这里没法从list的size进行递归,最小问题也不是list只有1/2项的时候,最小问题是exchange = 0,监测到list已经排好序不需要排序了。于是更小问题依次是排1次序,排2次序。最小问题不用操作,只用写次规模问题,先进行一次排序,再扔到函数里看是否排好。
  1. 改一下for的range,其他都没问题。
 
# selection sort as an enhanced bubble sort def sSort(list): round = len(list) exchange = True while round > 1 and exchange: # if exchange happens, resume. if not, stop. round -= 1 exchange = False # initiate: no exchanges happen when each loop starts # find max item max_index = 0 for j in range(1, round + 1): if list[j] >= list[max_index]: max_index = j else: exchange = True # if current item is smaller than previous max, exchange hanppens # if max_index < round: list[max_index], list[round] = list[round], list[max_index] import time test1 = [3,5,1,6,20,4,3,17] t1 = time.process_time() sSort(test1) t2 = time.process_time() print(test1) print(t2 - t1) # selection sort as an enhanced bubble sort def sSort(list): round = len(list) exchange = True while round > 1 and exchange: # if exchange happens, resume. if not, stop. round -= 1 exchange = False # initiate: no exchanges happen when each loop starts # find max item max_index = 0 for j in range(1, round + 1): if list[j] >= list[max_index]: max_index = j else: exchange = True # if current item is smaller than previous max, exchange hanppens # if max_index < round: list[max_index], list[round] = list[round], list[max_index]
411偷东西最优化问题

报错内容

# define treasure values treasure = [None, {'w':2,'v':3},{'w':3,'v':4},{'w':4,'v':8},{'w':5,'v':8},\ {'w':9,'v':10}] # restrict max weight maxW = 20 # initiate DP table # before w > existant max w, when w = 0 or when i = 0, initial m = 0 m = {(i, w) : 0 for i in range(len(treasure) for w in range(maxW + 1))} # fill in DP table for i in range(1, len(treasure) + 1): for w in range(1, maxW + 1): lastW = treasure[i]['w'] lastV = treasure[i]['v'] if lastW > w: # treasure is a list of dict, [i]refers to i'th dict, ['w']refers to the key in dict # only possible result: w/ last treasure m[(i, w)] = m[(i - 1, w)] # m is a dict, (i,w)is the key else: # w or w/ last treasure m[(i, w)] = max(m(i - 1, w), m(i - 1, w - lastW) + lastV) print(m[(5,20)])
  1. line 16, in <module> m = {(i, w) : 0 for i in range(len(treasure) for w in range(maxW + 1))} TypeError: 'generator' object cannot be interpreted as an integer
  1. m[(i, w)] = max(m(i - 1, w), m(i - 1, w - lastW) + lastV) TypeError: 'dict' object is not callable
  1. lastW = treasure[i]['w'] IndexError: list index out of range

原因

  1. 第一个不太明显,报错报的是range里只能放integer,实际虽然是maxW+1,但是是第一个range的地方括号打到了最后……,变成一整个range都是i的。
  1. m是dict,不能直接用dict(key)来call,要用dict[(key)],这里没有打方括号
  1. 在lastW的地方报错溢出,实际上是i的范围有问题,行名i需要从1到5,但是treasure本身因为已经有了NoneType,要用取length的方法就不用+1了

解决措施

410递归求找零问题答案错误

报错内容

原程序
def charge2(money): coins = [1,5,10,25] result = 0 if money > 0: if money in coins: result = 1 else: result = 1 + min(charge2(money-25),charge2(money-10),charge2(money-5),charge2(money-1)) return result print(charge2(28))
  1. 第一个if:TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'
  1. 输入增量,跑得巨慢
  1. 输出答案是错的
  1. otherCoins = 1 + change2(money-i,coins,results)TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

原因

  1. return放到第一个if里面以后,当我们遇到小于0的输入的时候,就没有return啦,在min里面就变成NoneType互相比较大小,系统搞不懂的!
  1. 对于小于0的输入,默认输出的是0,比较的时候当然最小了,但事实明显不是这样
  1. 结果要做数值计算的时候,递归函数一定要有return的实值,否则没法计算

解决措施

  1. 把return result dedent就可以bug free了
  1. 但是整个程序循环结构很烂,第一result默认返回的应该是worst scenario,就是只能用1找零的最大值。第二进if第二个else的条件应该是coin里面的值小于money的时候。第三,既然第二已经这样了,min里面不永远是4个变量比较,而是只有硬币面值小于money的函数比较。循环结构条件需要重写
  1. 特别慢的原因是用了递归就算了,还在一个min函数里同时用4个,时间复杂度太大
def change2(money,coins,results): minCoins = money if money in coins: results[money] = 1 minCoins = 1 elif results[money] != 0: minCoins = results[money] else: for i in [coin for coin in coins if coin <= money]: otherCoins = 1 + change2(money-i,coins,results) if otherCoins < minCoins: results[money] = otherCoins minCoins = otherCoins return minCoins import time t1 = time.process_time() print(change2(63,[1,5,10,25],64*[0])) t2 = time.process_time() print(t2 - t1)
312判断回文词全都是false

报错内容

源程序
# define Palindrome def palindrome(word): order = Deque() reverse = Deque() for letter in word: order.addRear(letter) reverse.addFront(letter) if order == reverse: return True else: return False test1 = 'abccba' test2 = 'abc' print(palindrome(test1)) print(palindrome(test2)) # solution 2 def palindrome2(word): d = Deque() for i in word: d.addRear(i) for j in range(d.size()): if d.removeRear() != d.removeFront(): return False return True print(palindrome2(test1)) print(palindrome2(test2))
  1. solution1全是false
  1. d.removeRear() != d.removeFront() IndexError: pop from empty list

原因

  1. solution2里面的for循环限制没对,一开始dsize是word里全部字母数,但对消的次数只有一半
  1. 试了不止半个小时才发现,Deque的本质是class,不是列表。if order == reverse比较的是类的两个实例,暂时不知道比较instance背后是什么机制,可能是class的地址?反正这里比出来不相等了。我们在创建Deque的时候,初始化建了一个内部变量item才是列表

解决措施

  1. 把range改成len(word)//2 注意是整除,否则报错TypeError: 'float' object cannot be interpreted as an integer
  1. 把solution1里面的判等改成items
  1. 很明显,第一个我自己想的方法更占空间
# define Palindrome def palindrome(word): order = Deque() reverse = Deque() for letter in word: order.addRear(letter) reverse.addFront(letter) if order.items == reverse.items: return True else: return False test1 = 'toot' test2 = 'abc' print(palindrome(test1)) print(palindrome(test2)) # solution 2 def palindrome2(word): d = Deque() for i in word: d.addRear(i) for j in range(len(word)//2): if d.removeRear() != d.removeFront(): return False return True print(palindrome2(test1)) print(palindrome2(test2))
311打印机问题

报错内容

源程序
def simPrinter(stuNum,maxPage,avgTime,mode): # stuNum学生总数 manPage单次任务最大页数 avgTime发起次数 # mode1 打印机差模式每分钟打印10 # mode2 打印机好模式每分钟打印5 printFree = True # 默认空闲状态 taskProb = (stuNum*avgTime)/3600 pageProb = 1/maxPage taskQueue = Queue() # 存放task排队 for i in range(3600): # 确定这一秒有没有新任务,新任务多少页,如果有insert进queue,把这个task打上时间戳 # task应该是一个class # 判断打印机此刻是否空闲,如果不空,显示正在打的task序号、多少页,倒计时 # 如果空,把queue队首的一项pop出来,打印机改为非空,显示上面的信息 # return平均等待时间 class Task(): def __init__(self,page,start): self.number = 0 self.page = page self.start = start # 该任务等待时间 def waitTime(self,now): ---- import random class Printer(): def __init__(self,ppm): self.pagerate = ppm # page per minute self.currentTask = None self.timeRemaining = 0 # default free # 确定此时打印机状态,和等待时间 def tick(self): # 不空闲时等待时间少一秒 if self.currentTask != None: self.timeRemaining -= 1 if self.timeRemaining == 0: self.currentTask = None def busy(self): if self.currentTask == None: return False else: return True def startNew(self,newtask): self.currentTask = newtask self.timeRemaining = newtask.getPage() * 60 / self.pagerate class Task(): def __init__(self, page, start): self.page = random.randrange(1,page) self.timeStamp = start # 输出生成的属性 def getStamp(self): return self.timeStamp def getPage(self): return self.page # 该任务等待时间 def waitTime(self, now): return now - self.timeStamp def newTask(taskProb): prob = random.randrange(1, 1+taskProb) if prob == taskProb: return True else: return False def simPrinter(stuNum,maxPage,avgTime,mode): # stuNum学生总数 manPage单次任务最大页数 avgTime发起次数 # mode10 打印机差模式每分钟打印10 # mode5 打印机好模式每分钟打印5 newPrinter = Printer(mode) taskProb = 3600/(stuNum*avgTime) # 每隔多少秒会出现一个任务,也就是说每秒钟出现任务的概率是1/x taskQueue = Queue() # 存放task排队 waitRecord = [] for currentSecond in range(3600): # 确定这一秒有没有新任务,新任务多少页,如果有insert进queue,把这个task打上时间戳 # task应该是一个class if newTask(taskProb): taskQueue.enqueue(Task(maxPage,currentSecond)) # 判断打印机此刻是否空闲,如果不空,显示正在打的task序号、多少页,倒计时 # 如果空,把queue队首的一项pop出来,打印机改为非空,显示上面的信息 if not newPrinter.busy(): currentTask = taskQueue.dequeue() newPrinter.startNew(currentTask) waitRecord += currentTask.waitTime(currentSecond) else: newPrinter.tick() # return平均等待时间 return waitRecord print(simPrinter(10,20,2,10))
  1. 第一次运行会导致从空列表里pop,是因为if不合理
  1. waitRecord += currentTask.waitTime(currentSecond) TypeError: 'int' object is not iterable

原因

  1. 第一次如果random没有generate出task,taskqueue就是空的,此时打印机不忙,程序想让queue里pop一个任务出来给打印机,所以出现dequeue失败
  1. waitrecord是列表不是字符串,所以不能简单用数值加减数字,要用自带函数append或者pop(或者之前讲过的四种生成方法)。这里除非把后面要加进去的变量变成列表,但是注意这样concat操作了n+k次(因为是复制到新列表),复杂度更大。 waitRecord += [currentTask.waitTime(currentSecond)]这样写其实也可以

解决措施

  1. 在判断是否要给打印机新任务那里,要加一个打印列表不空的条件。同时tick函数不用放在else后面,因为tick是在打印机忙的情况下才操作,在打印机空的时候运行无伤大雅
  1. 向waitrecord列表增加data改成append
  1. task class里其实有两个函数不太需要
def simPrinter(stuNum,maxPage,avgTime,mode): # stuNum学生总数 manPage单次任务最大页数 avgTime发起次数 # mode10 打印机差模式每分钟打印10 # mode5 打印机好模式每分钟打印5 newPrinter = Printer(mode) taskProb = 3600/(stuNum*avgTime) # 每隔多少秒会出现一个任务,也就是说每秒钟出现任务的概率是1/x taskQueue = Queue() # 存放task排队 waitRecord = [] for currentSecond in range(3600): # 确定这一秒有没有新任务,新任务多少页,如果有insert进queue,把这个task打上时间戳 # task应该是一个class if newTask(taskProb): taskQueue.enqueue(Task(maxPage,currentSecond)) # 判断打印机此刻是否空闲,如果不空,显示正在打的task序号、多少页,倒计时 # 如果空,把queue队首的一项pop出来,打印机改为非空,显示上面的信息 if not taskQueue.isEmpty() and not newPrinter.busy(): currentTask = taskQueue.dequeue() newPrinter.startNew(currentTask) waitRecord += [currentTask.waitTime(currentSecond)] #waitRecord.append(currentTask.waitTime(currentSecond)) # 不论此时什么情况打印机都要过一秒 newPrinter.tick() # return平均等待时间 # return waitRecord avgWait = sum(waitRecord) / len(waitRecord) print("average waiting time is %6.2f, remaining task number is %d"\ %(avgWait,taskQueue.size())) # 这里的%6.2f意思是总共输出含六个数字的float 小数位两位 不足数位用空格符补充 # %s %d %f 分别是placeholder for string decimal float simPrinter(10,20,2,10)
 
309算约瑟夫问题死循环

报错内容

源程序
def josephProb(N,k): simQueue = Queue() pplOut = [] for i in N: simQueue.enqueue(i) counter = 1 while N > 1: # 玩到counter=k 有人out为一局 while counter != k: # 当前的报数为counter call = simQueue.dequeue() # 当前报数的人的序号 simQueue.enqueue(call) # 当前报数的人不out则移到队尾 # counter=k 此刻队首的人要出局 总人数-1 # 把出局的人从左到右记录到list pplOut.append(simQueue.dequeue()) # N = simQueue.size() N -= 1 return simQueue.dequeue() N = 10 k = 3 josephProb(N, k)
  1. for i in N TypeError: 'int' object is not iterable
  1. 在while counter里面死循环
  1. 没有输出结果
  1. out的序列打不出来

原因

  1. 不能 for 变量 in 数字,后者必须是range。而且注意range(n)打印的是0到n-1,range(a,b)也是左闭右开
  1. while循环条件是counter,但是while里面居然没有counter的值改变。。。
  1. 循环完一局,counter=k有人out了,总人数减1,继续数,counter没有清零
  1. 注意结果要print出来才显示,除非是bool

解决措施

def josephProb(N,k): simQueue = Queue() pplOut = [] for i in range(1,N+1): # remember to use range!!! simQueue.enqueue(i) counter = 1 while N > 1: # 玩到counter=k 有人out为一局 while counter != k: # for i in range k: #另一种循环写法,虽然是0到k-1,循环次数一致 # 当前的报数为counter call = simQueue.dequeue() # 当前报数的人的序号 simQueue.enqueue(call) # 当前报数的人不out则移到队尾 counter += 1 #remember to auto increase # counter=k 此刻队首的人要出局 总人数-1 # 把出局的人从左到右记录到list pplOut.append(simQueue.dequeue()) N = simQueue.size() # N -= 1 counter = 1 # remember to reset counter return simQueue.dequeue() N = 10 k = 3 print(josephProb(N, k))
306计算后缀形式算式循环中无法计算string

报错内容

初始程序
def posCal(expression): operand = Stack() tokenList = expression.split() for token in tokenList: if token == '*' and not operand.isEmpty(): operand.push(operand.pop() * operand.pop()) elif token == '/' and not operand.isEmpty(): operand.push(1/operand.pop() * operand.pop()) elif token == '+' and not operand.isEmpty(): operand.push(operand.pop() + operand.pop()) elif token == '-' and not operand.isEmpty(): operand.push(- operand.pop() + operand.pop()) else: operand.push(token) result = operand.pop() return result test5 = 'a b * c -' test6 = 'a b c * +' test7 = 'a b + c * d e - -' test8 = '3 4 * 5 -' print(posCal(test8))
TypeError: can't multiply sequence by non-int of type 'str'

原因

  1. 破罐破摔法改造:流程没问题,把token的运算符对应到计算的具体操作也没有问题,主要问题在于,最后一个else的时候,遇到数字push进去的是string,没法做前面所有if的运算。
  1. code没有硬伤,但简洁性还有问题,选择分支if语句太多,可以额外做一个function出来,以及pop()出现太多次(每一个if里都有),可以在进入分之前先给变量。
  1. 遇到除法和减法的时候,运算顺序和pop出来的顺序是相反的!!

解决措施

  1. 最简单的改法:直接在我的程序上else里的token加上int(token)
  1. 改进原则还是把数字放到最后的else里push,因为很难找到条件判断进来的token是数字?把那一堆if放到另一个函数里,把前面所有if改成先pop出两个数
  1. 第一个def输出的时候不用另找变量直接pop
改进后:
def posCal(expression): operand = Stack() tokenList = expression.split() for token in tokenList: if token in '*/-+' and not operand.isEmpty(): op1 = operand.pop() op2 = operand.pop() operand.push(doMath(op1,op2,token)) else: operand.push(int(token)) return int(operand.pop()) def doMath(op1,op2,operator): if operator == '*': return op1 * op2 elif operator == '/': # better use elif, so circulation time is 1 return 1 / op1 * op2 # note the order of op1 and op2 is contrary with division elif operator == '+': return op1 + op2 else: return - op1 + op2 test5 = '3 4 * 5 -' print(posCal(test5))
 
305中缀转换列表问题

报错内容

原程序:
def in2post(expression): opstack = Stack() postfixList = [] tokenList = expression.split() index = 0 # use dict to record priority for later comparison pri = {} pri['*'] = pri['/'] = 3 # define key with a value pri['+'] = pri['-'] = 2 pri['('] = 1 # because operator can be pushed directly after ( without popping while index < len(expression): token = tokenList[index] # meet ( then push if token == '(': opstack.push(token) # meet */+- compare elif token in '*/+-': # check if last operator is prior while opstack.peek() != '(' and pri[opstack.peek()] > pri[token]: postfixList += str(opstack.pop()) opstack.push(token) elif token == ')': while opstack.peek() != '(': postfixList += str(opstack.pop()) opstack.pop() else: opstack.push(token) index += 1 while not opstack.isEmpty(): postfixList += opstack.pop() return postfixList test1 = '(a+b)*c-(d-e)' in2post(test1)
报错语句:
  1. token = tokenList[index]IndexError: list index out of range
  1. key error:‘a'

原因

  1. 比较stack最后一个项和刚遇到的符号优先级的时候,还要加上一个栈非空的条件
  1. 因为字典里没有字母作为key可以查,所以到了比较的那一步,遇到stack现存最后一个数据项是字母,就进行不下去。 →结果发现字母为什么会在stack里!!!字母明明直接输出到post,所以最后一个else那里不该是push
  1. 循环把变量放进函数做传参的时候,只能用exec函数,否则就会产生一群字符串而非变量
  1. split到tokenlist没法成功,每一次实际上是把一整个字符串放在了token里。试了半天又去看split函数的使用方法,才发现对字符串进行split操作必须要有分割符,默认是空符。也就是说我们的test必须要用空格隔开。。。

解决措施

  1. 不用join输出了,直接把post全部当成字符串。一开始创建list,用append添加,最后join输出也是一种方法。
  1. 不用tokenlist了,直接用list读取处理输入的string。注意当输入没有空格隔开的时候可以用index读取list的方法,如果有空格隔开就用token!!
def in2post(expression): opstack = Stack() postfixList = '' index = 0 # use dict to record priority for later comparison pri = {} pri['*'] = pri['/'] = 3 # define key with a value pri['+'] = pri['-'] = 2 pri['('] = 1 # because operator can be pushed directly after ( without popping while index < len(expression): token = expression[index] # meet ( then push if token == '(': opstack.push(token) # meet */+- compare elif token in '*/+-': # check if last operator is prior while not opstack.isEmpty() and pri[opstack.peek()] > pri[token]: postfixList += str(opstack.pop()) opstack.push(token) elif token == ')': while opstack.peek() != '(': postfixList += str(opstack.pop()) opstack.pop() else: postfixList += token index += 1 while not opstack.isEmpty(): postfixList += opstack.pop() return postfixList test1 = 'a*b-c' test2 = 'a+b*c' test3 = 'a*(b+c)' test4 = '(a+b)*c-(d-e)' for i in range(1,5): exec('print(in2post(test%s))'%i) # 循环输出变量不能单独把i拼接到test以后再放荡函数参数里,那样会变成字符串而不是变量名 # 用exec函数直接把i放进去
304进制转换程序卡死

报错内容

运行不exit
修改前原版
def dec2Bi(num): s = Stack() while num != 1: s.push(divmod(num,2)) num /= 2 bi = '' for i in s: bi += str(s.pop()) return bi

原因

  1. 检查debug发现生成的s栈无休止小数,是num除以二的时候,和c不一样,python不默认整除
  1. 输出循环不应该用for i in s,因为输出直接用pop,停止的标记是stack是否为空,和i没有关系的
  1. 用错了函数divmod,该函数不是返回余数,而是返回数组(a // b, a % b),当然数组push进栈是不会报错的。返回余数直接用%
  1. num != 1的话程序会在最后一次1/2的时候少一个余数1,导致输出少一位,正确界限是0

解决措施

把上三处错误修改以后成功
def dec2Bi(num): s = Stack() while num != 0: # 停止线是被除数不为1,在此循环中是num不为0 s.push(num % 2) num //= 2 # remember divide with integer only!!! bi = '' while not s.isEmpty(): bi += str(s.pop()) return bi test4 = 123 print(dec2Bi(test4))
303程序卡死

原因

进debug模式发现在test2的时候,stack里的数据项增加异常 ,怀疑是parenmatch函数里面死循环
测试完发现两个问题
  1. while循环里把counter自增写到了else里面,导致第一个if结束以后index不变
  1. 不管在C还是python里自增都应该是+=1,而不是=+1

解决措施

把index自增那行code改对,然后outdent
303Stack判断括号match的时候push传参数量出错

报错内容

push() takes 1 positional argument but 2 were given

原因

用list定义Stack类的时候,push函数就没写对
我写的:
# push defpush(self): self.items.append()
应该写的:
notion image

解决措施

这里需要传参两个,如果写成push(item) :,后面再给这个函数传参,python就会觉得你传了两个参数(第一个默认是self)。如果不写item,相当于定义的这个函数什么参数都没传进去,最后在主程序调用的时候用push(symbol)相当于传了2个参进去,就故障了

Situation: Code Jam to I/O

tensorflow import出错
2020不平衡秤很多错

报错内容

 
  1. position = int(input().split()) TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
  1. TypeError: unsupported operand type(s) for -: 'str' and 'int'
  1. 加入map函数以后: current_no = position[i] TypeError: 'map' object is not subscriptable
  1. result[current_no] = 'L' IndexError: list assignment index out of range
def imbalance(N): result = [] position = int(input().split()) pan = 'R' for i in range(N - 1, 0, -1): current_no = position[i] if i % 2 == 0: result[current_no] = 'R' else: result[current_no] = 'L' return str(result) T = int(input()) for case in range(1, T + 1): result = imbalance(input()) print("Case #{}: {}".format(case, result))

原因

  1. position是一个list,输入的string被split以后也是list,这没问题,但是这个list里每个元素是string,int不能作用在整个list里
  1. 忘记N的输入要作为integer形式
  1. map在py3里返回的是映射器!!调用debug会发现position被传的值是<map object at 0x104cbecf8>
  1. 空列表没有长度,直接调用result[4]会出现溢出。创建空列表以后,current_no那里还应该-1,因为数字对应到列表的位置包括0要-1,否则还是会溢出。
  1. 全部debug以后,输出出现空字符,是因为for range那里,遍历permutation的时候,是从index N-1到0,是应该包括0的,所以range改成-1。其次,输出格式不是string是list,是因为str()函数直接把list的所有东西变成string,应该用join函数

解决措施

  1. 尝试用map修改position的定义,并且在map前面强制list
  1. 调用imbalance的时候input强制int
  1. py定义是空列表len为0,所以强行创建一个N项元素为空字符串‘’的列表
2020数最大IO数输入报错以及算出错误答案

报错内容

TypeError: cannot unpack non-iterable int object
# Code Jam to I/O for women 2020 problems # 2021.04.17 # Problem 1: Interleaved Input def interleaved(string): int count_I, count_i, IO = 0 for char in string: if char == 'I': count_I += 1 elif char == 'i': count_i += 1 elif char == 'O': # match O with I first if count_I > 0: count_I -= 1 IO += 1 else: count_i -= 1 else: if count_i > 0: count_i -= 1 else: count_I -= 1 IO += 1 return IO T = int(input()) for case in range(1, T + 1): result = interleaved(input()) # print('Case #%d: %d'%(case, result)) print("Case #{}: {}".format(case, result))

原因

  1. c++里定义变量才用int,python不用
  1. 不能三个变量一起初始化
  1. 只有O匹配到I的时候才IO++,o匹配I的时候不用

解决措施

  1. 修改变量定义
  1. 删除第二个IO += 1
 

Situation: CFD project

panda

报错内容

 

原因

 

解决措施

pandas read csv问题

报错内容

no attribute found
之后又有no file found

原因

到处删package找了半天解决方法,突然发现,我他妈csv写成了cvs大无语
working directory开在其他文件夹下面了
pip3 install了以后pycharm显示不存在

原因

python版本太多,packages下载的位置不在当前project config的文件夹里

解决措施

pip3统一下载到anaconda里,统一用ana,之后做版本归一
 

Situation:NNDL project

delete redundant python versions

Solutions

homebrew cleanup
mac下多个版本的python如何删除?
我最近也在弄 下载了太多python版本 准备把除了anaconda下载的留下,其他的删掉,但是系统给的不能删,否则可能要重装系统 现在我梳理一下我要删除的,也就是homebrew下载的 和 pycharm下载的 估计还有pip和其他macports pycharm可以使用anaconda下载的就行了 How to uninstall Python 2.7 on a Mac OS X 10.6.4? 用这几个代码 删掉第三方安装的2.7版本的· sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7 再删掉directory sudo rm -rf "/Applications/Python 2.7" 再删掉连接 cd /usr/local/bin/ ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm 这一番弄下来,只剩下 直接剩下这个和系统2.7版本的 其他的都是invalid,也就是不可用 也就是把我的anaconda里面的也删掉了(这是pycharm显示的) 我也用alfred试了试,发现就是这样 只剩下这个3.5版本了 你也可以使用代码来看还有那些 which python which python3 FAQ homebrew 这个删不掉,因为只能删掉老版本的 只剩一个就删不掉 可以看看能删掉那些 于是乎我直接在python应用程序-右键-显示原身,然后整个python3文件夹移到垃圾桶了 于是乎alfred查找python彻底就找不到了 还要删掉macport的 我发现我有好多python 最后把你不必要的删掉 进去删掉你不需要的 nano .bash_profile 删完按control+x保存 y 回车就可以了 最终只剩下了系统的 参考: 1.
mac下多个版本的python如何删除?
download homebrew
 

Situation: Machine Learning

Jupyter notebook Non-unique cell id
“pastadom”???? Accessing dict with non-existent keyword

Error

notion image

Cause

Accessing dict with non-existent keyword

Solution

rewrite
Access Dataframe slices
multiple plots in one for loop
getting weights of wrong size in GD

Error

notion image

Cause

notion image
 

Solution

You have to make sure everything in matrix calculation is np array
without array, which means a = [1, 2, 3] is different from a = [[1],[2],[3]], the former one makes a * a 9 rows!
 
ipy notebook ignore warnings
copying data frame to change df values
plot labels can’t print greek symbols like theta in python

Causes

$\hat$ works fine, but \t means tab, so $\theta$ won’t work
 

Solutions

Only works in plots though, how about print?
Problem with operating with list in subtraction, print etc
Numpy array conversion without changing tuple to subarray
Range doesn’t take in float numbers

Errors

TypeError 'float' object cannot be interpreted as an integer

Causes

notion image

Solutions

standard printing lines
Weird Float digits

Errors

They should be 0.5, by hand
notion image

Causes

 

Solutions

decimal, round, fraction
Python Line break continuation wrapping codes
for in range() miss the last trail!

Errors

for depth in range(5, 50, 5)

Causes

range doesn’t include the stop point
 

Solutions

range(5, 51, 5)
jupyter notebook conda install sklearn error
 

Solutions

Get rid of those fancy commands, just download with the CORRECT name:
PackagesNotFoundError: The following packages are not available from current channels:
Updated Jun 29, 2020
matplotlib for drawing functions

Errors

only size-1 arrays can be converted to Python scalars

Causes

passed vectorized theta to L, which is expected to be a single value.
How? No idea, it may suggest that there are probably collision of function name and variable names.
notion image

Solutions

It turns out the math package is in conflict with numpy. Get rid of math and use np for log.

Situation: Stats

** for squares

Errors

can’t run through the function definition
notion image
ufunc 'bitwise_xor' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'’

Causes

 

Solutions

Turns out you have to use ** instead of ^ in python for squares.... been using too much latex...
scipy minimization doesn’t work: converge, constraint
ZIP!!!! not iterable

Errors

if you just zip k and freq, two arrays, together, in the def function, we won’t even go into the for loop
notion image

Causes

because zip returns an iterator!!! and it’s irreversible!! So the first time you go over it, you’re done, that’s why you’re not allowed to go into that “for”, because you encounter an empty list!
 

Solutions

make the zip() iterable: list(), dict(), str(), iter()
 

Situation: NLP

Error

 

Cause

 

Solution

zip in VM (Linux) and download from VM

Error

zip command not found
 

Solution

notion image
Colab output text wrap
passing multiple paras through list

Error

notion image

Cause

[’a’,’b’] in function(a, b) only defines a

Solution

use *
not hashable when set() a list to count unique values in list

Solution

index out of range when deleting elements in list

Error

notion image

Cause

Index is shrinking!!!
notion image
Even if you record before deleting, you still get out of range.

Solution

Python的list循环遍历中,删除数据的正确方法
初学Python,遇到过这样的问题,在遍历list的时候,删除符合条件的数据,可是总是报异常,代码如下: 会报异常:IndexError: list index out of range 原因是在删除list中的元素后,list的实际长度变小了,但是循环次数没有减少,依然按照原来list的长度进行遍历,所以会造成索引溢出。 于是我修改了代码如下: 这回不会报异常了,但是打印结果如下: [1, 2, 3, 4, 5] 1 4 5 [1, 3, 4, 5] [Finished in 0.441s] 虽然最后,list中的元素[2]确实被删除掉了,但是,在循环中的打印结果不对,少打印了[3]。 思考了下,知道了原因,当符合条件,删除元素[2]之后,后面的元素全部往前移,于是[3, 4, 5]向前移动,那么元素[3]的索引,就变成了之前[2]的索引(现在[3]的下标索引变为1了),后面的元素以此类推。可是,下一次for循环的时候,是从下标索引2开始的,于是,取出了元素[4],就把[3]漏掉了。 把代码修改成如下,结果一样,丝毫没有改观: 既然知道了问题的根本原因所在,想要找到正确的方法,也并不难,于是我写了如下的代码: 执行结果,完全正确: [1, 2, 3, 4, 5] 1 3 4 5 [1, 3, 4, 5] [Finished in 0.536s] 我的做法是,既然用for循环不行,那就换个思路,用while循环来搞定。每次while循环的时候,都会去检查list的长度(i < len(num_list) ),这样,就避免了索引溢出,然后,在符合条件,删除元素[2]之后,手动把当前下标索引-1,以使下一次循环的时候,通过-1后的下标索引取出来的元素是[3],而不是略过[3]。 当然,这还不是最优解,所以,我搜索到了通用的解决方案:1、倒序循环遍历;2、遍历拷贝的list,操作原始的list。 执行结果完全正确。那么,为何正序循环时删除就有问题,而倒序循环时删除就ok?额。。。。。。言语难表,还是画个丑图出来吧。 1)正序循环时删除: 删除元素[2]之后,下一次循环的下标索引为2,但此时,里面存放的是[4],于是就把[3]给漏了。 2)倒序循环时删除 删除元素[2]后,[3, 4, 5]往前挤,但是没关系,因为下一次循环的下标索引为0,里面存放的是[1],所以正是我们所期望的正确的元素值。 2、遍历拷贝的list,操作原始的list 原始的list是num_list,那么其实,num_list[:]是对原始的num_list的一个拷贝,是一个新的list,所以,我们遍历新的list,而删除原始的list中的元素,则既不会引起索引溢出,最后又能够得到想要的最终结果。此方法的缺点可能是,对于过大的list,拷贝后可能很占内存。那么对于这种情况,可以用倒序遍历的方法来实现。
Python的list循环遍历中,删除数据的正确方法
no directory when Using stopwords

Error

OSError: No such file or directory: '/root/nltk_data/corpora/stopwords/ ‘

Cause

notion image

Solution

this code here is by default blank, you need to insert a language so that it searches the file name in that folder for you
multi-dim list wrapped output
nltk package download

Error

nltk.download() won’t work

Solution

use a specific group eg. nltk.download("popular")
changing directory
 

Situation: samo

Jupyter notebook remote never get killed!

Error

jupyter notebook list jupyter notebook stop
even no serve is running, it shows you have one path running

Cause

Ungraceful exit in the past…

Solution

if not this is my post
filtering lists with a choice list or two

Error

i asked it here

Solution

use logical &
 
yaml install issue

Error

pip install yaml → import issue
conda install yaml → doesn’t exist
 

Solution

pip install pyyaml
folder exit error and overwrite
 
 

Cause

use makedir argument
 

Solution

if os.path.exists(args.out_fold): logging.warning('{} exists'.format(args.out_fold)) print("overwrite:" + args.overwrite) os.makedirs(args.out_fold, exist_ok=args.overwrite) if args.overwrite: shutil.rmtree(args.out_fold) os.mkdir(args.out_fold)
torch cosine similarity dim for matrix(64, 160)
Tuple can’t do to(device) or torch.cat
list iteration while remove list elements
Can’t reshape list object

Error

notion image

Cause

reshape is for np array
and reshape(1, -1) means we want a one row array without knowing how many columns there are, this -1 is for python to figure out
 
 

 

Situation: General Pycharm Usage

change python ver within conda env

Solution

conda 更换python版本
更改conda虚拟环境路径 (1)修改用户目录下的.condarc文件(C:\Users\username) conda 更换python版本 (2)打开.condarc文件之后,添加或修改.condarc 中的 env_dirs 设置环境路径,按顺序第⼀个路径作为默认存储路径,搜索环境按先后顺序在各⽬录中查找。直接在.condarc添加: envs_dirs: - D:\Anaconda3\envs 然后,在Anaconda Prompt执行 conda info 命令,就可以看到修改默认环境路径成功 当新创建虚拟环境验证时,可能会发现它还是默认安装在C盘用户目录下的envs 通过执行命令conda env list查看有哪些虚拟路径以及它们的存储路径,* 号表示当前所处的环境。 (pytor) C:\Users\username>conda env list #conda environments: # pytor * D:\Anaconda3\envs\pytor base d:\Anaconda3 pytor d:\Anaconda3\envs\pytor d:\anaconda3 (4)如果还是没有修改成功,则需要 更改D:\Anaconda3的权限 :选中Anaconda3文件夹,然后右击选则属性,找到安全,Users权限全部允许。接下来确定后,时间稍微有点长,等待完成即可。 这时新创建一个虚拟环境验证时,发现在D:\Anaconda3\envs下。 aniconda更换python的普通做法是删除旧的环境,安装新的环境,这样安装的其他库和依赖项都需要卸载,重新安装 简单的方法: conda activate xxx conda install python=3.7.4 自动会卸载之前的版本,更新新的版本。 不过换了版本以后,第三方库也都需要重新安装,比如opencv,torch 查看python版本: python3 --version 其中TensorFlow 1.15版本需要单独下载,不支持,python3.8版本 下载网址: tensorflow · PyPI 感谢: 将Anaconda默认Python版本变成指定版本_了因和尚的博客-CSDN博客_anaconda 默认python版本
conda 更换python版本
go into the conda ver
then conda install python=3.9
reinstall all other dependencies
Navigating into and out of functions, switching between cursor positions
 

Situation:AVN

args parser in jupyter
jupyternotebook: using shell scripts

Error

%%bash + cd is only working in one cell

Cause

%%bash or !cd won’t work

Solution

use%before lines directly
%cd …
%pwd…
changing batch size using /

Error

if you use / , it will be converted to float and is not acceptable by dataloader
 

Solution

 

Situation: Capstone

change conda env within jupyter
 

Situation: AM project

soundfile doesn’t report file not found!!!!
i don’t know if this is a normal case or it is just in selection execution console mode. Anyway, there’s no “filenotfound” error raised, when you are in a wrong working directory………….
File "_rgi_cython.pyx", line 19, in scipy.interpolate._rgi_cython.__pyx_fused_cpdef TypeError: No matching signature found
why debugging works but as soon as you run in a normal way: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
IDK why but it’s resolved when i closed the same file in another split view leaving only one open
don’t mix up “readline()” and readlines()
when you count row amount of a file, using len(a.readline()) is actually outputting the length of the first line!
broadcast problem when doing pointwise multiply (512, 7, 7 ) * (512, )
value error when checking if some np array ! = None
adding args inside code without command line
because parser.parse_args() is basically a namespace
you can directly define args = argparse.Namespace(a = ‘1’) stuff like this
checking all attributes of a class
A lot of import issues are usually dependency version’s problem
specify path to import local libraries from other projects