Solution() takes no arguments何解?

站内站外找到的解答都是关于__init__()写错了的问题。可是我没用__init__()啊。求大神指教我错在哪里了???
这是leetcode上的45题,看的别人的答案,在leetcode上能运行出来,自己在jupyter book上就运行不出来了(加了最后2句)。

from typing import List

class Solution:
    def jump(self, nums: List[int]) -> int:
        counter = 0  # 移动次数
        curr_end = 0  # 当前跳跃的终点
        curr_farthest = 0  # 最远位置的下标
        for i in range(len(nums) - 1):
            curr_farthest = max(curr_farthest, i + nums[i])
            if i == curr_end:
                counter += 1
                curr_end = curr_farthest
        return counter

a = Solution([2,3,1,1,4])
print(a.jump())

报错信息如下
TypeError Traceback (most recent call last)
in
13 return counter
14
---> 15 a = Solution([2,3,1,1,4])
16 print(a.jump())

TypeError: Solution() takes no arguments

2个回答

直接类名加括号调用的就是__init__函数,别人一看你这个错就知道是跟__init__有关才会那么说。
你都写了是jump函数传入这个数组,为什么还要直接用Solution调用呢。
这样写

a = Solution()
print(a.jump([2,3,1,1,4]))

出问题的时候自己检查,语言、编译环境和网站不会犯这种低级错误的

qq_43804897
狗正八 啊!小白在此多谢大佬!!!
3 个月之前 回复

这说得很清楚了,solution 这个函数定义的参数个数和你调用的参数个数不同,你要么让函数不要参数,要么调用的时候加上参数

qq_43804897
狗正八 谢谢您! 再请教一下:如果最后2句写成1句 print(Solution.jump([2,3,1,1,4])) 与写成 print(Solution().jump([2,3,1,1,4]));前者报错“TypeError: jump() missing 1 required positional argument: 'nums'”;后者运行正确。请问者背后的区别是什么?
3 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Python 3.7 使用sorted()函数对列表进行不区分大小写排序时出现TypeError: lower() takes no arguments (1 given)
在使用sorted()函数做练习时,分别定义了两个函数ording1()和ording2(),区别是ording1()中用于排序的列表是通过split()函数生成的,ording2()函数中的列表是直接用的字面值。最终都是使用sorted(str_list, key=str.lower) 函数对 list进行排序,执行ording2()时,系统正常输出,但是执行以ording1()时却遇到了以下错误信息:TypeError: lower() takes no arguments (1 given),不太理解这是什么原因导致的。 ``` def ording1(): str = "This is a test string from Andrew" str_list = str.split() print(type(str_list)) print(str_list) print(sorted(str_list, key=str.lower)) def ording2(): str_list = ['This', 'is', 'a', 'test', 'string', 'from', 'Andrew'] print(type(str_list)) print(str_list) print(sorted(str_list, key=str.lower)) ``` 执行ording1()函数时出现以下错误 ``` print(sorted(str_list, key=str.lower)) TypeError: lower() takes no arguments (1 given) ``` 执行ording1()函数时,显示正常 ``` <class 'list'> ['This', 'is', 'a', 'test', 'string', 'from', 'Andrew'] ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] ```
Python, TypeError: APP() takes no arguments
``` import tkinter as tk class APP(): def _init_(self,master): frame = tk.Frame(master) frame.pack(side = tk.LEFT, padx = 10, pady = 10) self.hi_there = tk.Button(frame,text = "打招呼", bg = 'black',fg = 'white',command = self.say_hi) self.hi_there.pack() def say_hi(self): print("hello everyone") root = tk.Tk() app = APP(root) root.mainloop() ``` 报错信息如下: Traceback (most recent call last): File "D:/py/AboutExcel/Tkinter_4.py", line 17, in <module> app = APP(root) TypeError: APP() takes no arguments Process finished with exit code 1
在ubuntu配置apache2出现LoadModule takes two arguments
我打开apache2.conf,里面LoadModule后面是没有东西的。。。我也不知道该加一些什么。。求大神帮助! ``` Output of config test was: apache2: Syntax error on line 223 of /etc/apache2/apache2.conf: LoadModule takes two arguments, a module name and the name of a shared object file to load it from Action 'configtest' failed. The Apache error log may have more information. ```
error_message:insertMysqlseghist() takes 4 positional arguments but 5 were given
从oracle获取数据插入mysql的脚本,大神帮忙看一下代码哪里有问题 sql语句:Insert_dblinkSql = insert into kt_collectoracle (owner,db_link,username,host,created) values ('%s','%s','%s','%s','%s') def insertMysqlseghist(self,oracleDatadb,oracleDatacur,OracleDataTuple): for OracleData in OracleDataTuple: try: oracleDatacur.execute(self.Insert_dblinkSql%(OracleData[0], OracleData[1],OracleData[2],OracleData[3],OracleData[4])) oracleDatadb.commit() except Exception as e: oracleDatadb.rollback() logger_data_message.debug('error: '+str(e)+'\n') ``` ```
R语言 分层抽样函数strata报错: 'match' requires vector arguments?
小白求教大神 是这样的,我有7376条数据,因为太多所以需要分层抽样。 构思是按照序号由小到大每六个为一组进行随机抽样。 为了简化数据,我制作了只包含顺序和分组信息的txt。截图如下![图片说明](https://img-ask.csdn.net/upload/202001/02/1577949502_854870.jpg) 按照教程,这是我写的代码 ```setwd("E:/newR/sampling") library(sampling) library(data.table) sampling <- as.matrix(fread("sampling.txt",header = TRUE,sep = "\t",encoding = "UTF-8")) n=round(nrow(sampling)/6) strata.1 <- strata(data = sampling,stratanames=sampling[,2],size=rep(n,6),method=srswor) 结果系统报错 Error in match(x, table, nomatch = 0L) : 'match' requires vector arguments ``` 后来用as.vector进行了数据变换还是不行。 求教各位大神,不胜感激
Django在运行时出现Reverse for 'xxx' with no arguments not found.
本人刚学Django,这是一个临时程序,本来想实现通过url查找用户信息,并且在代码片段中添加了跳转链接 urls.py ``` from . import views from django.conf.urls import url, include urlpatterns = [ url(r'^$',views.index,name='index'), url(r'^(?P<name_id>\d+)/$',views.names,name='names'), ] ``` views.py ``` from django.shortcuts import render from .models import Name # Create your views here. def index(request): name = Name.objects.all() context = {'names':name} return render(request,'index.html',context) def names(request, name_id): name = Name.objects.get(id=name_id) context = {'name':name} return render(request,'names.html',context) ``` index.py ``` <p>INDEX</p> <!--这里想通过无序列表将用户名列出来--> <ul> {% for name in names %} <!--本来想在此处插入跳转链接的,但是出错--> <li><a href="{% url 'testing:names' %}">{{ name }}</a></li> {% empty %} <li>NOTHING HERE</li> {% endfor %} </ul> ``` 以上就是主要的代码 报错如下:
Lazy Evaluation 怎么实现
Problem Description Most of the programming languages used in practice perform strictevaluation. When a function is called, the expressions passed in the function arguments (for instance a + b in f (a + b, 3)) are evaluated first,and the resulting values are passed to the function. However, this is not the only way how expressions can be evaluated, and in fact, even such a mainstream language as C++ is sometimes performing lazy evaluation: the operators && and jj evaluate only those arguments that are needed to determine the value of the expression. Pal Christian is now working on a comparative study of the performance of the lazy and strict evaluation. Pal wants to evaluate in both ways a set of expressions that follow this simplied syntax: --an expression is either a constant, a name, or a function call --a constant is a signed 32-bit integer; for example, 3, 0, -2, 123 are constants; --a name is a name of a built-in or user-dened function, for example, f , or add are names; names are words containing up to 32 lowercase letters from the English alphabet; --function call has the form: ( f unction arg1 . . . argN ), where f unction is an expression that evaluates to some function of N arguments, and arg1 . . . argN are expressions that evaluate to arguments passed to the function. For example, ( f 3 5 ) , or ( add 2 ( add 1 2 )) are valid function calls. Expressions are evaluated according to the following simple rules: --constants evaluate to themselves --names evaluate to the functions they denote --function calls: in lazy evaluation: the first expression is evaluated first to obtain a function, whose function body, with formal parameters substituted for the expressions provided as the arguments, is evaluated; however, whenever some argument gets evaluated while evaluating the function body, the resulting value will replace all occurences of the same parameter in that function body. In other words, the expression passed in the argument is never evaluated more than once. in strict evaluation: all expressions are evaluated first: the first expression should evaluate to a function, the remaining to values that are used as function arguments; the result is the result of evaluating the corresponding function body, where all occurences of formal parameters are replaced by the values obtained by evaluating the arguments. The following built-in functions are available: add x y - sum of the constants x and y, sub x y - returns the value x-y, mult x y - product of x and y, div x y - integer division, and rem x y - remainder (same semantics as '/' and '%' in C, C++ or Java), true x y - always returns x, f alse x y - always returns y , eq x y - returns true if x and y is the same constant, otherwise returns f alse, gt x y - returns true if x is greater than y, otherwise returns f alse. User-defined functions are defined using the following syntax: f unction name arg1 . . . argN = body, where arg1 . . . argN are distinct words (up to 32 English lowercase letters), denoting the formal parameters of the function, and the body is an expression. The formal parameters can occur in the body of the function in place of constants or names. The function name and the formal parameters are separated by a single space. There is one space on both sides of the "=". Functions with zero (no) rguments are legal. Note that the formal parameters can overshadow the function names (i.e. op in definition of not in sample input overshadows the function name op), but each function must have a unique name. Input The first part of the input contains (less than 1000) lines with one function denition each, followed by a single empty line. Forward references (that is, referring to functions dened later in the input) and recursion are legal. The second part of the input contains less than 1000 test expressions. Each test expression is an expresion occupying a single line. Function names and the arguments are always separated by a single space, but there are no extra spaces around parentheses (see sample input). There is an empty line after the last expression. Expressions are to be evaluated by both the lazy and the strict evaluation. You can assume that all function definitions and expressions are syntactically correct, and that the arithmetic built-in functions (add, sub, mult, div, rem, eq, gt) will always be called with integers only, and no division by 0 occurs. Overows outside the 32-bit integer range are legal and do not require any special treatment (just use the value produced by C, C++, or Java operators +, -, *, /, or %). In strict evaluation, built-in functions evaluate all their arguments too. In lazy evaluation, arithmetic built-in functions always evaluate all their arguments. All lines on the input contain no more than 255 characters including spaces. Output The program should produce a table in exactly the following format: operator lazy_evaluation strict_evaluation add addlazy addstrict sub sublazy substrict mult multlazy multstrict div divlazy divstrict rem remlazy remstrict where each is an integer - how many times op has been executed in lazy evaluation of all expressions, and is the number of evaluations of in strict evaluation. Spaces can occur arbitrarily. If the evaluation of a test expression does not terminate after a total of 2345 function evaluations , you can assume that it is in an innite loop, the program should skip that expression, and do not count it into the totals (omit counting operations both in lazy and strict evaluation of this expression). Sample Input if cond truepart elsepart = (cond truepart elsepart) fact x = (facta x 1) facta x a = (if (eq x 0) a (facta (sub x 1) (mult a x))) and x y = (x y false) ident x = x two = 2 op op x = ((if (eq op 1) add sub) op x) not op = (op false true) sum n = (suma n 0) suma n a = (((gt n 1) suma false) (sub n 1) (add a n)) (true (add 1 2) (mult 1 2)) 5 true (and (gt (op (sub 2 1) 1) 5) (eq (two) (op 1 1))) (false (sub 1 2) (sum 4)) ((eq (true 1 2) (false 2 1)) (add 1 2) (sub 1 2)) (fact 3) Sample Output operator lazy_evaluation strict_evaluation add 7 8 sub 4 7 mult 0 1 div 0 0 rem 0 0
function takes at least 2 arguments(1 given)
机器学习实战kNN篇手写数字识别: ``` def img2vector(filename): file=open(filename) imgvector=zeros((1,1024)) for i in range(32): line=file.readline() for j in range(32): imgvector[0,32*i+j]=int(line[j]) return imgvector def handwritingClassifier(): hwlabels=[] trainingfilelist=listdir('trainingDigits') m=len(trainingfilelist) trainingMat=zeros((m,1024)) for i in range(m): fn=trainingfilelist[i] filename1=fn.split('.')[0] filelabel=int(filename1.split('_')[0]) hwlabels.append(filelabel) trainingMat[i,:]=img2vector('trainingDigits/%s' % fn) testfilelist=listdir('testDigits') mT=len(testfilelist) errorCount=0.0 for i in range(mT): filenameT=testfilelist[i] filename1T=filenameT.split('.')[0] filelabelT=int(filename1T.split('_')[0]) testfilevector=img2vector('testDigits/%s' % filenameT) predictlabel=Classifier(testfilevector,trainingMat,hwlabels,5) if (predictlabel!=filelabelT): errorCount+=1.0 print "the classifier came back with %d ,the real answer is %d " % (predictlabel,filelabelT) print "the error rate is %f" % (errorCount/float(mT)) ``` 结果在命令行输入import kNN ...kNN.handwritingClassifier()的时候 TypeError Traceback (most recent call last) <ipython-input-1-b18521761a29> in <module>() 1 import kNN ----> 2 kNN.handwritingClassifier() C:\Users\Administrator\kNN.py in handwritingClassifier() 99 filelabel=int(filename1.split('_')[0]) 100 hwlabels.append(filelabel) --> 101 trainingMat[i,:]=img2vector('trainingDigits/%s' % fn) 102 testfilelist=listdir('testDigits') 103 mT=len(testfilelist) C:\Users\Administrator\kNN.py in img2vector(filename) 81 82 def img2vector(filename): ---> 83 file=open(filename) 84 imgvector=zeros((1,1024)) 85 for i in range(32): TypeError: function takes at least 2 arguments (1 given) 小白一枚,请问到底哪里有问题,open函数不是只要一个参数吗,用的是python2.7望指教!!
TypeError: Triangle_2D_3Node_Stiffness() missing 2 required positional arguments: 'j' and 'm'。i,j, m为单元节点坐标,e为单元序号。求大神指导???
def Triangle_2D_3Node_Stiffness(E,mu,t,xy,i,j,m,): """ FUNC: this function calculates the element stiffness matrix for a 2D 3 nodes plane element PARA: E -Young's modulus mu -Poisson's ratio t -thick of plate xy -locations of nodes, eg.[(x1,y1),(x2,y2),(x3,y3)] ID -1 for plane stress, 2 for plane strain """ (xi,yi),(xj,yj),(xm,ym) = xy_e A_e = (xi*(yj-ym) + xj*(ym-yi) + xm*(yi-yj))/2 ai, aj, am = xj*ym - xm*yj, xm*yi - xi*ym, xi*yj - xj*yi bi, bj, bm = yj-ym, ym-yi, yi-yj ci, cj, cm = xm-xj, xi-xm, xj-xi B = np.mat([ [bi, 0, bj, 0, bm, 0], [ 0, ci, 0, cj, 0, cm], [cj, bi, cj, bj, cm, bm] ])/(2*A) D = (E/(1-mu**2))*np.mat([ [ 1, mu, 0], [mu, 1, 0], [ 0, 0, (1-mu)/2] ]) k_e = t*A*np.transpose(B)*D*B return k
too few arguments for variable template "set"
```#include<iostream> #include<cstdio> #include<algorithm> #include<set> using namespace std; const int maxn=200000+5; int a[maxn],f[maxn],g[maxn]; struct candidate{ int a,g; candidate(int a,int g):a(a),g(g){} bool operator < (const candidate& rhs) const{ return a<rhs.a; } }; set<candidate > s; //以下省略 ``` vs中编译报错:too few arguments for variable template "set" 使用map 《int,int 》m;时也报错:too few arguments for variable template "map" 已经包含了头文件的情况下也报错,且编译运行失败。 请问是什么原因以及如何解决?
TensorFlow初始化一个权重矩阵时报了这个错误,想请教一下大家是怎么回事
ValueError: You can only pass an initializer function that expects no arguments to its callable when the shape is not fully defined. The given initializer function expects the following args ['self', 'shape', 'dtype', 'partition_info']
Polish notation 程序的编写
Problem Description Reverse Polish notation (RPN) is a method for representing expressions in which the operator symbol is placed after the arguments being operated on. Polish notation, in which the operator comes before the operands, was invented in the 1920s by the Polish mathematician Jan Lucasiewicz. In the late 1950s, Australian philosopher and computer scientist Charles L. Hamblin suggested placing the operator after the operands and hence created reverse polish notation. RPN has the property that brackets are not required to represent the order of evaluation or grouping of the terms. RPN expressions are simply evaluated from left to right and this greatly simplifies the computation of the expression within computer programs. As an example, the arithmetic expression (3+4)*5 can be expressed in RPN as 3 4 + 5 *. Reverse Polish notation, also known as postfix notation, contrasts with the infix notation of standard arithmetic expressions in which the operator symbol appears between the operands. So Polish notation just as prefix notation. Now, give you a string of standard arithmetic expressions, please tell me the Polish notation and the value of expressions. Input There're have multi-case. Every case put in one line, the expressions just contain some positive integers(all less than 100, the number of integers less than 20), bi-operand operators(only have 3 kinds : +,-,*) and some brackets'(',')'. you can assume the expressions was valid. Output Each case output the Polish notation in first line, and the result of expressions was output in second line. all of the answers are no any spaces and blank line.the answer will be not exceed the 64-signed integer. Sample Input 1+2-3*(4-5) 1+2*(3-4)-5*6 Sample Output Case 1: - + 1 2 * 3 - 4 5 6 Case 2: - + 1 * 2 - 3 4 * 5 6 -31
python中报TypeError: __init__() missing 2 required positional arguments: 'url' and 'method'
demo1.py代码如下: import requests class RunMain: def __init__(self,url,method,data=None): self.res = self.run_main(url,method,data) def send_get(self,url,data): res = requests.get(url=url,data=data) return res.json() def send_post(self,url,data): res = requests.post(url=url,data=data) return res.json() def run_main(self,url,method,data=None): res = None if method == 'GET': res = self.send_get(url,data) else: res = self.send_post(url,data) return res if __name__ == '__main__': url = 'http://www.imooc.com/m/web/shizhanapi/loadmorepingjia.html' data = { 'cart': '11' } run = RunMain(url,'GET',data) print(run.res) test_method1.py代码如下: #coding = utf-8 import unittest from demo1 import RunMain class TestMethod(unittest.TestCase): def setUp(self): self.run = RunMain() def test_01(self): url = 'http://coding.imooc.com/api/cate' data = { 'timestamp': '1507034803124', 'uid': '5249191', 'uuid': '5ae7d1a22c82fb89c78f603420870ad7', 'secrect': '078474b41dd37ddd5efeb04aa591ec12', 'token': '7d6f14f21ec96d755de41e6c076758dd', 'cid': '0' } res = self.run.run_main(url,'POST',data) print(res) def test_02(self): url = 'http://coding.imooc.com/api/cate' data = { 'timestamp': '1507034803124', 'uid': '5249192', 'uuid': '5ae7d1a22c82fb89c78f603420870ad7', 'secrect': '078474b41dd37ddd5efeb04aa591ec12', 'token': '7d6f14f21ec96d755de41e6c076758dd', 'cid': '0' } res = self.run.run_main(url,'POST',data) print(res) if __name__ == '__main__': unittest.main(url,method) 但是报如下错误: Error Traceback (most recent call last): File "E:\MyLeaning\Python36-32\lib\unittest\case.py", line 59, in testPartExecutor yield File "E:\MyLeaning\Python36-32\lib\unittest\case.py", line 601, in run self.setUp() File "D:\www\ImoocInterface\base\test_method1.py", line 7, in setUp self.run = RunMain() TypeError: __init__() missing 2 required positional arguments: 'url' and 'method' ``` ```
springboot绑定数据错误,希望大牛帮帮小白
### 在使用springboot从前端绑定数据的时候,出现如下错误 **图片如下** ![图片说明](https://img-ask.csdn.net/upload/201912/22/1577012041_526179.png) **内容如下:** ``` There was an unexpected error (type=Bad Request, status=400). Validation failed for object='mainCategory'. Error count: 1 org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'mainCategory' on field 'subCategories': rejected value [[SubCategory{id=1, name='课后作业'}, SubCategory{id=2, name='实验报告'}, SubCategory{id=3, name='课堂课件'}]]; codes [typeMismatch.mainCategory.subCategories,typeMismatch.subCategories,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [mainCategory.subCategories,subCategories]; arguments []; default message [subCategories]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'subCategories'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.zjq.hbut.csdn.entity.SubCategory' for property 'subCategories[0]': no matching editors or conversion strategy found] ``` ## **前端代码如下** ``` <form action="" class="ui form" th:object="${mainCategory}" th:action="*{id}==null ? @{/admin/type/add}:@{/admin/type/add/{id}(id=*{id})}" method="post"> <input type="hidden" name="id" th:value="*{id}"> <input type="hidden" name="subCategories" th:value="*{subCategories}"> <div class="required field"> <div class="ui left labeled input"> <label class="ui teal basic label">名称</label> <input type="text" name="name" placeholder="名称..." th:value="*{name}"> </div> </div> <div class="ui right aligned container"> <!--onclick事件返回上一个页面--> <button type="button" class="ui button" onclick="window.history.go(-1)">返回</button> <button class="ui teal submit button">提交</button> </div> </form> ``` ## **后端Controller代码如下** ``` @PostMapping({"/type/add","/type/add/{id}"}) public String add(@Valid MainCategory mainCategory, BindingResult result, @PathVariable(name = "id",required = false)Long id, @RequestParam(name = "subCategories") String subCategories, RedirectAttributes attributes) { if(imainCategoryService.getByName(mainCategory.getName())!=null) { result.rejectValue("name","nameError","该标签已存在"); } if(result.hasErrors()) { System.out.println(result.getAllErrors()); return "admin/type-input"; } if(id!=null&&id>0) {//修改 MainCategory update = imainCategoryService.update(mainCategory); if(update==null) { attributes.addFlashAttribute("message","更新成功"); }else { attributes.addFlashAttribute("message","更新失败"); } return "redirect:/admin/type"; }else { //新增 MainCategory save = imainCategoryService.save(mainCategory); if(save==null) { attributes.addFlashAttribute("message","保存成功"); }else { attributes.addFlashAttribute("message","保存失败"); } return "redirect:/admin/type"; } } ``` ## **实体类代码如下** ``` package com.zjq.hbut.csdn.entity; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "t_maincategory") public class MainCategory { @Id @GeneratedValue private Long id; private String name; @ManyToMany private List<SubCategory> subCategories=new ArrayList<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<SubCategory> getSubCategories() { return subCategories; } public void setSubCategories(List<SubCategory> subCategories) { this.subCategories = subCategories; } @Override public String toString() { return "MainCategory{" + "id=" + id + ", name='" + name + '\'' + ", subCategories=" + subCategories + '}'; } } ```
unity 取消电脑自动关机
public InputField inputField; public void OnClickOKBtn() { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = "/c " + "shutdown -s -t " + (int.Parse(inputField.text) * 60).ToString(); p.Start(); } public void OnClickCancelBtn() { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = "/c " + "shutdown -a"; } ``` OnClickOKBtn()是定时关机,OnclickCancelBtn却没办法取消。 ```
Finding Seats 的解答
Problem Description A group of K friends is going to see a movie. However, they are too late to get good tickets, so they are looking for a good way to sit all nearby. Since they are all science students, they decided to come up with an optimization problem instead of going on with informal arguments to decide which tickets to buy. The movie theater has R rows of C seats each, and they can see a map with the currently available seats marked. They decided that seating close to each other is all that matters, even if that means seating in the front row where the screen is so big it’s impossible to see it all at once. In order to have a formal criteria, they thought they would buy seats in order to minimize the extension of their group. The extension is defined as the area of the smallest rectangle with sides parallel to the seats that contains all bought seats. The area of a rectangle is the number of seats contained in it. They’ve taken out a laptop and pointed at you to help them find those desired seats. Input Each test case will consist on several lines. The first line will contain three positive integers R, C and K as explained above (1 <= R,C <= 300, 1 <= K <= R × C). The next R lines will contain exactly C characters each. The j-th character of the i-th line will be ‘X’ if the j-th seat on the i-th row is taken or ‘.’ if it is available. There will always be at least K available seats in total. Input is terminated with R = C = K = 0. Output For each test case, output a single line containing the minimum extension the group can have. Sample Input 3 5 5 ...XX .X.XX XX... 5 6 6 ..X.X. .XXX.. .XX.X. .XXX.X .XX.XX 0 0 0 Sample Output 6 9
knn猫狗识别算法中样本为0报错
错误如下: ValueError: With n_samples=0, test_size=0.25 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters. 代码如下: # import the necessary packages from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from pyimagesearch.preprocessing import SimplePreprocessor from pyimagesearch.datasets import SimpleDatasetLoader from imutils import paths import argparse # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-d", "--datasets", type=str, default="‪H:\\111\\try1\\pyimagesearch\\datasets\\animals\\", help="path to input dataset") ap.add_argument("-k", "--neighbors", type=int, default=1, help="# of nearest neighbors for classification") ap.add_argument("-j", "--jobs", type=int, default=-1, help="# of jobs for k-NN distance (-1 uses all available cores)") args = vars(ap.parse_args()) # grab the list of images that we’ll be describing print("[INFO] loading images...") imagePaths = list(paths.list_images(args["datasets"])) # initialize the image preprocessor, load the dataset from disk, # and reshape the data matrix sp = SimplePreprocessor.SimplePreprocessor(32, 32) sdl = SimpleDatasetLoader.SimpleDatasetLoader(preprocessors=[sp]) (data, labels) = sdl.load(imagePaths, verbose=500) data = data.reshape((data.shape[0], 3072)) # show some information on memory consumption of the images print("[INFO] features matrix: {:.1f}MB".format( data.nbytes / (1024 * 1000.0))) # encode the labels as integers le = LabelEncoder() labels = le.fit_transform(labels) # partition the data into training and testing splits using 75% of # the data for training and the remaining 25% for testing (trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.25, random_state=42) # train and evaluate a k-NN classifier on the raw pixel intensities print("[INFO] evaluating k-NN classifier...") model = KNeighborsClassifier(n_neighbors=args["neighbors"], n_jobs=args["jobs"]) model.fit(trainX, trainY) print(classification_report(testY, model.predict(testX), target_names=le.classes_)) ``` ```
python face_recognition库中使用其他的功能都可以正常运行,但只有用face_encodings会报错?
已正确安装dlib和face_recognition库 __代码如下:__ ``` import face_recognition face_recognition.face_encodings("F:/multi-media/video frames/260.png") ``` 报错如下: ``` PS F:\multi-media> & C:/Users/ONE7/AppData/Local/Programs/Python/Python37/python.exe "f:/multi-media/vedio analysis.py" Traceback (most recent call last): File "f:/multi-media/vedio analysis.py", line 118, in <module> face_recognition.face_encodings("F:/multi-media/video frames/260.png", known_face_locations=None, num_jitters=1) File "C:\Users\ONE7\AppData\Local\Programs\Python\Python37\lib\site-packages\face_recognition\api.py", line 209, in face_encodings raw_landmarks = _raw_face_landmarks(face_image, known_face_locations, model="small") File "C:\Users\ONE7\AppData\Local\Programs\Python\Python37\lib\site-packages\face_recognition\api.py", line 153, in _raw_face_landmarks face_locations = _raw_face_locations(face_image) File "C:\Users\ONE7\AppData\Local\Programs\Python\Python37\lib\site-packages\face_recognition\api.py", line 102, in _raw_face_locations return face_detector(img, number_of_times_to_upsample) TypeError: __call__(): incompatible function arguments. The following argument types are supported: 1. (self: dlib.fhog_object_detector, image: array, upsample_num_times: int=0) -> dlib.rectangles Invoked with: <dlib.fhog_object_detector object at 0x0000026A438B91B0>, 'F:/multi-media/video frames/260.png', 1 ```
android studio 导入github项目出错:startup failed
android studio 导入github项目出错:startup failed ![图片说明](https://img-ask.csdn.net/upload/201912/07/1575705839_965977.png) 点击open file,显示注释这行有错: ![图片说明](https://img-ask.csdn.net/upload/201912/07/1575705925_659514.png) 删除注释,就会有新错: ![图片说明](https://img-ask.csdn.net/upload/201912/07/1575706040_376828.png) 错误是这样: ``` ERROR: Could not find method buildscript() for arguments [build_d3qy2t3u4593rxqhf9sxz98oc$_run_closure1@4bd534b8] on root project 'MobileShop-prj06' of type org.gradle.api.Project. ``` 弄了好久真的没辙了,有大神能帮忙提点解决一下吗,感激不尽!!!!
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
有哪些让程序员受益终生的建议
从业五年多,辗转两个大厂,出过书,创过业,从技术小白成长为基层管理,联合几个业内大牛回答下这个问题,希望能帮到大家,记得帮我点赞哦。 敲黑板!!!读了这篇文章,你将知道如何才能进大厂,如何实现财务自由,如何在工作中游刃有余,这篇文章很长,但绝对是精品,记得帮我点赞哦!!!! 一腔肺腑之言,能看进去多少,就看你自己了!!! 目录: 在校生篇: 为什么要尽量进大厂? 如何选择语言及方...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
redis分布式锁,面试官请随便问,我都会
文章有点长并且绕,先来个图片缓冲下! 前言 现在的业务场景越来越复杂,使用的架构也就越来越复杂,分布式、高并发已经是业务要求的常态。像腾讯系的不少服务,还有CDN优化、异地多备份等处理。 说到分布式,就必然涉及到分布式锁的概念,如何保证不同机器不同线程的分布式锁同步呢? 实现要点 互斥性,同一时刻,智能有一个客户端持有锁。 防止死锁发生,如果持有锁的客户端崩溃没有主动释放锁,也要保证锁可以正常释...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
Python 编程开发 实用经验和技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法和技巧,包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等,会持续更新......
YouTube排名第一的励志英文演讲《Dream(梦想)》
Idon’t know what that dream is that you have, I don't care how disappointing it might have been as you've been working toward that dream,but that dream that you’re holding in your mind, that it’s po...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Java世界最常用的工具类库
Apache Commons Apache Commons有很多子项目 Google Guava 参考博客
相关热词 c# clr dll c# 如何orm c# 固定大小的字符数组 c#框架设计 c# 删除数据库 c# 中文文字 图片转 c# 成员属性 接口 c#如何将程序封装 16进制负数转换 c# c#练手项目
立即提问