Situation: Intro2musictech projectSituation: Data Structure and AlgorithmsSituation: Code Jam to I/OSituation: CFD projectSituation:NNDL projectSituation: Machine LearningSituation: StatsSituation: NLPSituation: samoSituation: General Pycharm UsageSituation:AVNSituation: CapstoneSituation: AM projectSituation:Jupyter Notebook
Situation: Intro2musictech project
01 librosa.display has no attribute “waveplot"
has changed to waveshow.....
重新打开jupyter notebook的时候说找不到了?
每一次在notebook里打开一个新的jpynb文件在import的时候都会报错
下载jpynb插件
Situation: Data Structure and Algorithms
509用哈希表library的时候编码问题报错
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)
原因
- debug冒泡的时候发现当round = 1了程序不会进入if但是还是会直接执行if里面的bsort2???
- debug选择的时候发现,有时候即使列表里最后一个已经是最大,还是会被交换,比如会出现[3,3,1,4]被换成[3,4,1,3]的情况。反过去想循环原理,这肯定是因为我们循环了j in range(round)找最大值的时候,没有比到最后一项,找的最大值是前3项最大值。
- 其次看exchange这个bool有没有问题,它代表的含义是是否要继续对比,也就是排序是否完全排好,在compare的过程中是每一项都和max进行了compare的,但凡有一次max没更新,也就是发现后面还有更小值的情况,就说明还要继续,如果全程max一直更新到最后一位,说明已经排好了exchange继续等于false。这里exchange位置正确。
解决措施
- 递归的内容不正确,这里没法从list的size进行递归,最小问题也不是list只有1/2项的时候,最小问题是exchange = 0,监测到list已经排好序不需要排序了。于是更小问题依次是排1次序,排2次序。最小问题不用操作,只用写次规模问题,先进行一次排序,再扔到函数里看是否排好。
- 改一下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)])
- 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
- m[(i, w)] = max(m(i - 1, w), m(i - 1, w - lastW) + lastV) TypeError: 'dict' object is not callable
- lastW = treasure[i]['w'] IndexError: list index out of range
原因
- 第一个不太明显,报错报的是range里只能放integer,实际虽然是maxW+1,但是是第一个range的地方括号打到了最后……,变成一整个range都是i的。
- m是dict,不能直接用dict(key)来call,要用dict[(key)],这里没有打方括号
- 在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))
- 第一个if:TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'
- 输入增量,跑得巨慢
- 输出答案是错的
otherCoins = 1 + change2(money-i,coins,results)
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
原因
- return放到第一个if里面以后,当我们遇到小于0的输入的时候,就没有return啦,在min里面就变成NoneType互相比较大小,系统搞不懂的!
- 对于小于0的输入,默认输出的是0,比较的时候当然最小了,但事实明显不是这样
- 结果要做数值计算的时候,递归函数一定要有return的实值,否则没法计算
解决措施
- 把return result dedent就可以bug free了
- 但是整个程序循环结构很烂,第一result默认返回的应该是worst scenario,就是只能用1找零的最大值。第二进if第二个else的条件应该是coin里面的值小于money的时候。第三,既然第二已经这样了,min里面不永远是4个变量比较,而是只有硬币面值小于money的函数比较。循环结构条件需要重写
- 特别慢的原因是用了递归就算了,还在一个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))
- solution1全是false
- d.removeRear() != d.removeFront() IndexError: pop from empty list
原因
- solution2里面的for循环限制没对,一开始dsize是word里全部字母数,但对消的次数只有一半
- 试了不止半个小时才发现,Deque的本质是class,不是列表。if order == reverse比较的是类的两个实例,暂时不知道比较instance背后是什么机制,可能是class的地址?反正这里比出来不相等了。我们在创建Deque的时候,初始化建了一个内部变量item才是列表
解决措施
- 把range改成
len(word)//2
注意是整除,否则报错TypeError: 'float' object cannot be interpreted as an integer
- 把solution1里面的判等改成items
- 很明显,第一个我自己想的方法更占空间
# 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))
- 第一次运行会导致从空列表里pop,是因为if不合理
- waitRecord += currentTask.waitTime(currentSecond) TypeError: 'int' object is not iterable
原因
- 第一次如果random没有generate出task,taskqueue就是空的,此时打印机不忙,程序想让queue里pop一个任务出来给打印机,所以出现dequeue失败
- waitrecord是列表不是字符串,所以不能简单用数值加减数字,要用自带函数append或者pop(或者之前讲过的四种生成方法)。这里除非把后面要加进去的变量变成列表,但是注意这样concat操作了n+k次(因为是复制到新列表),复杂度更大。
waitRecord += [currentTask.waitTime(currentSecond)]
这样写其实也可以
解决措施
- 在判断是否要给打印机新任务那里,要加一个打印列表不空的条件。同时tick函数不用放在else后面,因为tick是在打印机忙的情况下才操作,在打印机空的时候运行无伤大雅
- 向waitrecord列表增加data改成append
- 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)
- for i in N TypeError: 'int' object is not iterable
- 在while counter里面死循环
- 没有输出结果
- out的序列打不出来
原因
- 不能 for 变量 in 数字,后者必须是range。而且注意range(n)打印的是0到n-1,range(a,b)也是左闭右开
- while循环条件是counter,但是while里面居然没有counter的值改变。。。
- 循环完一局,counter=k有人out了,总人数减1,继续数,counter没有清零
- 注意结果要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'
原因
- 破罐破摔法改造:流程没问题,把token的运算符对应到计算的具体操作也没有问题,主要问题在于,最后一个else的时候,遇到数字push进去的是string,没法做前面所有if的运算。
- code没有硬伤,但简洁性还有问题,选择分支if语句太多,可以额外做一个function出来,以及pop()出现太多次(每一个if里都有),可以在进入分之前先给变量。
- 遇到除法和减法的时候,运算顺序和pop出来的顺序是相反的!!
解决措施
- 最简单的改法:直接在我的程序上else里的token加上int(token)
- 改进原则还是把数字放到最后的else里push,因为很难找到条件判断进来的token是数字?把那一堆if放到另一个函数里,把前面所有if改成先pop出两个数
- 第一个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)
报错语句:
- token = tokenList[index]IndexError: list index out of range
- key error:‘a'
原因
- 比较stack最后一个项和刚遇到的符号优先级的时候,还要加上一个栈非空的条件
- 因为字典里没有字母作为key可以查,所以到了比较的那一步,遇到stack现存最后一个数据项是字母,就进行不下去。 →结果发现字母为什么会在stack里!!!字母明明直接输出到post,所以最后一个else那里不该是push
- 循环把变量放进函数做传参的时候,只能用exec函数,否则就会产生一群字符串而非变量
- split到tokenlist没法成功,每一次实际上是把一整个字符串放在了token里。试了半天又去看split函数的使用方法,才发现对字符串进行split操作必须要有分割符,默认是空符。也就是说我们的test必须要用空格隔开。。。
解决措施
- 不用join输出了,直接把post全部当成字符串。一开始创建list,用append添加,最后join输出也是一种方法。
- 不用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
原因
- 检查debug发现生成的s栈无休止小数,是num除以二的时候,和c不一样,python不默认整除
- 输出循环不应该用for i in s,因为输出直接用pop,停止的标记是stack是否为空,和i没有关系的
- 用错了函数
divmod
,该函数不是返回余数,而是返回数组(a // b, a % b)
,当然数组push进栈是不会报错的。返回余数直接用%
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程序卡死
303Stack判断括号match的时候push传参数量出错
Situation: Code Jam to I/O
2020不平衡秤很多错
报错内容
- position = int(input().split()) TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
- TypeError: unsupported operand type(s) for -: 'str' and 'int'
- 加入map函数以后: current_no = position[i] TypeError: 'map' object is not subscriptable
- 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))
原因
- position是一个list,输入的string被split以后也是list,这没问题,但是这个list里每个元素是string,int不能作用在整个list里
- 忘记N的输入要作为integer形式
- map在py3里返回的是映射器!!调用debug会发现position被传的值是
<map object at 0x104cbecf8>
- 空列表没有长度,直接调用result[4]会出现溢出。创建空列表以后,current_no那里还应该-1,因为数字对应到列表的位置包括0要-1,否则还是会溢出。
- 全部debug以后,输出出现空字符,是因为for range那里,遍历permutation的时候,是从index N-1到0,是应该包括0的,所以range改成-1。其次,输出格式不是string是list,是因为str()函数直接把list的所有东西变成string,应该用join函数
解决措施
- 尝试用map修改position的定义,并且在map前面强制list
- 调用imbalance的时候input强制int
- 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))
原因
- c++里定义变量才用int,python不用
- 不能三个变量一起初始化
- 只有O匹配到I的时候才IO++,o匹配I的时候不用
解决措施
- 修改变量定义
- 删除第二个
IO += 1
Situation: CFD project
pandas read csv问题
pip3 install了以后pycharm显示不存在
Situation:NNDL project
Situation: Machine Learning
Jupyter notebook Non-unique cell id
“pastadom”???? Accessing dict with non-existent keyword
Access Dataframe slices
getting weights of wrong size in GD
copying data frame to change df values
plot labels can’t print greek symbols like theta in python
Problem with operating with list in subtraction, print etc
Range doesn’t take in float numbers
Python Line break continuation wrapping codes
for in range() miss the last trail!
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.
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
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
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
passing multiple paras through list
index out of range when deleting elements in list
no directory when Using stopwords
multi-dim list wrapped output
nltk package download
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 it’s a server problem https://stackoverflow.com/questions/38511673/cannot-quit-jupyter-notebook-server-running
if not this is my post
yaml install issue
folder exit error and overwrite
torch cosine similarity dim for matrix(64, 160)
Can’t reshape list object
Situation: General Pycharm Usage
change python ver within conda env
Navigating into and out of functions, switching between cursor positions
Situation:AVN
args parser in jupyter
jupyternotebook: using shell scripts
changing batch size using /
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
Cause
float type mismatch caused this, maybe some version of scipy, cython, python automatically solve this, but not python 3.11 and scipy 1.10
Solution
convert your numpy array into .astype(np.float64)
[BUG] No matching signature found when using fused types to write generic numpy code
Updated Apr 26, 2023
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 thischecking all attributes of a class
To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir().
only attributes:
model.__dict__.keys() or values()
A lot of import issues are usually dependency version’s problem
Situation:Jupyter Notebook
switching conda envs inside notebook page
method 1:
First install this in your base env:
conda install -n base nb_conda_kernels
The prerequisite is to install ipykernel inside the env you wanna show up in notebook:
conda install -n r_env r-irkernel
Method2:
Go inside the env you want and do:
conda install -c anaconda ipykernel
Then do:
python -m ipykernel install --user --name=firstEnv
In this case if you wanna delete them