leetcode

package
v1.4.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 4, 2024 License: MIT Imports: 37 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrPaidOnlyQuestion  = errors.New("this is paid only question, you need to subscribe to LeetCode Premium")
	ErrQuestionNotFound  = errors.New("no such question")
	ErrContestNotStarted = errors.New("contest has not started")
	ErrForbidden         = UnexpectedStatusCode{
		Code: 403,
		Body: "access is forbidden, your cookies may have expired or LeetCode has restricted its API access",
	}
	ErrTooManyRequests = UnexpectedStatusCode{
		Code: 429,
		Body: "LeetCode limited you access rate, you may be submitting too frequently",
	}
)

Functions

func ParseContestQID

func ParseContestQID(qid string, c Client, withQuestions bool) (*Contest, []*QuestionData, error)

Types

type CategoryTitle added in v0.1.6

type CategoryTitle string
const (
	CategoryAlgorithms  CategoryTitle = "Algorithms"
	CategoryDatabase    CategoryTitle = "Database"
	CategoryShell       CategoryTitle = "Shell"
	CategoryConcurrency CategoryTitle = "Concurrency"
	CategoryJavaScript  CategoryTitle = "JavaScript"
	CategoryAll         CategoryTitle = ""
)

type CheckResult

type CheckResult interface {
	Display(q *QuestionData) string
	GetState() string
}

type Client

type Client interface {
	BaseURI() string
	Inspect(typ string) (map[string]any, error)
	Login(username, password string) (*http.Response, error)
	GetUserStatus() (*UserStatus, error)
	GetQuestionData(slug string) (*QuestionData, error)
	GetAllQuestions() ([]*QuestionData, error)
	GetTodayQuestion() (*QuestionData, error)
	GetQuestionOfDate(date time.Time) (*QuestionData, error)
	GetQuestionsByFilter(f QuestionFilter, limit int, skip int) (QuestionList, error)
	GetQuestionTags() ([]QuestionTag, error)
	RunCode(q *QuestionData, lang string, code string, dataInput string) (
		*InterpretSolutionResult,
		error,
	)
	SubmitCode(q *QuestionData, lang string, code string) (string, error)
	CheckResult(interpretId string) (CheckResult, error)
	GetUpcomingContests() ([]*Contest, error)
	GetContest(contestSlug string) (*Contest, error)
	GetContestQuestionData(contestSlug string, questionSlug string) (*QuestionData, error)
	RegisterContest(slug string) error
	UnregisterContest(slug string) error
}

func NewClient

func NewClient(cred CredentialsProvider) Client

type CodeSnippet

type CodeSnippet struct {
	LangSlug string `json:"langSlug"`
	Lang     string `json:"lang"`
	Code     string `json:"code"`
}

type Contest

type Contest struct {
	Id              int
	TitleSlug       string
	Title           string
	StartTime       int64
	OriginStartTime int64
	Duration        int
	Description     string
	Questions       []*QuestionData
	Registered      bool
	ContainsPremium bool
	IsVirtual       bool
	// contains filtered or unexported fields
}

func (*Contest) GetAllQuestions

func (ct *Contest) GetAllQuestions() ([]*QuestionData, error)

func (*Contest) GetQuestionByNumber

func (ct *Contest) GetQuestionByNumber(num int) (*QuestionData, error)

func (*Contest) GetQuestionNumber

func (ct *Contest) GetQuestionNumber(slug string) (int, error)

func (*Contest) HasFinished

func (ct *Contest) HasFinished() bool

func (*Contest) HasStarted

func (ct *Contest) HasStarted() bool

func (*Contest) Refresh

func (ct *Contest) Refresh() error

func (*Contest) TimeTillStart

func (ct *Contest) TimeTillStart() time.Duration

type CredentialsProvider

type CredentialsProvider interface {
	AddCredentials(req *http.Request) error
}

func NewBrowserAuth

func NewBrowserAuth(browsers []string) CredentialsProvider

func NewCookiesAuth

func NewCookiesAuth(session, csrftoken, cfClearance string) CredentialsProvider

func NewPasswordAuth

func NewPasswordAuth(username, passwd string) CredentialsProvider

func NonAuth

func NonAuth() CredentialsProvider

func ReadCredentials added in v1.3.1

func ReadCredentials() CredentialsProvider

type EditorType added in v1.3.1

type EditorType string
const (
	EditorTypeCKEditor EditorType = "CKEDITOR"
	EditorTypeMarkdown EditorType = "MARKDOWN"
)

type InterpretSolutionResult

type InterpretSolutionResult struct {
	InterpretExpectedId string `json:"interpret_expected_id"`
	InterpretId         string `json:"interpret_id"`
	TestCase            string `json:"test_case"`
}

type JsonExampleTestCases

type JsonExampleTestCases []string

func (*JsonExampleTestCases) UnmarshalJSON

func (j *JsonExampleTestCases) UnmarshalJSON(data []byte) error

type MetaData

type MetaData struct {
	Name   string          `json:"name"`
	Params []MetaDataParam `json:"params"`
	Return *MetaDataReturn `json:"return"`
	Output *MetaDataOutput `json:"output"`
	// System design problems related
	SystemDesign bool                `json:"systemdesign"`
	ClassName    string              `json:"classname"`
	Constructor  MetaDataConstructor `json:"constructor"`
	Methods      []MetaDataMethod    `json:"methods"`
	Manual       bool                `json:"manual"`
}

func (*MetaData) NArg added in v1.3.1

func (m *MetaData) NArg() int

func (*MetaData) ResultType added in v1.3.1

func (m *MetaData) ResultType() string

func (*MetaData) UnmarshalJSON

func (m *MetaData) UnmarshalJSON(data []byte) error

type MetaDataConstructor

type MetaDataConstructor struct {
	Params []MetaDataParam `json:"params"`
}

type MetaDataMethod

type MetaDataMethod struct {
	Name   string          `json:"name"`
	Params []MetaDataParam `json:"params"`
	Return MetaDataReturn  `json:"return"`
}

type MetaDataOutput added in v0.2.1

type MetaDataOutput struct {
	ParamIndex int `json:"paramindex"`
}

type MetaDataParam

type MetaDataParam struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

type MetaDataReturn

type MetaDataReturn struct {
	Type string `json:"type"`
	// Size    *int   `json:"size"`
	// ColSize *int `json:"colsize"`
	Dealloc bool `json:"dealloc"`
}

type NeedClient

type NeedClient interface {
	SetClient(c Client)
}

type Options

type Options struct {
	// contains filtered or unexported fields
}

type QuestionData

type QuestionData struct {
	TitleSlug            string               `json:"titleSlug"`
	QuestionId           string               `json:"questionId"`
	QuestionFrontendId   string               `json:"questionFrontendId"`
	CategoryTitle        CategoryTitle        `json:"categoryTitle"`
	Title                string               `json:"title"`
	TranslatedTitle      string               `json:"translatedTitle"`
	Difficulty           string               `json:"difficulty"`
	TopicTags            []TopicTag           `json:"topicTags"`
	IsPaidOnly           bool                 `json:"isPaidOnly"`
	Content              string               `json:"content"`
	TranslatedContent    string               `json:"translatedContent"`
	Status               string               `json:"status"` // "ac", "notac", or null
	Stats                Stats                `json:"stats"`
	Hints                []string             `json:"hints"`
	SimilarQuestions     SimilarQuestions     `json:"similarQuestions"`
	SampleTestCase       string               `json:"sampleTestCase"`
	ExampleTestcases     string               `json:"exampleTestcases"`
	JsonExampleTestcases JsonExampleTestCases `json:"jsonExampleTestcases"`
	ExampleTestcaseList  []string             `json:"exampleTestcaseList"`
	MetaData             MetaData             `json:"metaData"`
	CodeSnippets         []CodeSnippet        `json:"codeSnippets"`
	EditorType           EditorType           `json:"editorType"`
	// contains filtered or unexported fields
}

func ParseQID

func ParseQID(qid string, c Client) ([]*QuestionData, error)

func QuestionBySlug

func QuestionBySlug(slug string, c Client) (*QuestionData, error)

QuestionBySlug loads question data from cache first, if not found, fetch from leetcode.com

func QuestionFromCacheByID

func QuestionFromCacheByID(id string, c Client) (*QuestionData, error)

func QuestionFromCacheBySlug

func QuestionFromCacheBySlug(slug string, c Client) (*QuestionData, error)

func (*QuestionData) Contest

func (q *QuestionData) Contest() *Contest

func (*QuestionData) ContestUrl

func (q *QuestionData) ContestUrl() string

func (*QuestionData) Fulfill

func (q *QuestionData) Fulfill() (err error)

func (*QuestionData) GetCodeSnippet

func (q *QuestionData) GetCodeSnippet(slug string) string

func (*QuestionData) GetExampleTestCases added in v1.3.3

func (q *QuestionData) GetExampleTestCases() []string

func (*QuestionData) GetFormattedContent

func (q *QuestionData) GetFormattedContent() string

func (*QuestionData) GetFormattedFilename

func (q *QuestionData) GetFormattedFilename(lang string, filenameTemplate string) (string, error)

func (*QuestionData) GetPreferContent added in v1.3.1

func (q *QuestionData) GetPreferContent() (string, config.Language)

func (*QuestionData) GetTitle

func (q *QuestionData) GetTitle() string

func (*QuestionData) IsContest

func (q *QuestionData) IsContest() bool

func (*QuestionData) ParseExampleOutputs

func (q *QuestionData) ParseExampleOutputs() []string

ParseExampleOutputs parses example output from content and translatedContent. We can also get correct example outputs by submitting example inputs to judge server.

func (*QuestionData) SetClient added in v1.3.6

func (q *QuestionData) SetClient(c Client)

func (*QuestionData) TagSlugs

func (q *QuestionData) TagSlugs() []string

func (*QuestionData) UnmarshalJSON added in v1.3.1

func (q *QuestionData) UnmarshalJSON(data []byte) error

func (*QuestionData) Url

func (q *QuestionData) Url() string

type QuestionFilter

type QuestionFilter struct {
	Difficulty     string   `json:"difficulty,omitempty"`
	Tags           []string `json:"tags,omitempty"`
	Status         string   `json:"status,omitempty"`
	SearchKeywords string   `json:"searchKeywords,omitempty"`
}

type QuestionList

type QuestionList struct {
	Questions []*QuestionData `json:"questions"`
	HasMore   bool            `json:"hasMore"`
	Total     int             `json:"total"`
}

type QuestionTag

type QuestionTag struct {
	Id             string `json:"id"`
	Name           string `json:"name"`
	NameTranslated string `json:"nameTranslated"`
	Slug           string `json:"slug"`
	TypeName       string `json:"typeName"`
	TypeTransName  string `json:"typeTransName"`
}

type QuestionsCache

type QuestionsCache interface {
	CacheFile() string
	GetBySlug(slug string) *QuestionData
	GetById(id string) *QuestionData
	GetAllQuestions() []*QuestionData
	Outdated() bool
	Update() error
}

func GetCache

func GetCache(c Client) QuestionsCache

type ResettableProvider

type ResettableProvider interface {
	Reset()
}

type RunCheckResult

type RunCheckResult struct {
	InputData              string
	State                  string   `json:"state"` // STARTED, SUCCESS
	StatusCode             int      `json:"status_code"`
	StatusMsg              string   `json:"status_msg"`         // Accepted, Wrong Answer, Time Limit Exceeded, Memory Limit Exceeded, Runtime Error, Compile Error, Output Limit Exceeded, Unknown Error
	Memory                 int      `json:"memory"`             // 内存消耗 in bytes
	StatusMemory           string   `json:"status_memory"`      // 内存消耗
	MemoryPercentile       float64  `json:"memory_percentile"`  // 内存消耗击败百分比
	StatusRuntime          string   `json:"status_runtime"`     // 执行用时
	RuntimePercentile      float64  `json:"runtime_percentile"` // 用时击败百分比
	Lang                   string   `json:"lang"`
	PrettyLang             string   `json:"pretty_lang"`
	CodeAnswer             []string `json:"code_answer"`   // return values of our code
	CompileError           string   `json:"compile_error"` //
	FullCompileError       string   `json:"full_compile_error"`
	FullRuntimeError       string   `json:"full_runtime_error"`
	CompareResult          string   `json:"compare_result"`  // "111", 1 means correct, 0 means wrong
	CorrectAnswer          bool     `json:"correct_answer"`  // true means all passed
	CodeOutput             []string `json:"code_output"`     // output to stdout of our code
	StdOutputList          []string `json:"std_output_list"` // list of output to stdout, same as code_output
	TaskName               string   `json:"task_name"`
	TotalCorrect           int      `json:"total_correct"`   // number of correct answers
	TotalTestcases         int      `json:"total_testcases"` // number of test cases
	ElapsedTime            int      `json:"elapsed_time"`
	TaskFinishTime         int      `json:"task_finish_time"`
	RunSuccess             bool     `json:"run_success"` // true if run success
	FastSubmit             bool     `json:"fast_submit"`
	Finished               bool     `json:"finished"`
	ExpectedOutput         string   `json:"expected_output"`
	ExpectedCodeAnswer     []string `json:"expected_code_answer"`
	ExpectedCodeOutput     []string `json:"expected_code_output"`
	ExpectedElapsedTime    int      `json:"expected_elapsed_time"`
	ExpectedLang           string   `json:"expected_lang"`
	ExpectedMemory         int      `json:"expected_memory"`
	ExpectedRunSuccess     bool     `json:"expected_run_success"`
	ExpectedStatusCode     int      `json:"expected_status_code"`
	ExpectedStatusRuntime  string   `json:"expected_status_runtime"`
	ExpectedStdOutputList  []string `json:"expected_std_output_list"`
	ExpectedTaskFinishTime int      `json:"expected_task_finish_time"`
	ExpectedTaskName       string   `json:"expected_task_name"`
}

func (*RunCheckResult) Accepted added in v1.3.9

func (r *RunCheckResult) Accepted() bool

func (*RunCheckResult) Display

func (r *RunCheckResult) Display(_ *QuestionData) string

func (*RunCheckResult) GetState

func (r *RunCheckResult) GetState() string

type SimilarQuestion

type SimilarQuestion struct {
	Title           string `json:"title"`
	TitleSlug       string `json:"titleSlug"`
	Difficulty      string `json:"difficulty"`
	TranslatedTitle string `json:"translatedTitle"`
}

type SimilarQuestions

type SimilarQuestions []SimilarQuestion

func (*SimilarQuestions) UnmarshalJSON

func (s *SimilarQuestions) UnmarshalJSON(data []byte) error

type Stats

type Stats struct {
	TotalAccepted      string `json:"totalAccepted"`
	TotalSubmission    string `json:"totalSubmission"`
	TotalAcceptedRaw   int    `json:"totalAcceptedRaw"`
	TotalSubmissionRaw int    `json:"totalSubmissionRaw"`
	ACRate             string `json:"acRate"`
}

func (*Stats) UnmarshalJSON

func (s *Stats) UnmarshalJSON(data []byte) error

type StatusCode

type StatusCode int
const (
	Accepted            StatusCode = 10
	WrongAnswer         StatusCode = 11 // submit only
	MemoryLimitExceeded StatusCode = 12 // submit only?
	OutputLimitExceeded StatusCode = 13
	TimeLimitExceeded   StatusCode = 14
	RuntimeError        StatusCode = 15
	CompileError        StatusCode = 20
)

type SubmitCheckResult

type SubmitCheckResult struct {
	CodeOutput        string  `json:"code_output"` // answers of our code
	CompareResult     string  `json:"compare_result"`
	ElapsedTime       int     `json:"elapsed_time"`
	ExpectedOutput    string  `json:"expected_output"`
	FastSubmit        bool    `json:"fast_submit"`
	Finished          bool    `json:"finished"`
	Lang              string  `json:"lang"`
	LastTestcase      string  `json:"last_testcase"`
	Memory            int     `json:"memory"`
	MemoryPercentile  float64 `json:"memory_percentile"`
	PrettyLang        string  `json:"pretty_lang"`
	QuestionId        string  `json:"question_id"`
	RunSuccess        bool    `json:"run_success"`
	RuntimePercentile float64 `json:"runtime_percentile"`
	State             string  `json:"state"`
	StatusCode        int     `json:"status_code"`
	StatusMemory      string  `json:"status_memory"`
	StatusMsg         string  `json:"status_msg"`
	StatusRuntime     string  `json:"status_runtime"`
	StdOutput         string  `json:"std_output"`
	SubmissionId      string  `json:"submission_id"`
	TaskFinishTime    int     `json:"task_finish_time"`
	TaskName          string  `json:"task_name"`
	TotalCorrect      int     `json:"total_correct"`
	TotalTestcases    int     `json:"total_testcases"`
	CompileError      string  `json:"compile_error"`
	FullCompileError  string  `json:"full_compile_error"`
	FullRuntimeError  string  `json:"full_runtime_error"`
}

func (*SubmitCheckResult) Accepted added in v1.3.1

func (r *SubmitCheckResult) Accepted() bool

func (*SubmitCheckResult) Display

func (r *SubmitCheckResult) Display(q *QuestionData) string

func (*SubmitCheckResult) GetState

func (r *SubmitCheckResult) GetState() string

type TopicTag

type TopicTag struct {
	Slug           string `json:"slug"`
	Name           string `json:"name"`
	TranslatedName string `json:"translatedName"`
}

type UnexpectedStatusCode added in v1.4.3

type UnexpectedStatusCode struct {
	Code int
	Body string
}

func (UnexpectedStatusCode) Error added in v1.4.3

func (e UnexpectedStatusCode) Error() string

type UserStatus

type UserStatus struct {
	Username        string `json:"username"`
	UserSlug        string `json:"userSlug"`
	RealName        string `json:"realName"`
	Avatar          string `json:"avatar"`
	ActiveSessionId int    `json:"activeSessionId"`
	IsSignedIn      bool   `json:"isSignedIn"`
	IsPremium       bool   `json:"isPremium"`
}

func (*UserStatus) Whoami added in v0.2.1

func (u *UserStatus) Whoami(c Client) string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL