id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
178,632
from typing import List import torch import torch.nn as nn import torch.nn.functional as F from transformers import BitsAndBytesConfig, CLIPVisionModel from utils.utils import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IMAGE_PATCH_TOKEN) from .llava.model.language_model.llava_llama ...
Compute the DICE loss, similar to generalized IOU for masks Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class).
178,633
from typing import List import torch import torch.nn as nn import torch.nn.functional as F from transformers import BitsAndBytesConfig, CLIPVisionModel from utils.utils import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IMAGE_PATCH_TOKEN) from .llava.model.language_model.llava_llama ...
Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). Returns: Loss tensor
178,634
from typing import Optional, Tuple, Type import torch import torch.nn as nn import torch.nn.functional as F from .common import LayerNorm2d, MLPBlock The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function `def window_partition( x: torch.T...
Partition into non-overlapping windows with padding if needed. Args: x (tensor): input tokens with [B, H, W, C]. window_size (int): window size. Returns: windows: windows after partition with [B * num_windows, window_size, window_size, C]. (Hp, Wp): padded height and width before partition
178,635
from typing import Optional, Tuple, Type import torch import torch.nn as nn import torch.nn.functional as F from .common import LayerNorm2d, MLPBlock The provided code snippet includes necessary dependencies for implementing the `window_unpartition` function. Write a Python function `def window_unpartition( window...
Window unpartition into original sequences and removing padding. Args: windows (tensor): input tokens with [B * num_windows, window_size, window_size, C]. window_size (int): window size. pad_hw (Tuple): padded height and width (Hp, Wp). hw (Tuple): original height and width (H, W) before padding. Returns: x: unpartitio...
178,636
from typing import Optional, Tuple, Type import torch import torch.nn as nn import torch.nn.functional as F from .common import LayerNorm2d, MLPBlock def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: """ Get relative positional embeddings according to the relative positions of ...
Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 Args: attn (Tensor): attention map. q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). rel_pos_h (Te...
178,637
from functools import partial import torch from .modeling import (ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer) def _build_sam( encoder_embed_dim, encoder_depth, encoder_num_heads, encoder_global_attn_indexes, checkpoint=None, ): prompt_embed_dim = 2...
null
178,638
from functools import partial import torch from .modeling import (ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer) def _build_sam( encoder_embed_dim, encoder_depth, encoder_num_heads, encoder_global_attn_indexes, checkpoint=None, ): prompt_embed_dim = 2...
null
178,639
from functools import partial import torch from .modeling import (ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer) def _build_sam( encoder_embed_dim, encoder_depth, encoder_num_heads, encoder_global_attn_indexes, checkpoint=None, ): prompt_embed_dim = 2...
null
178,640
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor: x0, y0, _, _ = crop_box offset = torch.tensor([[x0, y0, x0, y0]], d...
Filter masks at the edge of a crop, but not at the edge of the original image.
178,641
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor: box_xywh = deepcopy(box_xyxy) box_xywh[2] = box_xywh[2] - box_xywh[0] box_xywh[3]...
null
178,642
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]: assert len(args) > 0 and all( len(a) == len(args[0]) for a in a...
null
178,643
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `mask_to_rle_pytorch` function. Write a Python function `def mask_to_rle_pyt...
Encodes masks to an uncompressed RLE, in the format expected by pycoco tools.
178,644
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `rle_to_mask` function. Write a Python function `def rle_to_mask(rle: Dict[s...
Compute a binary mask from an uncompressed RLE.
178,645
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch def area_from_rle(rle: Dict[str, Any]) -> int: return sum(rle["counts"][1::2])
null
178,646
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `calculate_stability_score` function. Write a Python function `def calculate...
Computes the stability score for a batch of masks. The stability score is the IoU between the binary masks obtained by thresholding the predicted mask logits at high and low values.
178,647
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch def build_point_grid(n_per_side: int) -> np.ndarray: """Generates a 2D grid of points evenly spaced in [0,1]x[0,1].""" offset = 1 / (2 * n_per_side)...
Generates point grids for all crop layers.
178,648
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `generate_crop_boxes` function. Write a Python function `def generate_crop_b...
Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.
178,649
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor: x0, y0, _, _ = crop_box offset = torch.tensor([[x0, y0]], device=poin...
null
178,650
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch def uncrop_masks( masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int ) -> torch.Tensor: x0, y0, x1, y1 = crop_box if x0 == 0 an...
null
178,651
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `remove_small_regions` function. Write a Python function `def remove_small_r...
Removes small disconnected regions and holes in a mask. Returns the mask and an indicator of if the mask has been modified.
178,652
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]: from pycocotools import mask as mask_utils # type: ignore h, w = uncompr...
null
178,653
import math from copy import deepcopy from itertools import product from typing import Any, Dict, Generator, ItemsView, List, Tuple import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `batched_mask_to_box` function. Write a Python function `def batched_mask_to...
Calculates boxes in XYXY format around masks. Return [0,0,0,0] for an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
178,654
import datetime import logging import logging.handlers import os import sys import requests from llava.constants import LOGDIR handler = None class StreamToLogger(object): def __init__(self, logger, log_level=logging.INFO): def __getattr__(self, attr): def write(self, buf): def flush(self): LOGDIR ...
null
178,655
import datetime import logging import logging.handlers import os import sys import requests from llava.constants import LOGDIR The provided code snippet includes necessary dependencies for implementing the `disable_torch_init` function. Write a Python function `def disable_torch_init()` to solve the following problem:...
Disable the redundant torch default initialization to accelerate model creation.
178,656
import datetime import logging import logging.handlers import os import sys import requests from llava.constants import LOGDIR The provided code snippet includes necessary dependencies for implementing the `violates_moderation` function. Write a Python function `def violates_moderation(text)` to solve the following pr...
Check whether the text violates OpenAI moderation API.
178,658
import copy import json import logging import os import pathlib from dataclasses import dataclass, field from typing import Dict, List, Optional, Sequence import torch import transformers from llava import conversation as conversation_lib from llava.constants import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, ...
null
178,659
import copy import json import logging import os import pathlib from dataclasses import dataclass, field from typing import Dict, List, Optional, Sequence import torch import transformers from llava import conversation as conversation_lib from llava.constants import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, ...
Given a list of sources, each is a conversation list. This transform: 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; 2. Concatenate conversations together; 3. Tokenize the concatenated conversation; 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
178,660
import copy import json import logging import os import pathlib from dataclasses import dataclass, field from typing import Dict, List, Optional, Sequence import torch import transformers from llava import conversation as conversation_lib from llava.constants import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, ...
null
178,661
import logging from typing import List, Optional, Tuple import torch import transformers from einops import rearrange from torch import nn from transformers.models.llama.modeling_llama import apply_rotary_pos_emb from flash_attn.bert_padding import pad_input, unpad_input def forward( self, hidden_states: torch....
null
178,662
import base64 from io import BytesIO import torch from PIL import Image from transformers import StoppingCriteria from .constants import IMAGE_TOKEN_INDEX def load_image_from_base64(image): return Image.open(BytesIO(base64.b64decode(image)))
null
178,663
import base64 from io import BytesIO import torch from PIL import Image from transformers import StoppingCriteria from .constants import IMAGE_TOKEN_INDEX def process_images(images, image_processor, model_cfg): return image_processor(images, return_tensors="pt")["pixel_values"]
null
178,664
import base64 from io import BytesIO import torch from PIL import Image from transformers import StoppingCriteria from .constants import IMAGE_TOKEN_INDEX def get_model_name_from_path(model_path): model_path = model_path.strip("/") model_paths = model_path.split("/") if model_paths[-1].startswith("checkpoi...
null
178,665
from .clip_encoder import CLIPVisionTower class CLIPVisionTower(nn.Module): def __init__(self, vision_tower, args, delay_load=False): super().__init__() self.is_loaded = False self.vision_tower_name = vision_tower self.select_layer = args.mm_vision_select_layer self.select...
null
178,666
import os import shutil import torch from llava.constants import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IMAGE_PATCH_TOKEN) from llava.model import * from transformers import (AutoConfig, AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig) DEFA...
null
178,667
import argparse import torch from llava import LlavaLlamaForCausalLM from tqdm import tqdm from transformers import AutoModelForCausalLM, AutoTokenizer def apply_delta(base_model_path, target_model_path, delta_path): print("Loading base model") base = AutoModelForCausalLM.from_pretrained( base_model_pa...
null
178,668
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from packaging import version from torch import nn from .norm import LPLayerNorm def scaled_multihead_dot_product_attention( query, key, value, n_heads, past_key_value=None, s...
null
178,669
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from packaging import version from torch import nn from .norm import LPLayerNorm def _reset_is_causal( num_query_tokens: int, num_key_tokens: int, original_is_causal: bool ): if original_is_ca...
null
178,670
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from packaging import version from torch import nn from .norm import LPLayerNorm def _reset_is_causal( num_query_tokens: int, num_key_tokens: int, original_is_causal: bool ): if original_is_ca...
null
178,671
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from packaging import version from torch import nn from .norm import LPLayerNorm def attn_bias_shape( attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id ): if attn_impl ==...
null
178,672
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from packaging import version from torch import nn from .norm import LPLayerNorm def build_alibi_bias( n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None ): alibi_bias = t...
null
178,676
import math import torch import triton_pre_mlir as triton import triton_pre_mlir.language as tl def _fwd_kernel( Q, K, V, Bias, Out, Lse, TMP, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride...
null
178,677
import math import torch import triton_pre_mlir as triton import triton_pre_mlir.language as tl def _bwd_preprocess_do_o_dot( Out, DO, Delta, stride_ob, stride_oh, stride_om, stride_dob, stride_doh, stride_dom, nheads, seqlen_q, seqlen_q_rounded, headdim, BLOCK_M:...
null
178,678
from contextlib import contextmanager import torch import torch.nn as nn def init_on_device(device: torch.device, include_buffers: bool = False): """Device initialization context manager. A context manager under which models are initialized with all parameters on the specified device. Args: devi...
Meta initialization context manager. A context manager under which models are initialized with all parameters on the meta device, therefore creating an empty model. Useful when just initializing the model would blow the available RAM. Args: include_buffers (`bool`, *optional*, defaults to `False`): Whether or not to al...
178,680
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def _normal_param_init_fn_( module: nn.Module, std: float, n_layers: int, d_model: Optional[int...
null
178,682
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] ...
null
178,683
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] ...
null
178,684
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] ...
null
178,685
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] ...
null
178,686
import math import warnings from types import MethodType from typing import Any, Dict, List, Optional, Tuple, Union import torch from transformers.models.bloom.modeling_bloom import ( BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss) fr...
Converts a HuggingFace Causal LM to a Prefix LM. Supported HuggingFace model classes: - `GPT2LMHeadModel` - `GPTNeoForCausalLM` - `GPTNeoXForCausalLM` - `GPTJForCausalLM` - `BloomForCausalLM` - `OPTForCausalLM` Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the `generate` method ...
178,687
import math import warnings from types import MethodType from typing import Any, Dict, List, Optional, Tuple, Union import torch from transformers.models.bloom.modeling_bloom import ( BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss) fr...
Attempts to add bidirectional_mask to batch if missing. Raises: KeyError if bidirectional_mask is missing and can't be inferred
178,688
from typing import Union from transformers import (AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast) Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] NUM_SENTINEL_TOKENS: int = 100 The provided code snippet includes necessary dependencies for implementing the `adapt_...
Adds sentinel tokens and padding token (if missing). Expands the tokenizer vocabulary to include sentinel tokens used in mixture-of-denoiser tasks as well as a padding token. All added tokens are added as special tokens. No tokens are added if sentinel tokens and padding token already exist.
178,689
import argparse import torch from llava.model.utils import auto_upgrade from tqdm import tqdm from transformers import AutoModelForCausalLM, AutoTokenizer def auto_upgrade(config): cfg = AutoConfig.from_pretrained(config) if "llava" in config and "llava" not in cfg.model_type: assert cfg.model_type == ...
null
178,690
import argparse import torch from llava.model import * from llava.model.utils import auto_upgrade from transformers import AutoModelForCausalLM, AutoTokenizer def auto_upgrade(config): cfg = AutoConfig.from_pretrained(config) if "llava" in config and "llava" not in cfg.model_type: assert cfg.model_type...
null
178,691
import json import os import random import cv2 import torch import torch.nn.functional as F from transformers import CLIPImageProcessor from model.llava import conversation as conversation_lib from model.segment_anything.utils.transforms import ResizeLongestSide from .utils import DEFAULT_IMAGE_TOKEN DEFAULT_IMAGE_TOK...
null
178,692
import glob import json import os import cv2 import numpy as np def get_mask_from_json(json_path, img): try: with open(json_path, "r") as r: anno = json.loads(r.read()) except: with open(json_path, "r", encoding="cp1252") as r: anno = json.loads(r.read()) inform = a...
null
178,693
import contextlib import copy import io import logging import os import random import numpy as np import pycocotools.mask as mask_util from detectron2.structures import Boxes, BoxMode, PolygonMasks, RotatedBoxes from detectron2.utils.file_io import PathManager from fvcore.common.timer import Timer from PIL import Image...
null
178,694
import dataclasses from enum import Enum, auto from typing import Any, List conv_one_shot = Conversation( system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.", roles=("Human", "Assistant"), ...
null
178,695
import glob import os import random import cv2 import numpy as np import torch import torch.nn.functional as F from pycocotools import mask from transformers import CLIPImageProcessor from model.llava import conversation as conversation_lib from model.llava.constants import (DEFAULT_IMAGE_TOKEN, IGNORE_INDEX, ...
null
178,696
import glob import json import os import random import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image from pycocotools.coco import COCO from transformers import CLIPImageProcessor from model.llava import conversation as conversation_lib from model.segment_anything.utils.transf...
null
178,697
import glob import json import os import random import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image from pycocotools.coco import COCO from transformers import CLIPImageProcessor from model.llava import conversation as conversation_lib from model.segment_anything.utils.transf...
null
178,698
import glob import json import os import random import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image from pycocotools.coco import COCO from transformers import CLIPImageProcessor from model.llava import conversation as conversation_lib from model.segment_anything.utils.transf...
null
178,699
import glob import json import os import random import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image from pycocotools.coco import COCO from transformers import CLIPImageProcessor from model.llava import conversation as conversation_lib from model.segment_anything.utils.transf...
null
178,700
import glob import json import os import random import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image from pycocotools.coco import COCO from transformers import CLIPImageProcessor from model.llava import conversation as conversation_lib from model.segment_anything.utils.transf...
null
178,701
def lcs(s1, s2): cols = len(s1) + 1 rows = len(s2) + 1 t = [[0 for i in range(cols)] for i in range(rows)] max_length = 0 for i in range(1, rows): for j in range(1, cols): if s2[i-1] == s1[j-1]: t[i][j] = t[i-1][j-1] + 1 max_length = max(max_l...
null
178,702
The provided code snippet includes necessary dependencies for implementing the `prefix_sums` function. Write a Python function `def prefix_sums(ls: [int]) -> [int]` to solve the following problem: Returns list of prefix sums for given list of integers. Here is the function: def prefix_sums(ls: [int]) -> [int]: ...
Returns list of prefix sums for given list of integers.
178,703
The provided code snippet includes necessary dependencies for implementing the `prefix_function` function. Write a Python function `def prefix_function(s: str) -> [int]` to solve the following problem: The prefix function for string s is defined as an array pi of length n, where pi[i] is the length of the longest pro...
The prefix function for string s is defined as an array pi of length n, where pi[i] is the length of the longest proper prefix of the substring s[0...i] which is also a suffix of this substring. A proper prefix of a string is a prefix that is not equal to the string itself. By definition, pi[0] = 0.
178,704
def find_seq(arr): seq = {} count = 0 for num in arr: if num - 1 in seq: seq[num] = seq[num - 1] + 1 count = max(count, seq[num]) else: seq[num] = 1 return count
null
178,705
def LIS(arr): n = len(arr) if n == 0: return 0 res = 1 dp = [0] * n dp[0] = 1 for i in range(1, n): dp[i] = 1; for j in range(0 , i): if arr[i] > arr[j]: dp[i] = max(dp[i] , dp[j] + 1) res = max(res , dp[i]) return res
null
178,706
def longest_palindromic_substring_DP(s): S = [[False for i in range(len(s))] for j in range(len(s))] max_palindrome = "" for i in range(len(s))[::-1]: for j in range(i, len(s)): # if j - 1 < 3, then there is one or two characters between these # two positions, implying t...
null
178,707
def longest_palindromic_substring_expansion(s): max_palindrome = "" for i in range(len(s) * 2 - 1): if i % 2 == 0: # This is when you are "on" an actual character # o = offset, ind = current character o = 0 ind = i // 2 while ind + o < len(s...
null
178,708
def lcs(s1, s2): cols = len(s1) + 1 rows = len(s2) + 1 t = [[0 for i in range(cols)] for i in range(rows)] max_length = 0 for i in range(1, rows): for j in range(1, cols): if s2[i-1] == s1[j-1]: t[i][j] = 1 + t[i-1][j-1] else: t[i]...
null
178,709
def find_partiion(arr, n) : sum = 0 # Calculate sum of all elements for i in range(n) : sum += arr[i] if (sum % 2 != 0) : return 0 part = [0] * ((sum // 2) + 1) # Initialize the part array as 0 for i in range((sum // 2) + 1) : part[i] = 0 # Fill the partition table in bottom up manner for i in range...
null
178,710
ans, elements = find_seq(arr, len(arr)) def find_seq(arr, n): s = set() for num in arr: s.add(num) ans = 0 elements = [] for i in range(n): temp = [] if arr[i] - 1 not in s: j = arr[i] while j in s: temp.append(j) ...
null
178,711
def find_length(arr, k): hash_table = {} mod_arr = [] s = 0 length = 0 start, end = 0, 0 for i in range(0, len(arr)): s += arr[i] mod_arr.append(s % k) for i in range(0, len(mod_arr)): if mod_arr[i] == 0: length += 1 else: if mod_ar...
null
178,712
import functools def hamilton_cycle(graph, n): height = 1 << n dp = [[False for _ in range(n)] for _ in range(height)] for i in range(n): dp[1 << i][i] = True for i in range(height): ones, zeros = [], [] for pos in range(n): if (1 << pos) & i: ones....
null
178,713
def min_coins(coins, total): cols = total + 1 min_coins = [float('inf')] * (total + 1) coins_used = [-1] * (total + 1) min_coins[0] = 0 # to form 0, we need 0 coins for i in range(0, len(coins)): for j in range(1, len(min_coins)): if coins[i] > j: # if the coin value is mo...
null
178,714
The provided code snippet includes necessary dependencies for implementing the `find_subarray` function. Write a Python function `def find_subarray(arr, k)` to solve the following problem: True means divisible by k Here is the function: def find_subarray(arr, k): """ True means divisible by k """ st...
True means divisible by k
178,715
def knapsack(values, weights, total): total_items = len(weights) rows = total_items + 1 cols = total + 1 # rows are the number of items # columns are the values of weights required t = [[0 for i in range(cols)] for i in range(rows)] for i in range(1, rows): for j in range(1, co...
null
178,716
The provided code snippet includes necessary dependencies for implementing the `check_luhn` function. Write a Python function `def check_luhn(card_number)` to solve the following problem: Luhn algorithm or Luhn formula is a simple checksum formula used to validate a variety of identification numbers, such as credit c...
Luhn algorithm or Luhn formula is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in some of the countries. It takes a number as an input (Assuming cardnumber as a string) and returns true or false based upon...
178,717
The provided code snippet includes necessary dependencies for implementing the `front_and_back_search` function. Write a Python function `def front_and_back_search(lst, item)` to solve the following problem: args: lst: an unsorted array of integers item: data to be found return: item which is found else False Here i...
args: lst: an unsorted array of integers item: data to be found return: item which is found else False
178,718
import codecs import random def processSeed(seed, mostFreqSeed, mostFreq, ch, k, mp): seed += ch if len(seed) == k+1: oldSeed = seed[:-1] mp.setdefault(oldSeed, []).append(ch) if mostFreq < len(mp[oldSeed]): mostFreq, mostFreqSeed = len(mp[oldSeed]), oldSeed seed = s...
null
178,719
import codecs import random MAX_LETTERS = 2000 def generateText(mp, mostFreqSeed): text, curSeed = mostFreqSeed, mostFreqSeed while (len(text) < MAX_LETTERS): ch = random.choice(mp[curSeed]) text, curSeed = text+ch, curSeed+ch curSeed = curSeed[1:] return text
null
178,720
def merge_sort(arr): if len(arr) >1: mid = len(arr)//2 #Finding the mid of the array L = arr[:mid] # Dividing the array elements R = arr[mid:] # into 2 halves merge_sort(L) # Sorting the first half merge_sort(R) # Sorting the second half i = j = k = 0 # C...
null
178,721
my_min = min(a) my_max = max(a) size = my_max - my_min + 1 holes = [0] * size for x in a: assert type(x) is int, "integers only please" holes[x - my_min] += 1 i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = co...
null
178,722
def find_smallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selection_sort(arr): new_arr = [] for i in range(len(arr)): smallest = find_sma...
null
178,723
def counting_sort(arr): # Find min and max values min_value = min(arr) max_value = max(arr) # Count number appearances in the array counting_arr = [0]*(max_value-min_value+1) for num in arr: counting_arr[num-min_value] += 1 # Rearrange sequence in the array index = 0 ...
null
178,724
def heapify(nums, heap_size, root_index): # Assume the index of the largest element is the root index largest = root_index left_child = (2 * root_index) + 1 right_child = (2 * root_index) + 2 # If the left child of the root is a valid index, and the element is greater # than the current largest ...
null
178,725
import random def is_sorted(a): n = len(a) for i in range(0, n - 1): if (a[i] > a[i + 1]): return False return True def shuffle(a): n = len(a) for i in range(0, n): r = random.randint(0, n - 1) a[i], a[r] = a[r], a[i] def bogo_sort(a): n = len(a) while (i...
null
178,726
def insertion_sort(lst): for i in range(1,len(lst)): while(i > 0 and lst[i] < lst[i - 1]): lst[i], lst[i - 1] = lst[i - 1], lst[i] i -= 1 return lst
null
178,727
The provided code snippet includes necessary dependencies for implementing the `gnome_sort` function. Write a Python function `def gnome_sort(arr)` to solve the following problem: Examples: >>> gnome_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] >>> gnome_sort([]) [] >>> gnome_sort([-2, -45, -5]) [-45, -5, -2] Here is the f...
Examples: >>> gnome_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] >>> gnome_sort([]) [] >>> gnome_sort([-2, -45, -5]) [-45, -5, -2]
178,728
def qsort(arr): if len(arr) <= 1: return arr pivot = arr.pop() greater, lesser = [], [] for item in arr: if item > pivot: greater.append(item) else: lesser.append(item) return qsort(lesser) + [pivot] + qsort(greater)
null
178,729
def shell_sort(arr): # Start with a big gap, then reduce the gap n = len(arr) gap = int(n / 2) # Do a gapped insertion sort for this gap size. # The first gap elements a[0..gap-1] are already in gapped # order keep adding one more element until the entire array # is gap sorted while ...
null
178,730
def bubble_sort(array): n = len(array) for i in range(n): for j in range(0, n-i-1): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] return array
null
178,731
The provided code snippet includes necessary dependencies for implementing the `bubble_sort_optimized` function. Write a Python function `def bubble_sort_optimized(array)` to solve the following problem: Optimizes on bubble sort by taking care of already swapped cases Reference - https://github.com/prabhupant/python-...
Optimizes on bubble sort by taking care of already swapped cases Reference - https://github.com/prabhupant/python-ds/pull/346
178,732
The provided code snippet includes necessary dependencies for implementing the `getSum` function. Write a Python function `def getSum(a, b)` to solve the following problem: :type a: int :type b: int :rtype: int Here is the function: def getSum(a, b): """ :type a: int :type b: int :rt...
:type a: int :type b: int :rtype: int
178,733
The provided code snippet includes necessary dependencies for implementing the `countBits` function. Write a Python function `def countBits(n)` to solve the following problem: Consider a number x and half of the number (x//2). The binary representation of x has all the digits as the binary representation of x//2 foll...
Consider a number x and half of the number (x//2). The binary representation of x has all the digits as the binary representation of x//2 followed by an additional digit at the last position. Therefore, we can find the number of set bits in x by finding the number of set bits in x//2 and determining whether the last di...
178,734
def cost(arr, A, B): n = len(arr) m = len(arr[0]) ans = 0 for i in range(n): j = 0 while j < m: if arr[i][j] == '*': # tile is already there j += 1 continue if j == m - 1: # if j is pointing to last tile, you can use...
null
178,735
def find_platforms(arrival, departure): n = len(arrival) arrival.sort() departure.sort() i = 1 j = 0 ans = 1 # atleast one platform is required plat = 1 while i < n and j < n: if arrival[i] <= departure[j]: plat += 1 i += 1 elif arrival[i] ...
null
178,736
import math def egyptian_fraction(nr, dr): ef = [] while nr != 0: x = math.ceil(dr / nr) ef.append(x) nr = x * nr - dr dr = dr * x
null
178,737
def find_activities(arr): n = len(arr) selected = [] arr.sort(key = lambda x: x[1]) i = 0 # since it is a greedy algorithm, the first acitivity is always # selected because it is the most optimal choice at that point selected.append(arr[i]) for j in range(1, n): start_time_...
null