repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
sglang | examples/frontend_language/usage/json_decode.py | .py | """
Usage:
python -m sglang.launch_server --model-path meta-llama/Llama-2-7b-chat-hf --port 30000
python json_decode.py
"""
from enum import Enum
from pydantic import BaseModel
import sglang as sgl
from sglang.srt.constrained.outlines_backend import build_regex_from_object
character_regex = (
r"""\{\n"""
+ ... | 84 | 2,216 |
sglang | examples/frontend_language/usage/cot_decoding.py | .py | from math import exp
from pprint import pformat
import sglang as sgl
YELLOW = "\033[1;33m"
GREEN = "\033[1;32m"
BLUE = "\033[1;34m"
CLEAR = "\033[1;0m"
@sgl.function
def cot_decoding(s, question, get_top_k, is_chat_model, verbose):
"""CoT Decoding: http://arxiv.org/abs/2402.10200"""
if is_chat_model:
... | 116 | 3,893 |
sglang | examples/frontend_language/usage/choices_logprob.py | .py | """
Usage:
python -m sglang.launch_server --model-path meta-llama/Llama-2-7b-chat-hf --port 30000
python choices_logprob.py
"""
import sglang as sgl
@sgl.function
def tool_use(s, question):
s += "To answer this question: " + question + ", "
s += "I need to use a " + sgl.gen("tool", choices=["calculator", "se... | 45 | 1,354 |
sglang | examples/frontend_language/usage/readme_examples.py | .py | """
Usage:
python -m sglang.launch_server --model-path meta-llama/Llama-2-7b-chat-hf --port 30000
python readme_examples.py
"""
import sglang as sgl
@sgl.function
def tool_use(s, question):
s += "To answer this question: " + question + ". "
s += (
"I need to use a "
+ sgl.gen("tool", choices=... | 110 | 2,670 |
sglang | examples/frontend_language/usage/chinese_regex.py | .py | import sglang as sgl
character_regex = (
r"""\{\n"""
+ r""" "姓名": "[^"]{1,32}",\n"""
+ r""" "学院": "(格兰芬多|赫奇帕奇|拉文克劳|斯莱特林)",\n"""
+ r""" "血型": "(纯血|混血|麻瓜)",\n"""
+ r""" "职业": "(学生|教师|傲罗|魔法部|食死徒|凤凰社成员)",\n"""
+ r""" "魔杖": \{\n"""
+ r""" "材质": "[^"]{1,32}",\n"""
+ r"""... | 54 | 1,554 |
sglang | examples/frontend_language/usage/openai_chat_speculative.py | .py | """
Usage:
***Note: for speculative execution to work, user must put all "gen" in "assistant".
Show in "assistant" the desired answer format. Each "gen" term should have a stop token.
The stream mode is not supported in speculative execution.
E.g.
correct:
sgl.assistant("\nName:" + sgl.gen("name", stop="\n") + "\n... | 156 | 4,910 |
sglang | examples/frontend_language/usage/openai_speculative.py | .py | """
Usage:
python3 openai_speculative.py
"""
from sglang import OpenAI, function, gen, set_default_backend
@function(num_api_spec_tokens=64)
def gen_character_spec(s):
s += "Construct a character within the following format:\n"
s += "Name: Steve Jobs.\nBirthday: February 24, 1955.\nJob: Apple CEO.\n"
s +... | 55 | 1,742 |
sglang | examples/frontend_language/usage/streaming.py | .py | """
Usage:
python3 streaming.py
"""
import asyncio
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.system("You are a helpful assistant.")
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max_tokens=256))
s += sgl.user(question_2)
s ... | 50 | 1,155 |
sglang | examples/frontend_language/usage/triton/models/character_generation/1/model.py | .py | import numpy
import triton_python_backend_utils as pb_utils
from pydantic import BaseModel
import sglang as sgl
from sglang import function
from sglang.srt.constrained.outlines_backend import build_regex_from_object
sgl.set_default_backend(sgl.RuntimeEndpoint("http://localhost:30000"))
class Character(BaseModel):
... | 56 | 1,624 |
sglang | examples/frontend_language/usage/llava_video/srt_example_llava_v.py | .py | """
Usage:
pip install opencv-python-headless
python3 srt_example_llava_v.py
"""
import argparse
import csv
import json
import os
import time
import requests
import sglang as sgl
@sgl.function
def video_qa(s, num_frames, video_path, question):
s += sgl.user(sgl.video(video_path, num_frames) + question)
s ... | 261 | 9,268 |
sglang | examples/frontend_language/quick_start/openai_example_n.py | .py | """
Usage:
export OPENAI_API_KEY=sk-******
python3 openai_example_chat.py
"""
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.system("You are a helpful assistant.")
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max_tokens=1024, n=2))
... | 72 | 1,886 |
sglang | examples/frontend_language/quick_start/openai_example_chat.py | .py | """
Usage:
export OPENAI_API_KEY=sk-******
python3 openai_example_chat.py
"""
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.system("You are a helpful assistant.")
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max_tokens=256))
s += s... | 75 | 1,785 |
sglang | examples/frontend_language/quick_start/openai_example_o1.py | .py | """
Usage:
export OPENAI_API_KEY=sk-******
python3 openai_example_chat.py
"""
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.system("You are a helpful assistant.")
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max_tokens=100))
s += s... | 58 | 1,397 |
sglang | examples/frontend_language/quick_start/gemini_example_multimodal_chat.py | .py | """
Usage:
export GCP_PROJECT_ID=******
python3 gemini_example_multimodal_chat.py
"""
import sglang as sgl
@sgl.function
def image_qa(s, image_file1, image_file2, question):
s += sgl.user(sgl.image(image_file1) + sgl.image(image_file2) + question)
s += sgl.assistant(sgl.gen("answer", max_tokens=256))
if __... | 31 | 738 |
sglang | examples/frontend_language/quick_start/anthropic_example_complete.py | .py | """
Usage:
export ANTHROPIC_API_KEY=sk-******
python3 anthropic_example_complete.py
"""
import sglang as sgl
@sgl.function
def few_shot_qa(s, question):
s += """
\n\nHuman: What is the capital of France?
\n\nAssistant: Paris
\n\nHuman: What is the capital of Germany?
\n\nAssistant: Berlin
\n\nHuman: What is the ... | 69 | 1,526 |
sglang | examples/frontend_language/quick_start/gemini_example_complete.py | .py | """
Usage:
export GCP_PROJECT_ID=******
python3 gemini_example_complete.py
"""
import sglang as sgl
@sgl.function
def few_shot_qa(s, question):
s += """The following are questions with answers.
Q: What is the capital of France?
A: Paris
Q: What is the capital of Germany?
A: Berlin
Q: What is the capital of Italy... | 69 | 1,475 |
sglang | examples/frontend_language/quick_start/local_example_complete.py | .py | """
Usage:
python3 local_example_complete.py
"""
import sglang as sgl
@sgl.function
def few_shot_qa(s, question):
s += """The following are questions with answers.
Q: What is the capital of France?
A: Paris
Q: What is the capital of Germany?
A: Berlin
Q: What is the capital of Italy?
A: Rome
"""
s += "Q: " +... | 71 | 1,520 |
sglang | examples/frontend_language/quick_start/orcarouter_example_chat.py | .py | """
Usage:
export ORCAROUTER_API_KEY=sk-orca-******
python3 orcarouter_example_chat.py
"""
import os
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.system("You are a helpful assistant.")
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max... | 84 | 2,093 |
sglang | examples/frontend_language/quick_start/azure_openai_example_chat.py | .py | """
Usage:
export AZURE_OPENAI_API_KEY=sk-******
python3 openai_example_chat.py
"""
import os
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.system("You are a helpful assistant.")
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max_tokens... | 84 | 2,034 |
sglang | examples/frontend_language/quick_start/openai_example_complete.py | .py | """
Usage:
export OPENAI_API_KEY=sk-******
python3 openai_example_complete.py
"""
import sglang as sgl
@sgl.function
def few_shot_qa(s, question):
s += """The following are questions with answers.
Q: What is the capital of France?
A: Paris
Q: What is the capital of Germany?
A: Berlin
Q: What is the capital of It... | 69 | 1,488 |
sglang | examples/frontend_language/quick_start/together_example_chat.py | .py | """
Usage:
export TOGETHER_API_KEY=sk-******
python3 together_example_chat.py
"""
import os
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.system("You are a helpful assistant.")
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max_tokens=2... | 82 | 1,971 |
sglang | examples/frontend_language/quick_start/local_example_chat.py | .py | """
Usage:
python3 local_example_chat.py
"""
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max_tokens=256))
s += sgl.user(question_2)
s += sgl.assistant(sgl.gen("answer_2", max_tokens=256))
def... | 76 | 1,774 |
sglang | examples/frontend_language/quick_start/gemini_example_chat.py | .py | """
Usage:
export GCP_PROJECT_ID=******
python3 gemini_example_chat.py
"""
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max_tokens=256))
s += sgl.user(question_2)
s += sgl.assistant(sgl.gen("ans... | 74 | 1,729 |
sglang | examples/frontend_language/quick_start/together_example_complete.py | .py | """
Usage:
export TOGETHER_API_KEY=sk-******
python3 together_example_complete.py
"""
import os
import sglang as sgl
@sgl.function
def few_shot_qa(s, question):
s += """The following are questions with answers.
Q: What is the capital of France?
A: Paris
Q: What is the capital of Germany?
A: Berlin
Q: What is th... | 77 | 1,694 |
sglang | examples/frontend_language/quick_start/anthropic_example_chat.py | .py | """
Usage:
export ANTHROPIC_API_KEY=sk-******
python3 anthropic_example_chat.py
"""
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max_tokens=256))
s += sgl.user(question_2)
s += sgl.assistant(sgl... | 74 | 1,752 |
sglang | examples/frontend_language/quick_start/local_example_llava_next.py | .py | """
Usage: python3 local_example_llava_next.py
"""
import sglang as sgl
from sglang.lang.chat_template import get_chat_template
@sgl.function
def image_qa(s, image_path, question):
s += sgl.user(sgl.image(image_path) + question)
s += sgl.assistant(sgl.gen("answer"))
def single():
state = image_qa.run(
... | 79 | 2,007 |
sglang | examples/frontend_language/quick_start/openrouter_example_chat.py | .py | """
Usage:
export OPENROUTER_API_KEY=sk-******
python3 together_example_chat.py
"""
import os
import sglang as sgl
@sgl.function
def multi_turn_question(s, question_1, question_2):
s += sgl.system("You are a helpful assistant.")
s += sgl.user(question_1)
s += sgl.assistant(sgl.gen("answer_1", max_tokens... | 82 | 1,963 |
sglang | examples/runtime/reward_model.py | .py | # launch server
# python -m sglang.launch_server --model LxzGordon/URM-LLaMa-3.1-8B --is-embedding
import requests
url = "http://127.0.0.1:30000"
PROMPT = (
"What is the range of the numeric output of a sigmoid node in a neural network?"
)
RESPONSE1 = "The output of a sigmoid node is bounded between -1 and 1."
R... | 33 | 830 |
sglang | examples/runtime/lora.py | .py | """
OpenAI-compatible LoRA adapter usage with SGLang.
Server Setup:
python -m sglang.launch_server \\
--model meta-llama/Llama-3.1-8B-Instruct \\
--enable-lora \\
--lora-paths sql=/path/to/sql python=/path/to/python
"""
import openai
client = openai.Client(base_url="http://127.0.0.1:30000... | 68 | 2,245 |
sglang | examples/runtime/multimodal_embedding.py | .py | # launch server
# python -m sglang.launch_server --model-path Alibaba-NLP/gme-Qwen2-VL-2B-Instruct --is-embedding
import requests
url = "http://127.0.0.1:30000"
text_input = "Represent this image in embedding space."
image_path = "https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild/resolve/main/images... | 19 | 583 |
sglang | examples/runtime/openai_chat_with_response_prefill.py | .py | """
Usage:
1) Launch the server in one terminal:
python -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --port 30000
2) Run this script in another terminal:
python openai_chat_with_response_prefill.py
This example demonstrates two chat completion calls:
- One with continue_final_message en... | 54 | 1,899 |
sglang | examples/runtime/qwen3_vl_reranker.py | .py | """
Example usage of Qwen3-VL-Reranker with SGLang.
This example demonstrates how to use the Qwen3-VL-Reranker model for multimodal
reranking tasks, supporting text, images, and videos.
Server Launch:
python -m sglang.launch_server \
--model-path Qwen/Qwen3-VL-Reranker-2B \
--served-model-name Qwe... | 186 | 6,143 |
sglang | examples/runtime/vertex_predict.py | .py | """
Usage:
python -m sglang.launch_server --model meta-llama/Llama-2-7b-hf --port 30000
python vertex_predict.py
This example shows the request and response formats of the prediction route for
Google Cloud Vertex AI Online Predictions.
Vertex AI SDK for Python is recommended for deploying models to Vertex AI
instead ... | 67 | 1,889 |
sglang | examples/runtime/chain_of_verification.py | .py | #!/usr/bin/env python3
"""Chain-of-Verification (CoVe) example for reducing LLM hallucinations with SGLang.
This script implements the "Factored CoVe" pattern from:
Dhuliawala et al. (2023) "Chain-of-Verification Reduces Hallucination in Large Language Models"
https://arxiv.org/abs/2309.11495
The key insight (Fac... | 279 | 9,740 |
sglang | examples/runtime/hidden_states/hidden_states_engine.py | .py | """
Usage:
python hidden_states_engine.py
CUDA graphs use the configured maximum hidden-state mode. Requests may select
that mode or a weaker one without triggering mode-dependent recapture.
"""
import torch
import sglang as sgl
def main():
prompts = [
"Hello, my name is",
"The president of the... | 59 | 1,633 |
sglang | examples/runtime/hidden_states/hidden_states_server.py | .py | """
Usage:
python hidden_states_server.py
CUDA graphs use the configured maximum hidden-state mode. Requests may select
that mode or a weaker one without triggering mode-dependent recapture.
"""
import requests
import torch
from sglang.test.test_utils import is_in_ci
from sglang.utils import terminate_process, wait... | 76 | 1,960 |
sglang | examples/runtime/engine/offline_batch_inference_eagle.py | .py | import sglang as sgl
def main():
# Sample prompts.
prompts = [
"Hello, my name is",
"The president of the United States is",
"The capital of France is",
"The future of AI is",
]
# Create a sampling params object.
sampling_params = {"temperature": 0, "max_new_tokens... | 39 | 1,204 |
sglang | examples/runtime/engine/offline_batch_inference_vlm.py | .py | """
Usage:
python offline_batch_inference_vlm.py --model-path Qwen/Qwen2-VL-7B-Instruct
"""
import argparse
import dataclasses
import sglang as sgl
from sglang.srt.parser.conversation import chat_templates
from sglang.srt.server_args import ServerArgs
def main(
server_args: ServerArgs,
):
vlm = sgl.Engine(*... | 53 | 1,415 |
sglang | examples/runtime/engine/save_sharded_state.py | .py | # SPDX-License-Identifier: Apache-2.0
"""
Saves each worker's model state dict directly to a checkpoint, which enables a
fast load path for large tensor-parallel models where each worker only needs to
read its own shard rather than the entire checkpoint.
Example usage:
python save_sharded_state.py \
--model-path ... | 76 | 2,142 |
sglang | examples/runtime/engine/launch_engine.py | .py | """
This example demonstrates how to launch the offline engine.
"""
import sglang as sgl
def main():
llm = sgl.Engine(model_path="meta-llama/Meta-Llama-3.1-8B-Instruct")
llm.generate("What is the capital of France?")
llm.shutdown()
# The __main__ condition is necessary here because we use "spawn" to cr... | 18 | 518 |
sglang | examples/runtime/engine/save_remote_state.py | .py | # SPDX-License-Identifier: Apache-2.0
"""
Saves each worker's model state dict directly to a checkpoint, which enables a
fast load path for large tensor-parallel models where each worker only needs to
read its own shard rather than the entire checkpoint.
Example usage:
python save_remote_state.py \
--model-path /... | 61 | 1,590 |
sglang | examples/runtime/engine/offline_batch_inference_async.py | .py | """
Usage:
python offline_batch_inference_async.py --model-path Qwen/Qwen2-VL-7B-Instruct
Note:
This demo shows the usage of async generation,
which is useful to implement an online-like generation with batched inference.
"""
import argparse
import asyncio
import dataclasses
import time
import sglang as sgl
from sgl... | 66 | 1,739 |
sglang | examples/runtime/engine/offline_batch_inference_qwen_1m.py | .py | """
Usage:
python3 offline_batch_inference.py
"""
from urllib.request import urlopen
import sglang as sgl
def load_prompt() -> str:
# Test cases with various lengths can be found at:
#
# https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2.5-1M/test-data/64k.txt
# https://qianwen-res.oss-cn-beijing... | 75 | 2,040 |
sglang | examples/runtime/engine/offline_batch_inference.py | .py | """
Usage:
python3 offline_batch_inference.py --model meta-llama/Llama-3.1-8B-Instruct
"""
import argparse
import dataclasses
import sglang as sgl
from sglang.srt.server_args import ServerArgs
def main(
server_args: ServerArgs,
):
# Sample prompts.
prompts = [
"Hello, my name is",
"The ... | 44 | 1,287 |
sglang | examples/runtime/engine/fastapi_engine_inference.py | .py | """
FastAPI server example for text generation using SGLang Engine and demonstrating client usage.
Starts the server, sends requests to it, and prints responses.
Usage:
python fastapi_engine_inference.py --model-path Qwen/Qwen2.5-0.5B-Instruct --tp_size 1 --host 127.0.0.1 --port 8000 [--startup-timeout 60]
"""
impor... | 196 | 6,591 |
sglang | examples/runtime/engine/custom_server.py | .py | from sanic import Sanic, text
from sanic.response import json
import sglang as sgl
engine = None
# Create an instance of the Sanic app
app = Sanic("sanic-server")
# Define an asynchronous route handler
@app.route("/generate", methods=["POST"])
async def generate(request):
prompt = request.json.get("prompt")
... | 54 | 1,317 |
sglang | examples/runtime/engine/embedding.py | .py | import sglang as sgl
def main():
# Sample prompts.
prompts = [
"Hello, my name is",
"The president of the United States is",
"The capital of France is",
"The future of AI is",
]
# Create an LLM.
llm = sgl.Engine(
model_path="Alibaba-NLP/gte-Qwen2-1.5B-instru... | 28 | 873 |
sglang | examples/runtime/multimodal/pixtral_server.py | .py | """
Usage:
# Run a Pixtral model with SGLang:
# HuggingFace:
python -m sglang.launch_server --model-path mistral-community/pixtral-12b --port=30000
# ModelScope:
python -m sglang.launch_server --model-path AI-ModelScope/pixtral-12b --port=30000
# Then test it with:
python pixtral_server.py
This script tests Pixtral m... | 130 | 3,908 |
sglang | examples/runtime/multimodal/qwen_llava_server.py | .py | """
Usage:
# Installing latest llava-next: pip install git+https://github.com/LLaVA-VL/LLaVA-NeXT.git
# Installing latest sglang.
# Endpoint Service CLI:
python -m sglang.launch_server --model-path lmms-lab/llava-next-72b --port=30000 --tp-size=8
python3 qwen_llava_server.py
Output:
"Two children pose with a large t... | 114 | 3,625 |
sglang | examples/runtime/multimodal/llama3_llava_server.py | .py | """
Usage:
# Installing latest llava-next: pip install git+https://github.com/LLaVA-VL/LLaVA-NeXT.git
# Installing latest sglang.
# Endpoint Service CLI:
python -m sglang.launch_server --model-path lmms-lab/llama3-llava-next-8b --port=30000
python3 llama3_llava_server.py
Output:
"Friends posing for a fun photo with ... | 114 | 3,620 |
sglang | examples/runtime/multimodal/llava_onevision_server.py | .py | """
Usage:
python3 -m sglang.launch_server --model-path lmms-lab/llava-onevision-qwen2-72b-ov --port=30000 --tp-size=8
python3 llava_onevision_server.py
"""
import io
import os
import sys
import time
import numpy as np
import openai
import pybase64
import requests
from PIL import Image
from sglang.srt.utils.video_... | 266 | 8,216 |
sglang | examples/runtime/token_in_token_out/token_in_token_out_llm_server.py | .py | """
Usage:
python token_in_token_out_llm_server.py
"""
import requests
from sglang.srt.utils.hf_transformers_utils import get_tokenizer
from sglang.test.test_utils import is_in_ci
from sglang.utils import terminate_process, wait_for_server
if is_in_ci():
from docs.backend.patch import launch_server_cmd
else:
... | 69 | 1,740 |
sglang | examples/runtime/token_in_token_out/token_in_token_out_vlm_engine.py | .py | import argparse
import dataclasses
from typing import Tuple
from transformers import AutoProcessor
from sglang import Engine
from sglang.lang.chat_template import get_chat_template_by_model_path
from sglang.srt.configs.model_config import ModelConfig
from sglang.srt.server_args import ServerArgs
from sglang.test.test... | 75 | 2,003 |
sglang | examples/runtime/token_in_token_out/token_in_token_out_llm_engine.py | .py | """
This example demonstrates how to provide tokenized ids to LLM as input instead of text prompt, i.e. a token-in-token-out workflow.
"""
import sglang as sgl
from sglang.srt.utils.hf_transformers_utils import get_tokenizer
MODEL_PATH = "meta-llama/Llama-3.1-8B-Instruct"
def main():
# Sample prompts.
promp... | 44 | 1,497 |
sglang | examples/runtime/token_in_token_out/token_in_token_out_vlm_server.py | .py | """
Usage:
python token_in_token_out_vlm_server.py
"""
from typing import Tuple
import requests
from transformers import AutoProcessor
from sglang.lang.chat_template import get_chat_template_by_model_path
from sglang.test.test_utils import DEFAULT_IMAGE_URL, is_in_ci
from sglang.utils import terminate_process, wai... | 79 | 1,811 |
interactive-coding-challenges | staging/sorting_searching/group_ordered/test_group_ordered.py | .py | import unittest
class TestGroupOrdered(unittest.TestCase):
def test_group_ordered(self, func):
self.assertEqual(func(None), None)
print('Success: ' + func.__name__ + " None case.")
self.assertEqual(func([]), [])
print('Success: ' + func.__name__ + " Empty case.")
self.asse... | 32 | 1,040 |
interactive-coding-challenges | staging/graphs_trees/binary_tree/binary_search_tree.py | .py |
class Node (object):
def __init__ (self, data):
self.data = data
self.rightChild = None
self.leftChild = None
class BinaryTree (object):
def __init__ (self):
self.root = None
def insert (self, newData):
leaf = Node(newData)
if self.root is None:
self.root = leaf
else:
current = self.root
p... | 156 | 3,231 |
interactive-coding-challenges | staging/graphs_trees/binary_tree/test_binary_search_tree.py | .py | import unittest
class TestBinaryTree(unittest.TestCase):
def test_insert_traversals (self):
myTree = BinaryTree()
myTree2 = BinaryTree()
for num in [50, 30, 70, 10, 40, 60, 80, 7, 25, 38]:
myTree.insert(num)
[myTree2.insert(num) for num in range (1, 100, 10)]
print("Test: insert checking with in order ... | 81 | 2,238 |
interactive-coding-challenges | staging/arrays_strings/reverse_words/reverse_words_solution.py | .py | import unittest
class TestReverseWords(unittest.TestCase):
def testReverseWords(self, func):
self.assertEqual(func('the sun is hot'), 'eht nus si toh')
self.assertEqual(func(''), None)
self.assertEqual(func('123 456 789'), '321 654 987')
self.assertEqual(func('magi... | 21 | 499 |
interactive-coding-challenges | recursion_dynamic/longest_substring/test_longest_common_substr.py | .py | import unittest
class TestLongestCommonSubstr(unittest.TestCase):
def test_longest_common_substr(self):
str_comp = StringCompare()
self.assertRaises(TypeError, str_comp.longest_common_substr, None, None)
self.assertEqual(str_comp.longest_common_substr('', ''), '')
str0 = 'ABCDEFGH... | 24 | 639 |
interactive-coding-challenges | recursion_dynamic/coin_change_ways/test_coin_change_ways.py | .py | import unittest
class Challenge(unittest.TestCase):
def test_coin_change_ways(self,solution):
self.assertEqual(solution(0, [1, 2]), 0)
self.assertEqual(solution(100, [1, 2, 3]), 884)
self.assertEqual(solution(1000, range(1, 101)),
15658181104580771094597751280645)
... | 21 | 487 |
interactive-coding-challenges | recursion_dynamic/knapsack_01/test_knapsack.py | .py | import unittest
class TestKnapsack(unittest.TestCase):
def test_knapsack_bottom_up(self):
knapsack = Knapsack()
self.assertRaises(TypeError, knapsack.fill_knapsack, None, None)
self.assertEqual(knapsack.fill_knapsack(0, 0), 0)
items = []
items.append(Item(label='a', value=... | 48 | 1,701 |
interactive-coding-challenges | recursion_dynamic/magic_index/test_find_magic_index.py | .py | import unittest
class TestFindMagicIndex(unittest.TestCase):
def test_find_magic_index(self):
magic_index = MagicIndex()
self.assertEqual(magic_index.find_magic_index(None), -1)
self.assertEqual(magic_index.find_magic_index([]), -1)
array = [-4, -2, 2, 6, 6, 6, 6, 10]
self... | 26 | 753 |
interactive-coding-challenges | recursion_dynamic/grid_path/test_grid_path.py | .py | import unittest
class TestGridPath(unittest.TestCase):
def test_grid_path(self):
grid = Grid()
self.assertEqual(grid.find_path(None), None)
self.assertEqual(grid.find_path([[]]), None)
max_rows = 8
max_cols = 4
matrix = [[1] * max_cols for _ in range(max_rows)]
... | 40 | 1,020 |
interactive-coding-challenges | recursion_dynamic/coin_change_min/test_coin_change_min.py | .py | import unittest
class TestCoinChange(unittest.TestCase):
def test_coin_change(self):
coin_changer = CoinChanger()
self.assertRaises(TypeError, coin_changer.make_change, None, None)
self.assertEqual(coin_changer.make_change([], 0), 0)
self.assertEqual(coin_changer.make_change([1, 2... | 23 | 622 |
interactive-coding-challenges | recursion_dynamic/longest_common_subsequence/test_longest_common_subseq.py | .py | import unittest
class TestLongestCommonSubseq(unittest.TestCase):
def test_longest_common_subseq(self):
str_comp = StringCompare()
self.assertRaises(TypeError, str_comp.longest_common_subseq, None, None)
self.assertEqual(str_comp.longest_common_subseq('', ''), '')
str0 = 'ABCDEFGH... | 24 | 639 |
interactive-coding-challenges | recursion_dynamic/permutations/test_permutations.py | .py | import unittest
class TestPermutations(unittest.TestCase):
def test_permutations(self):
permutations = Permutations()
self.assertEqual(permutations.find_permutations(None), None)
self.assertEqual(permutations.find_permutations(''), '')
string = 'AABC'
expected = [
... | 27 | 685 |
interactive-coding-challenges | recursion_dynamic/hanoi/test_hanoi.py | .py | import unittest
class TestHanoi(unittest.TestCase):
def test_hanoi(self):
hanoi = Hanoi()
num_disks = 3
src = Stack()
buff = Stack()
dest = Stack()
print('Test: None towers')
self.assertRaises(TypeError, hanoi.move_disks, num_disks, None, None, None)
... | 42 | 1,002 |
interactive-coding-challenges | recursion_dynamic/max_profit_k/test_max_profit.py | .py | import unittest
class TestMaxProfit(unittest.TestCase):
def test_max_profit(self):
stock_trader = StockTrader()
self.assertRaises(TypeError, stock_trader.find_max_profit, None, None)
self.assertEqual(stock_trader.find_max_profit(prices=[], k=0), [])
prices = [5, 4, 3, 2, 1]
... | 44 | 1,564 |
interactive-coding-challenges | recursion_dynamic/knapsack_unbounded/test_knapsack_unbounded.py | .py | import unittest
class TestKnapsack(unittest.TestCase):
def test_knapsack(self):
knapsack = Knapsack()
self.assertRaises(TypeError, knapsack.fill_knapsack, None, None)
self.assertEqual(knapsack.fill_knapsack(0, 0), 0)
items = []
items.append(Item(label='a', value=1, weight=... | 30 | 862 |
interactive-coding-challenges | recursion_dynamic/longest_substr_k_distinct/test_longest_substr.py | .py | import unittest
class TestSolution(unittest.TestCase):
def test_longest_substr(self):
solution = Solution()
self.assertRaises(TypeError, solution.longest_substr, None)
self.assertEqual(solution.longest_substr('', k=3), 0)
self.assertEqual(solution.longest_substr('abcabcdefgghiij',... | 22 | 566 |
interactive-coding-challenges | recursion_dynamic/fibonacci/test_fibonacci.py | .py | import unittest
class TestFib(unittest.TestCase):
def test_fib(self, func):
result = []
expected = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
for i in range(len(expected)):
result.append(func(i))
self.assertEqual(result, expected)
print('Success: test_fib')
def main()... | 25 | 513 |
interactive-coding-challenges | recursion_dynamic/longest_inc_subseq/test_longest_increasing_subseq.py | .py | import unittest
class TestLongestIncreasingSubseq(unittest.TestCase):
def test_longest_increasing_subseq(self):
subseq = Subsequence()
self.assertRaises(TypeError, subseq.longest_inc_subseq, None)
self.assertEqual(subseq.longest_inc_subseq([]), [])
seq = [3, 4, -1, 0, 6, 2, 3]
... | 23 | 611 |
interactive-coding-challenges | recursion_dynamic/steps/test_steps.py | .py | import unittest
class TestSteps(unittest.TestCase):
def test_steps(self):
steps = Steps()
self.assertRaises(TypeError, steps.count_ways, None)
self.assertRaises(TypeError, steps.count_ways, -1)
self.assertEqual(steps.count_ways(0), 1)
self.assertEqual(steps.count_ways(1), ... | 26 | 658 |
interactive-coding-challenges | recursion_dynamic/matrix_mult/test_find_min_cost.py | .py | import unittest
class TestMatrixMultiplicationCost(unittest.TestCase):
def test_find_min_cost(self):
matrix_mult_cost = MatrixMultiplicationCost()
self.assertRaises(TypeError, matrix_mult_cost.find_min_cost, None)
self.assertEqual(matrix_mult_cost.find_min_cost([]), 0)
matrices = ... | 26 | 718 |
interactive-coding-challenges | recursion_dynamic/coin_change/test_coin_change.py | .py | import unittest
class Challenge(unittest.TestCase):
def test_coin_change(self):
coin_changer = CoinChanger()
self.assertEqual(coin_changer.make_change([1, 2], 0), 0)
self.assertEqual(coin_changer.make_change([1, 2, 3], 5), 5)
self.assertEqual(coin_changer.make_change([1, 5, 25, 50... | 21 | 479 |
interactive-coding-challenges | recursion_dynamic/power_set/test_power_set.py | .py | import unittest
class TestPowerSet(unittest.TestCase):
def test_power_set(self):
input_set = ''
expected = ['']
self.run_test(input_set, expected)
input_set = 'a'
expected = ['a', '']
self.run_test(input_set, expected)
input_set = 'ab'
expected = ['... | 40 | 1,069 |
interactive-coding-challenges | recursion_dynamic/n_pairs_parentheses/test_n_pairs_parentheses.py | .py | import unittest
class TestPairParentheses(unittest.TestCase):
def test_pair_parentheses(self):
parentheses = Parentheses()
self.assertRaises(TypeError, parentheses.find_pair, None)
self.assertRaises(ValueError, parentheses.find_pair, -1)
self.assertEqual(parentheses.find_pair(0), ... | 29 | 963 |
interactive-coding-challenges | bit_manipulation/flip_bit/test_flip_bit.py | .py | import unittest
class TestBits(unittest.TestCase):
def test_flip_bit(self):
bits = Bits()
self.assertRaises(TypeError, bits.flip_bit, None)
self.assertEqual(bits.flip_bit(0), 1)
self.assertEqual(bits.flip_bit(-1), bits.MAX_BITS)
num = int('00001111110111011110001111110000'... | 30 | 829 |
interactive-coding-challenges | bit_manipulation/insert_m_into_n/test_insert_m_into_n.py | .py | import unittest
class TestBit(unittest.TestCase):
def test_insert_m_into_n(self):
n = int('0000010000111101', base=2)
m = int('0000000000010011', base=2)
expected = int('0000010001001101', base=2)
bits = Bits()
self.assertEqual(bits.insert_m_into_n(m, n, i=2, j=6), expecte... | 22 | 477 |
interactive-coding-challenges | bit_manipulation/print_binary/test_print_binary.py | .py | import unittest
class TestBits(unittest.TestCase):
def test_print_binary(self):
bit = Bits()
self.assertEqual(bit.print_binary(None), 'ERROR')
self.assertEqual(bit.print_binary(0), 'ERROR')
self.assertEqual(bit.print_binary(1), 'ERROR')
num = 0.625
expected = '0.10... | 26 | 613 |
interactive-coding-challenges | bit_manipulation/get_next/test_get_next_largest.py | .py | import unittest
class TestBits(unittest.TestCase):
def test_get_next_largest(self):
bits = Bits()
self.assertRaises(Exception, bits.get_next_largest, None)
self.assertRaises(Exception, bits.get_next_largest, 0)
self.assertRaises(Exception, bits.get_next_largest, -1)
num = ... | 34 | 1,095 |
interactive-coding-challenges | bit_manipulation/bit/test_bit.py | .py | import unittest
class TestBit(unittest.TestCase):
def test_bit(self):
number = int('10001110', base=2)
bit = Bit(number)
self.assertEqual(bit.get_bit(index=3), True)
expected = int('10011110', base=2)
self.assertEqual(bit.set_bit(index=4), expected)
bit = Bit(numbe... | 39 | 1,208 |
interactive-coding-challenges | bit_manipulation/draw_line/test_draw_line.py | .py | import unittest
class TestBitsScreen(unittest.TestCase):
def test_draw_line(self):
bits_screen = BitsScreen()
screen = []
for _ in range(20):
screen.append(int('00000000', base=2))
bits_screen.draw_line(screen, width=32, x1=68, x2=80)
self.assertEqual(screen[8]... | 29 | 863 |
interactive-coding-challenges | bit_manipulation/pairwise_swap/test_pairwise_swap.py | .py | import unittest
class TestBits(unittest.TestCase):
def test_pairwise_swap(self):
bits = Bits()
self.assertEqual(bits.pairwise_swap(0), 0)
self.assertEqual(bits.pairwise_swap(1), 1)
num = int('0000100111110110', base=2)
expected = int('0000011011111001', base=2)
sel... | 25 | 592 |
interactive-coding-challenges | bit_manipulation/bits_to_flip/test_bits_to_flip.py | .py | import unittest
class TestBits(unittest.TestCase):
def test_bits_to_flip(self):
bits = Bits()
a = int('11101', base=2)
b = int('01111', base=2)
expected = 2
self.assertEqual(bits.bits_to_flip(a, b), expected)
print('Success: test_bits_to_flip')
def main():
te... | 22 | 405 |
interactive-coding-challenges | online_judges/str_diff/test_str_diff.py | .py | import unittest
class TestFindDiff(unittest.TestCase):
def test_find_diff(self):
solution = Solution()
self.assertRaises(TypeError, solution.find_diff, None)
self.assertEqual(solution.find_diff('aaabbcdd', 'abdbacade'), 'e')
print('Success: test_find_diff')
def main():
test ... | 20 | 403 |
interactive-coding-challenges | online_judges/island_perimeter/test_island_perimeter.py | .py | import unittest
class TestIslandPerimeter(unittest.TestCase):
def test_island_perimeter(self):
solution = Solution()
self.assertRaises(TypeError, solution.island_perimeter, None)
data = [[1, 0]]
expected = 4
self.assertEqual(solution.island_perimeter(data), expected)
... | 28 | 693 |
interactive-coding-challenges | online_judges/merge_ranges/test_merge_ranges.py | .py | import unittest
class TestMergeRanges(unittest.TestCase):
def test_merge_ranges(self):
solution = Solution()
self.assertRaises(TypeError, solution.merge_ranges, None)
self.assertEqual(solution.merge_ranges([]), [])
array = [(2, 3), (7, 9)]
expected = [(2, 3), (7, 9)]
... | 29 | 841 |
interactive-coding-challenges | online_judges/move_zeroes/test_move_zeroes.py | .py | import unittest
class TestMoveZeroes(unittest.TestCase):
def test_move_zeroes(self):
solution = Solution()
self.assertRaises(TypeError, solution.move_zeroes, None)
array = [0, 1, 0, 3, 12]
solution.move_zeroes(array)
self.assertEqual(array, [1, 3, 12, 0, 0])
array ... | 37 | 942 |
interactive-coding-challenges | online_judges/ransom_note/test_ransom_note.py | .py | import unittest
class TestRansomNote(unittest.TestCase):
def test_ransom_note(self):
solution = Solution()
self.assertRaises(TypeError, solution.match_note_to_magazine, None, None)
self.assertEqual(solution.match_note_to_magazine('', ''), True)
self.assertEqual(solution.match_note... | 23 | 658 |
interactive-coding-challenges | online_judges/sentence_screen_fit/test_count_sentence_fit.py | .py | import unittest
class TestSolution(unittest.TestCase):
def test_count_sentence_fit(self):
solution = Solution()
self.assertRaises(TypeError, solution.count_sentence_fit,
None, None, None)
self.assertRaises(ValueError, solution.count_sentence_fit,
... | 34 | 1,033 |
interactive-coding-challenges | online_judges/sum_two/test_sum_two.py | .py | import unittest
class TestSumTwo(unittest.TestCase):
def test_sum_two(self):
solution = Solution()
self.assertRaises(TypeError, solution.sum_two, None)
self.assertEqual(solution.sum_two(5, 7), 12)
self.assertEqual(solution.sum_two(-5, -7), -12)
self.assertEqual(solution.su... | 22 | 479 |
interactive-coding-challenges | online_judges/mult_other_numbers/test_mult_other_numbers.py | .py | import unittest
class TestMultOtherNumbers(unittest.TestCase):
def test_mult_other_numbers(self):
solution = Solution()
self.assertRaises(TypeError, solution.mult_other_numbers, None)
self.assertEqual(solution.mult_other_numbers([0]), [])
self.assertEqual(solution.mult_other_numbe... | 23 | 673 |
interactive-coding-challenges | online_judges/max_profit/test_max_profit.py | .py | import unittest
class TestMaxProfit(unittest.TestCase):
def test_max_profit(self):
solution = Solution()
self.assertRaises(TypeError, solution.find_max_profit, None)
self.assertRaises(ValueError, solution.find_max_profit, [])
self.assertEqual(solution.find_max_profit([8, 5, 3, 2, ... | 22 | 556 |
interactive-coding-challenges | online_judges/maximizing_xor/test_maximizing_xor.py | .py | import unittest
class TestMaximizingXor(unittest.TestCase):
def test_maximizing_xor(self):
solution = Solution()
self.assertEqual(solution.max_xor(10, 15), 7)
print('Success: test_maximizing_xor')
def main():
test = TestMaximizingXor()
test.test_maximizing_xor()
if __name__ ==... | 19 | 344 |
interactive-coding-challenges | online_judges/license_key/test_format_license_key.py | .py | import unittest
class TestSolution(unittest.TestCase):
def test_format_license_key(self):
solution = Solution()
self.assertRaises(TypeError, solution.format_license_key, None, None)
license_key = '---'
k = 3
expected = ''
self.assertEqual(solution.format_license_ke... | 30 | 834 |
interactive-coding-challenges | online_judges/utopian_tree/test_utopian_tree.py | .py | import unittest
class TestUtopianTree(unittest.TestCase):
def test_utopian_tree(self):
solution = Solution()
self.assertEqual(solution.calc_utopian_tree_height(0), 1)
self.assertEqual(solution.calc_utopian_tree_height(1), 2)
self.assertEqual(solution.calc_utopian_tree_height(4), 7... | 21 | 478 |
interactive-coding-challenges | online_judges/sub_two/test_sub_two.py | .py | import unittest
class TestSubTwo(unittest.TestCase):
def test_sub_two(self):
solution = Solution()
self.assertRaises(TypeError, solution.sub_two, None)
self.assertEqual(solution.sub_two(7, 5), 2)
self.assertEqual(solution.sub_two(-5, -7), 2)
self.assertEqual(solution.sub_t... | 23 | 531 |
interactive-coding-challenges | online_judges/assign_cookies/test_assign_cookie.py | .py | import unittest
class TestAssignCookie(unittest.TestCase):
def test_assign_cookie(self):
solution = Solution()
self.assertRaises(TypeError, solution.find_content_children, None, None)
self.assertEqual(solution.find_content_children([1, 2, 3],
... | 25 | 780 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.