Fix: Ensure all skills are tracked as files, not submodules

This commit is contained in:
sck_0
2026-01-14 18:48:48 +01:00
parent 7f46ed8ca1
commit 8bd204708b
1113 changed files with 82065 additions and 2 deletions

Submodule skills/claude-d3js-skill deleted from e198c87d03

View File

@@ -0,0 +1,820 @@
---
name: d3-viz
description: Creating interactive data visualisations using d3.js. This skill should be used when creating custom charts, graphs, network diagrams, geographic visualisations, or any complex SVG-based data visualisation that requires fine-grained control over visual elements, transitions, or interactions. Use this for bespoke visualisations beyond standard charting libraries, whether in React, Vue, Svelte, vanilla JavaScript, or any other environment.
---
# D3.js Visualisation
## Overview
This skill provides guidance for creating sophisticated, interactive data visualisations using d3.js. D3.js (Data-Driven Documents) excels at binding data to DOM elements and applying data-driven transformations to create custom, publication-quality visualisations with precise control over every visual element. The techniques work across any JavaScript environment, including vanilla JavaScript, React, Vue, Svelte, and other frameworks.
## When to use d3.js
**Use d3.js for:**
- Custom visualisations requiring unique visual encodings or layouts
- Interactive explorations with complex pan, zoom, or brush behaviours
- Network/graph visualisations (force-directed layouts, tree diagrams, hierarchies, chord diagrams)
- Geographic visualisations with custom projections
- Visualisations requiring smooth, choreographed transitions
- Publication-quality graphics with fine-grained styling control
- Novel chart types not available in standard libraries
**Consider alternatives for:**
- 3D visualisations - use Three.js instead
## Core workflow
### 1. Set up d3.js
Import d3 at the top of your script:
```javascript
import * as d3 from 'd3';
```
Or use the CDN version (7.x):
```html
<script src="https://d3js.org/d3.v7.min.js"></script>
```
All modules (scales, axes, shapes, transitions, etc.) are accessible through the `d3` namespace.
### 2. Choose the integration pattern
**Pattern A: Direct DOM manipulation (recommended for most cases)**
Use d3 to select DOM elements and manipulate them imperatively. This works in any JavaScript environment:
```javascript
function drawChart(data) {
if (!data || data.length === 0) return;
const svg = d3.select('#chart'); // Select by ID, class, or DOM element
// Clear previous content
svg.selectAll("*").remove();
// Set up dimensions
const width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
// Create scales, axes, and draw visualisation
// ... d3 code here ...
}
// Call when data changes
drawChart(myData);
```
**Pattern B: Declarative rendering (for frameworks with templating)**
Use d3 for data calculations (scales, layouts) but render elements via your framework:
```javascript
function getChartElements(data) {
const xScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([0, 400]);
return data.map((d, i) => ({
x: 50,
y: i * 30,
width: xScale(d.value),
height: 25
}));
}
// In React: {getChartElements(data).map((d, i) => <rect key={i} {...d} fill="steelblue" />)}
// In Vue: v-for directive over the returned array
// In vanilla JS: Create elements manually from the returned data
```
Use Pattern A for complex visualisations with transitions, interactions, or when leveraging d3's full capabilities. Use Pattern B for simpler visualisations or when your framework prefers declarative rendering.
### 3. Structure the visualisation code
Follow this standard structure in your drawing function:
```javascript
function drawVisualization(data) {
if (!data || data.length === 0) return;
const svg = d3.select('#chart'); // Or pass a selector/element
svg.selectAll("*").remove(); // Clear previous render
// 1. Define dimensions
const width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
// 2. Create main group with margins
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// 3. Create scales
const xScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.x)])
.range([0, innerWidth]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.y)])
.range([innerHeight, 0]); // Note: inverted for SVG coordinates
// 4. Create and append axes
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
g.append("g")
.attr("transform", `translate(0,${innerHeight})`)
.call(xAxis);
g.append("g")
.call(yAxis);
// 5. Bind data and create visual elements
g.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("r", 5)
.attr("fill", "steelblue");
}
// Call when data changes
drawVisualization(myData);
```
### 4. Implement responsive sizing
Make visualisations responsive to container size:
```javascript
function setupResponsiveChart(containerId, data) {
const container = document.getElementById(containerId);
const svg = d3.select(`#${containerId}`).append('svg');
function updateChart() {
const { width, height } = container.getBoundingClientRect();
svg.attr('width', width).attr('height', height);
// Redraw visualisation with new dimensions
drawChart(data, svg, width, height);
}
// Update on initial load
updateChart();
// Update on window resize
window.addEventListener('resize', updateChart);
// Return cleanup function
return () => window.removeEventListener('resize', updateChart);
}
// Usage:
// const cleanup = setupResponsiveChart('chart-container', myData);
// cleanup(); // Call when component unmounts or element removed
```
Or use ResizeObserver for more direct container monitoring:
```javascript
function setupResponsiveChartWithObserver(svgElement, data) {
const observer = new ResizeObserver(() => {
const { width, height } = svgElement.getBoundingClientRect();
d3.select(svgElement)
.attr('width', width)
.attr('height', height);
// Redraw visualisation
drawChart(data, d3.select(svgElement), width, height);
});
observer.observe(svgElement.parentElement);
return () => observer.disconnect();
}
```
## Common visualisation patterns
### Bar chart
```javascript
function drawBarChart(data, svgElement) {
if (!data || data.length === 0) return;
const svg = d3.select(svgElement);
svg.selectAll("*").remove();
const width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const xScale = d3.scaleBand()
.domain(data.map(d => d.category))
.range([0, innerWidth])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([innerHeight, 0]);
g.append("g")
.attr("transform", `translate(0,${innerHeight})`)
.call(d3.axisBottom(xScale));
g.append("g")
.call(d3.axisLeft(yScale));
g.selectAll("rect")
.data(data)
.join("rect")
.attr("x", d => xScale(d.category))
.attr("y", d => yScale(d.value))
.attr("width", xScale.bandwidth())
.attr("height", d => innerHeight - yScale(d.value))
.attr("fill", "steelblue");
}
// Usage:
// drawBarChart(myData, document.getElementById('chart'));
```
### Line chart
```javascript
const line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.value))
.curve(d3.curveMonotoneX); // Smooth curve
g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2)
.attr("d", line);
```
### Scatter plot
```javascript
g.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("r", d => sizeScale(d.size)) // Optional: size encoding
.attr("fill", d => colourScale(d.category)) // Optional: colour encoding
.attr("opacity", 0.7);
```
### Chord diagram
A chord diagram shows relationships between entities in a circular layout, with ribbons representing flows between them:
```javascript
function drawChordDiagram(data) {
// data format: array of objects with source, target, and value
// Example: [{ source: 'A', target: 'B', value: 10 }, ...]
if (!data || data.length === 0) return;
const svg = d3.select('#chart');
svg.selectAll("*").remove();
const width = 600;
const height = 600;
const innerRadius = Math.min(width, height) * 0.3;
const outerRadius = innerRadius + 30;
// Create matrix from data
const nodes = Array.from(new Set(data.flatMap(d => [d.source, d.target])));
const matrix = Array.from({ length: nodes.length }, () => Array(nodes.length).fill(0));
data.forEach(d => {
const i = nodes.indexOf(d.source);
const j = nodes.indexOf(d.target);
matrix[i][j] += d.value;
matrix[j][i] += d.value;
});
// Create chord layout
const chord = d3.chord()
.padAngle(0.05)
.sortSubgroups(d3.descending);
const arc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
const ribbon = d3.ribbon()
.source(d => d.source)
.target(d => d.target);
const colourScale = d3.scaleOrdinal(d3.schemeCategory10)
.domain(nodes);
const g = svg.append("g")
.attr("transform", `translate(${width / 2},${height / 2})`);
const chords = chord(matrix);
// Draw ribbons
g.append("g")
.attr("fill-opacity", 0.67)
.selectAll("path")
.data(chords)
.join("path")
.attr("d", ribbon)
.attr("fill", d => colourScale(nodes[d.source.index]))
.attr("stroke", d => d3.rgb(colourScale(nodes[d.source.index])).darker());
// Draw groups (arcs)
const group = g.append("g")
.selectAll("g")
.data(chords.groups)
.join("g");
group.append("path")
.attr("d", arc)
.attr("fill", d => colourScale(nodes[d.index]))
.attr("stroke", d => d3.rgb(colourScale(nodes[d.index])).darker());
// Add labels
group.append("text")
.each(d => { d.angle = (d.startAngle + d.endAngle) / 2; })
.attr("dy", "0.31em")
.attr("transform", d => `rotate(${(d.angle * 180 / Math.PI) - 90})translate(${outerRadius + 30})${d.angle > Math.PI ? "rotate(180)" : ""}`)
.attr("text-anchor", d => d.angle > Math.PI ? "end" : null)
.text((d, i) => nodes[i])
.style("font-size", "12px");
}
```
### Heatmap
A heatmap uses colour to encode values in a two-dimensional grid, useful for showing patterns across categories:
```javascript
function drawHeatmap(data) {
// data format: array of objects with row, column, and value
// Example: [{ row: 'A', column: 'X', value: 10 }, ...]
if (!data || data.length === 0) return;
const svg = d3.select('#chart');
svg.selectAll("*").remove();
const width = 800;
const height = 600;
const margin = { top: 100, right: 30, bottom: 30, left: 100 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
// Get unique rows and columns
const rows = Array.from(new Set(data.map(d => d.row)));
const columns = Array.from(new Set(data.map(d => d.column)));
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// Create scales
const xScale = d3.scaleBand()
.domain(columns)
.range([0, innerWidth])
.padding(0.01);
const yScale = d3.scaleBand()
.domain(rows)
.range([0, innerHeight])
.padding(0.01);
// Colour scale for values
const colourScale = d3.scaleSequential(d3.interpolateYlOrRd)
.domain([0, d3.max(data, d => d.value)]);
// Draw rectangles
g.selectAll("rect")
.data(data)
.join("rect")
.attr("x", d => xScale(d.column))
.attr("y", d => yScale(d.row))
.attr("width", xScale.bandwidth())
.attr("height", yScale.bandwidth())
.attr("fill", d => colourScale(d.value));
// Add x-axis labels
svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`)
.selectAll("text")
.data(columns)
.join("text")
.attr("x", d => xScale(d) + xScale.bandwidth() / 2)
.attr("y", -10)
.attr("text-anchor", "middle")
.text(d => d)
.style("font-size", "12px");
// Add y-axis labels
svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`)
.selectAll("text")
.data(rows)
.join("text")
.attr("x", -10)
.attr("y", d => yScale(d) + yScale.bandwidth() / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "end")
.text(d => d)
.style("font-size", "12px");
// Add colour legend
const legendWidth = 20;
const legendHeight = 200;
const legend = svg.append("g")
.attr("transform", `translate(${width - 60},${margin.top})`);
const legendScale = d3.scaleLinear()
.domain(colourScale.domain())
.range([legendHeight, 0]);
const legendAxis = d3.axisRight(legendScale)
.ticks(5);
// Draw colour gradient in legend
for (let i = 0; i < legendHeight; i++) {
legend.append("rect")
.attr("y", i)
.attr("width", legendWidth)
.attr("height", 1)
.attr("fill", colourScale(legendScale.invert(i)));
}
legend.append("g")
.attr("transform", `translate(${legendWidth},0)`)
.call(legendAxis);
}
```
### Pie chart
```javascript
const pie = d3.pie()
.value(d => d.value)
.sort(null);
const arc = d3.arc()
.innerRadius(0)
.outerRadius(Math.min(width, height) / 2 - 20);
const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
const g = svg.append("g")
.attr("transform", `translate(${width / 2},${height / 2})`);
g.selectAll("path")
.data(pie(data))
.join("path")
.attr("d", arc)
.attr("fill", (d, i) => colourScale(i))
.attr("stroke", "white")
.attr("stroke-width", 2);
```
### Force-directed network
```javascript
const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id).distance(100))
.force("charge", d3.forceManyBody().strength(-300))
.force("center", d3.forceCenter(width / 2, height / 2));
const link = g.selectAll("line")
.data(links)
.join("line")
.attr("stroke", "#999")
.attr("stroke-width", 1);
const node = g.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 8)
.attr("fill", "steelblue")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
simulation.on("tick", () => {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
});
function dragstarted(event) {
if (!event.active) simulation.alphaTarget(0.3).restart();
event.subject.fx = event.subject.x;
event.subject.fy = event.subject.y;
}
function dragged(event) {
event.subject.fx = event.x;
event.subject.fy = event.y;
}
function dragended(event) {
if (!event.active) simulation.alphaTarget(0);
event.subject.fx = null;
event.subject.fy = null;
}
```
## Adding interactivity
### Tooltips
```javascript
// Create tooltip div (outside SVG)
const tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("position", "absolute")
.style("visibility", "hidden")
.style("background-color", "white")
.style("border", "1px solid #ddd")
.style("padding", "10px")
.style("border-radius", "4px")
.style("pointer-events", "none");
// Add to elements
circles
.on("mouseover", function(event, d) {
d3.select(this).attr("opacity", 1);
tooltip
.style("visibility", "visible")
.html(`<strong>${d.label}</strong><br/>Value: ${d.value}`);
})
.on("mousemove", function(event) {
tooltip
.style("top", (event.pageY - 10) + "px")
.style("left", (event.pageX + 10) + "px");
})
.on("mouseout", function() {
d3.select(this).attr("opacity", 0.7);
tooltip.style("visibility", "hidden");
});
```
### Zoom and pan
```javascript
const zoom = d3.zoom()
.scaleExtent([0.5, 10])
.on("zoom", (event) => {
g.attr("transform", event.transform);
});
svg.call(zoom);
```
### Click interactions
```javascript
circles
.on("click", function(event, d) {
// Handle click (dispatch event, update app state, etc.)
console.log("Clicked:", d);
// Visual feedback
d3.selectAll("circle").attr("fill", "steelblue");
d3.select(this).attr("fill", "orange");
// Optional: dispatch custom event for your framework/app to listen to
// window.dispatchEvent(new CustomEvent('chartClick', { detail: d }));
});
```
## Transitions and animations
Add smooth transitions to visual changes:
```javascript
// Basic transition
circles
.transition()
.duration(750)
.attr("r", 10);
// Chained transitions
circles
.transition()
.duration(500)
.attr("fill", "orange")
.transition()
.duration(500)
.attr("r", 15);
// Staggered transitions
circles
.transition()
.delay((d, i) => i * 50)
.duration(500)
.attr("cy", d => yScale(d.value));
// Custom easing
circles
.transition()
.duration(1000)
.ease(d3.easeBounceOut)
.attr("r", 10);
```
## Scales reference
### Quantitative scales
```javascript
// Linear scale
const xScale = d3.scaleLinear()
.domain([0, 100])
.range([0, 500]);
// Log scale (for exponential data)
const logScale = d3.scaleLog()
.domain([1, 1000])
.range([0, 500]);
// Power scale
const powScale = d3.scalePow()
.exponent(2)
.domain([0, 100])
.range([0, 500]);
// Time scale
const timeScale = d3.scaleTime()
.domain([new Date(2020, 0, 1), new Date(2024, 0, 1)])
.range([0, 500]);
```
### Ordinal scales
```javascript
// Band scale (for bar charts)
const bandScale = d3.scaleBand()
.domain(['A', 'B', 'C', 'D'])
.range([0, 400])
.padding(0.1);
// Point scale (for line/scatter categories)
const pointScale = d3.scalePoint()
.domain(['A', 'B', 'C', 'D'])
.range([0, 400]);
// Ordinal scale (for colours)
const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
```
### Sequential scales
```javascript
// Sequential colour scale
const colourScale = d3.scaleSequential(d3.interpolateBlues)
.domain([0, 100]);
// Diverging colour scale
const divScale = d3.scaleDiverging(d3.interpolateRdBu)
.domain([-10, 0, 10]);
```
## Best practices
### Data preparation
Always validate and prepare data before visualisation:
```javascript
// Filter invalid values
const cleanData = data.filter(d => d.value != null && !isNaN(d.value));
// Sort data if order matters
const sortedData = [...data].sort((a, b) => b.value - a.value);
// Parse dates
const parsedData = data.map(d => ({
...d,
date: d3.timeParse("%Y-%m-%d")(d.date)
}));
```
### Performance optimisation
For large datasets (>1000 elements):
```javascript
// Use canvas instead of SVG for many elements
// Use quadtree for collision detection
// Simplify paths with d3.line().curve(d3.curveStep)
// Implement virtual scrolling for large lists
// Use requestAnimationFrame for custom animations
```
### Accessibility
Make visualisations accessible:
```javascript
// Add ARIA labels
svg.attr("role", "img")
.attr("aria-label", "Bar chart showing quarterly revenue");
// Add title and description
svg.append("title").text("Quarterly Revenue 2024");
svg.append("desc").text("Bar chart showing revenue growth across four quarters");
// Ensure sufficient colour contrast
// Provide keyboard navigation for interactive elements
// Include data table alternative
```
### Styling
Use consistent, professional styling:
```javascript
// Define colour palettes upfront
const colours = {
primary: '#4A90E2',
secondary: '#7B68EE',
background: '#F5F7FA',
text: '#333333',
gridLines: '#E0E0E0'
};
// Apply consistent typography
svg.selectAll("text")
.style("font-family", "Inter, sans-serif")
.style("font-size", "12px");
// Use subtle grid lines
g.selectAll(".tick line")
.attr("stroke", colours.gridLines)
.attr("stroke-dasharray", "2,2");
```
## Common issues and solutions
**Issue**: Axes not appearing
- Ensure scales have valid domains (check for NaN values)
- Verify axis is appended to correct group
- Check transform translations are correct
**Issue**: Transitions not working
- Call `.transition()` before attribute changes
- Ensure elements have unique keys for proper data binding
- Check that useEffect dependencies include all changing data
**Issue**: Responsive sizing not working
- Use ResizeObserver or window resize listener
- Update dimensions in state to trigger re-render
- Ensure SVG has width/height attributes or viewBox
**Issue**: Performance problems
- Limit number of DOM elements (consider canvas for >1000 items)
- Debounce resize handlers
- Use `.join()` instead of separate enter/update/exit selections
- Avoid unnecessary re-renders by checking dependencies
## Resources
### references/
Contains detailed reference materials:
- `d3-patterns.md` - Comprehensive collection of visualisation patterns and code examples
- `scale-reference.md` - Complete guide to d3 scales with examples
- `colour-schemes.md` - D3 colour schemes and palette recommendations
### assets/
Contains boilerplate templates:
- `chart-template.js` - Starter template for basic chart
- `interactive-template.js` - Template with tooltips, zoom, and interactions
- `sample-data.json` - Example datasets for testing
These templates work with vanilla JavaScript, React, Vue, Svelte, or any other JavaScript environment. Adapt them as needed for your specific framework.
To use these resources, read the relevant files when detailed guidance is needed for specific visualisation types or patterns.

View File

@@ -0,0 +1,106 @@
import { useEffect, useRef, useState } from 'react';
import * as d3 from 'd3';
function BasicChart({ data }) {
const svgRef = useRef();
useEffect(() => {
if (!data || data.length === 0) return;
// Select SVG element
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove(); // Clear previous content
// Define dimensions and margins
const width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
// Create main group with margins
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// Create scales
const xScale = d3.scaleBand()
.domain(data.map(d => d.label))
.range([0, innerWidth])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([innerHeight, 0])
.nice();
// Create and append axes
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
g.append("g")
.attr("class", "x-axis")
.attr("transform", `translate(0,${innerHeight})`)
.call(xAxis);
g.append("g")
.attr("class", "y-axis")
.call(yAxis);
// Bind data and create visual elements (bars in this example)
g.selectAll("rect")
.data(data)
.join("rect")
.attr("x", d => xScale(d.label))
.attr("y", d => yScale(d.value))
.attr("width", xScale.bandwidth())
.attr("height", d => innerHeight - yScale(d.value))
.attr("fill", "steelblue");
// Optional: Add axis labels
g.append("text")
.attr("class", "axis-label")
.attr("x", innerWidth / 2)
.attr("y", innerHeight + margin.bottom - 5)
.attr("text-anchor", "middle")
.text("Category");
g.append("text")
.attr("class", "axis-label")
.attr("transform", "rotate(-90)")
.attr("x", -innerHeight / 2)
.attr("y", -margin.left + 15)
.attr("text-anchor", "middle")
.text("Value");
}, [data]);
return (
<div className="chart-container">
<svg
ref={svgRef}
width="800"
height="400"
style={{ border: '1px solid #ddd' }}
/>
</div>
);
}
// Example usage
export default function App() {
const sampleData = [
{ label: 'A', value: 30 },
{ label: 'B', value: 80 },
{ label: 'C', value: 45 },
{ label: 'D', value: 60 },
{ label: 'E', value: 20 },
{ label: 'F', value: 90 }
];
return (
<div className="p-8">
<h1 className="text-2xl font-bold mb-4">Basic D3.js Chart</h1>
<BasicChart data={sampleData} />
</div>
);
}

View File

@@ -0,0 +1,227 @@
import { useEffect, useRef, useState } from 'react';
import * as d3 from 'd3';
function InteractiveChart({ data }) {
const svgRef = useRef();
const tooltipRef = useRef();
const [selectedPoint, setSelectedPoint] = useState(null);
useEffect(() => {
if (!data || data.length === 0) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
// Dimensions
const width = 800;
const height = 500;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
// Create main group
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// Scales
const xScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.x)])
.range([0, innerWidth])
.nice();
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.y)])
.range([innerHeight, 0])
.nice();
const sizeScale = d3.scaleSqrt()
.domain([0, d3.max(data, d => d.size || 10)])
.range([3, 20]);
const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
// Add zoom behaviour
const zoom = d3.zoom()
.scaleExtent([0.5, 10])
.on("zoom", (event) => {
g.attr("transform", `translate(${margin.left + event.transform.x},${margin.top + event.transform.y}) scale(${event.transform.k})`);
});
svg.call(zoom);
// Axes
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
const xAxisGroup = g.append("g")
.attr("class", "x-axis")
.attr("transform", `translate(0,${innerHeight})`)
.call(xAxis);
const yAxisGroup = g.append("g")
.attr("class", "y-axis")
.call(yAxis);
// Grid lines
g.append("g")
.attr("class", "grid")
.attr("opacity", 0.1)
.call(d3.axisLeft(yScale)
.tickSize(-innerWidth)
.tickFormat(""));
g.append("g")
.attr("class", "grid")
.attr("opacity", 0.1)
.attr("transform", `translate(0,${innerHeight})`)
.call(d3.axisBottom(xScale)
.tickSize(-innerHeight)
.tickFormat(""));
// Tooltip
const tooltip = d3.select(tooltipRef.current);
// Data points
const circles = g.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("r", d => sizeScale(d.size || 10))
.attr("fill", d => colourScale(d.category || 'default'))
.attr("stroke", "#fff")
.attr("stroke-width", 2)
.attr("opacity", 0.7)
.style("cursor", "pointer");
// Hover interactions
circles
.on("mouseover", function(event, d) {
// Enlarge circle
d3.select(this)
.transition()
.duration(200)
.attr("opacity", 1)
.attr("stroke-width", 3);
// Show tooltip
tooltip
.style("display", "block")
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 10) + "px")
.html(`
<strong>${d.label || 'Point'}</strong><br/>
X: ${d.x.toFixed(2)}<br/>
Y: ${d.y.toFixed(2)}<br/>
${d.category ? `Category: ${d.category}<br/>` : ''}
${d.size ? `Size: ${d.size.toFixed(2)}` : ''}
`);
})
.on("mousemove", function(event) {
tooltip
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 10) + "px");
})
.on("mouseout", function() {
// Restore circle
d3.select(this)
.transition()
.duration(200)
.attr("opacity", 0.7)
.attr("stroke-width", 2);
// Hide tooltip
tooltip.style("display", "none");
})
.on("click", function(event, d) {
// Highlight selected point
circles.attr("stroke", "#fff").attr("stroke-width", 2);
d3.select(this)
.attr("stroke", "#000")
.attr("stroke-width", 3);
setSelectedPoint(d);
});
// Add transition on initial render
circles
.attr("r", 0)
.transition()
.duration(800)
.delay((d, i) => i * 20)
.attr("r", d => sizeScale(d.size || 10));
// Axis labels
g.append("text")
.attr("class", "axis-label")
.attr("x", innerWidth / 2)
.attr("y", innerHeight + margin.bottom - 5)
.attr("text-anchor", "middle")
.style("font-size", "14px")
.text("X Axis");
g.append("text")
.attr("class", "axis-label")
.attr("transform", "rotate(-90)")
.attr("x", -innerHeight / 2)
.attr("y", -margin.left + 15)
.attr("text-anchor", "middle")
.style("font-size", "14px")
.text("Y Axis");
}, [data]);
return (
<div className="relative">
<svg
ref={svgRef}
width="800"
height="500"
style={{ border: '1px solid #ddd', cursor: 'grab' }}
/>
<div
ref={tooltipRef}
style={{
position: 'absolute',
display: 'none',
padding: '10px',
background: 'white',
border: '1px solid #ddd',
borderRadius: '4px',
pointerEvents: 'none',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
fontSize: '13px',
zIndex: 1000
}}
/>
{selectedPoint && (
<div className="mt-4 p-4 bg-blue-50 rounded border border-blue-200">
<h3 className="font-bold mb-2">Selected Point</h3>
<pre className="text-sm">{JSON.stringify(selectedPoint, null, 2)}</pre>
</div>
)}
</div>
);
}
// Example usage
export default function App() {
const sampleData = Array.from({ length: 50 }, (_, i) => ({
id: i,
label: `Point ${i + 1}`,
x: Math.random() * 100,
y: Math.random() * 100,
size: Math.random() * 30 + 5,
category: ['A', 'B', 'C', 'D'][Math.floor(Math.random() * 4)]
}));
return (
<div className="p-8">
<h1 className="text-2xl font-bold mb-2">Interactive D3.js Chart</h1>
<p className="text-gray-600 mb-4">
Hover over points for details. Click to select. Scroll to zoom. Drag to pan.
</p>
<InteractiveChart data={sampleData} />
</div>
);
}

View File

@@ -0,0 +1,115 @@
{
"timeSeries": [
{ "date": "2024-01-01", "value": 120, "category": "A" },
{ "date": "2024-02-01", "value": 135, "category": "A" },
{ "date": "2024-03-01", "value": 128, "category": "A" },
{ "date": "2024-04-01", "value": 145, "category": "A" },
{ "date": "2024-05-01", "value": 152, "category": "A" },
{ "date": "2024-06-01", "value": 168, "category": "A" },
{ "date": "2024-07-01", "value": 175, "category": "A" },
{ "date": "2024-08-01", "value": 182, "category": "A" },
{ "date": "2024-09-01", "value": 190, "category": "A" },
{ "date": "2024-10-01", "value": 185, "category": "A" },
{ "date": "2024-11-01", "value": 195, "category": "A" },
{ "date": "2024-12-01", "value": 210, "category": "A" }
],
"categorical": [
{ "label": "Product A", "value": 450, "category": "Electronics" },
{ "label": "Product B", "value": 320, "category": "Electronics" },
{ "label": "Product C", "value": 580, "category": "Clothing" },
{ "label": "Product D", "value": 290, "category": "Clothing" },
{ "label": "Product E", "value": 410, "category": "Food" },
{ "label": "Product F", "value": 370, "category": "Food" }
],
"scatterData": [
{ "x": 12, "y": 45, "size": 25, "category": "Group A", "label": "Point 1" },
{ "x": 25, "y": 62, "size": 35, "category": "Group A", "label": "Point 2" },
{ "x": 38, "y": 55, "size": 20, "category": "Group B", "label": "Point 3" },
{ "x": 45, "y": 78, "size": 40, "category": "Group B", "label": "Point 4" },
{ "x": 52, "y": 68, "size": 30, "category": "Group C", "label": "Point 5" },
{ "x": 65, "y": 85, "size": 45, "category": "Group C", "label": "Point 6" },
{ "x": 72, "y": 72, "size": 28, "category": "Group A", "label": "Point 7" },
{ "x": 85, "y": 92, "size": 50, "category": "Group B", "label": "Point 8" }
],
"hierarchical": {
"name": "Root",
"children": [
{
"name": "Category 1",
"children": [
{ "name": "Item 1.1", "value": 100 },
{ "name": "Item 1.2", "value": 150 },
{ "name": "Item 1.3", "value": 80 }
]
},
{
"name": "Category 2",
"children": [
{ "name": "Item 2.1", "value": 200 },
{ "name": "Item 2.2", "value": 120 },
{ "name": "Item 2.3", "value": 90 }
]
},
{
"name": "Category 3",
"children": [
{ "name": "Item 3.1", "value": 180 },
{ "name": "Item 3.2", "value": 140 }
]
}
]
},
"network": {
"nodes": [
{ "id": "A", "group": 1 },
{ "id": "B", "group": 1 },
{ "id": "C", "group": 1 },
{ "id": "D", "group": 2 },
{ "id": "E", "group": 2 },
{ "id": "F", "group": 3 },
{ "id": "G", "group": 3 },
{ "id": "H", "group": 3 }
],
"links": [
{ "source": "A", "target": "B", "value": 1 },
{ "source": "A", "target": "C", "value": 2 },
{ "source": "B", "target": "C", "value": 1 },
{ "source": "C", "target": "D", "value": 3 },
{ "source": "D", "target": "E", "value": 2 },
{ "source": "E", "target": "F", "value": 1 },
{ "source": "F", "target": "G", "value": 2 },
{ "source": "F", "target": "H", "value": 1 },
{ "source": "G", "target": "H", "value": 1 }
]
},
"stackedData": [
{ "group": "Q1", "seriesA": 30, "seriesB": 40, "seriesC": 25 },
{ "group": "Q2", "seriesA": 45, "seriesB": 35, "seriesC": 30 },
{ "group": "Q3", "seriesA": 40, "seriesB": 50, "seriesC": 35 },
{ "group": "Q4", "seriesA": 55, "seriesB": 45, "seriesC": 40 }
],
"geographicPoints": [
{ "city": "London", "latitude": 51.5074, "longitude": -0.1278, "value": 8900000 },
{ "city": "Paris", "latitude": 48.8566, "longitude": 2.3522, "value": 2140000 },
{ "city": "Berlin", "latitude": 52.5200, "longitude": 13.4050, "value": 3645000 },
{ "city": "Madrid", "latitude": 40.4168, "longitude": -3.7038, "value": 3223000 },
{ "city": "Rome", "latitude": 41.9028, "longitude": 12.4964, "value": 2873000 }
],
"divergingData": [
{ "category": "Item A", "value": -15 },
{ "category": "Item B", "value": 8 },
{ "category": "Item C", "value": -22 },
{ "category": "Item D", "value": 18 },
{ "category": "Item E", "value": -5 },
{ "category": "Item F", "value": 25 },
{ "category": "Item G", "value": -12 },
{ "category": "Item H", "value": 14 }
]
}

View File

@@ -0,0 +1,564 @@
# D3.js Colour Schemes and Palette Recommendations
Comprehensive guide to colour selection in data visualisation with d3.js.
## Built-in categorical colour schemes
### Category10 (default)
```javascript
d3.schemeCategory10
// ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
// '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
```
**Characteristics:**
- 10 distinct colours
- Good colour-blind accessibility
- Default choice for most categorical data
- Balanced saturation and brightness
**Use cases:** General purpose categorical encoding, legend items, multiple data series
### Tableau10
```javascript
d3.schemeTableau10
```
**Characteristics:**
- 10 colours optimised for data visualisation
- Professional appearance
- Excellent distinguishability
**Use cases:** Business dashboards, professional reports, presentations
### Accent
```javascript
d3.schemeAccent
// 8 colours with high saturation
```
**Characteristics:**
- Bright, vibrant colours
- High contrast
- Modern aesthetic
**Use cases:** Highlighting important categories, modern web applications
### Dark2
```javascript
d3.schemeDark2
// 8 darker, muted colours
```
**Characteristics:**
- Subdued palette
- Professional appearance
- Good for dark backgrounds
**Use cases:** Dark mode visualisations, professional contexts
### Paired
```javascript
d3.schemePaired
// 12 colours in pairs of similar hues
```
**Characteristics:**
- Pairs of light and dark variants
- Useful for nested categories
- 12 distinct colours
**Use cases:** Grouped bar charts, hierarchical categories, before/after comparisons
### Pastel1 & Pastel2
```javascript
d3.schemePastel1 // 9 colours
d3.schemePastel2 // 8 colours
```
**Characteristics:**
- Soft, low-saturation colours
- Gentle appearance
- Good for large areas
**Use cases:** Background colours, subtle categorisation, calming visualisations
### Set1, Set2, Set3
```javascript
d3.schemeSet1 // 9 colours - vivid
d3.schemeSet2 // 8 colours - muted
d3.schemeSet3 // 12 colours - pastel
```
**Characteristics:**
- Set1: High saturation, maximum distinction
- Set2: Professional, balanced
- Set3: Subtle, many categories
**Use cases:** Varied based on visual hierarchy needs
## Sequential colour schemes
Sequential schemes map continuous data from low to high values using a single hue or gradient.
### Single-hue sequential
**Blues:**
```javascript
d3.interpolateBlues
d3.schemeBlues[9] // 9-step discrete version
```
**Other single-hue options:**
- `d3.interpolateGreens` / `d3.schemeGreens`
- `d3.interpolateOranges` / `d3.schemeOranges`
- `d3.interpolatePurples` / `d3.schemePurples`
- `d3.interpolateReds` / `d3.schemeReds`
- `d3.interpolateGreys` / `d3.schemeGreys`
**Use cases:**
- Simple heat maps
- Choropleth maps
- Density plots
- Single-metric visualisations
### Multi-hue sequential
**Viridis (recommended):**
```javascript
d3.interpolateViridis
```
**Characteristics:**
- Perceptually uniform
- Colour-blind friendly
- Print-safe
- No visual dead zones
- Monotonically increasing perceived lightness
**Other perceptually-uniform options:**
- `d3.interpolatePlasma` - Purple to yellow
- `d3.interpolateInferno` - Black to white through red/orange
- `d3.interpolateMagma` - Black to white through purple
- `d3.interpolateCividis` - Colour-blind optimised
**Colour-blind accessible:**
```javascript
d3.interpolateTurbo // Rainbow-like but perceptually uniform
d3.interpolateCool // Cyan to magenta
d3.interpolateWarm // Orange to yellow
```
**Use cases:**
- Scientific visualisation
- Medical imaging
- Any high-precision data visualisation
- Accessible visualisations
### Traditional sequential
**Yellow-Orange-Red:**
```javascript
d3.interpolateYlOrRd
d3.schemeYlOrRd[9]
```
**Yellow-Green-Blue:**
```javascript
d3.interpolateYlGnBu
d3.schemeYlGnBu[9]
```
**Other multi-hue:**
- `d3.interpolateBuGn` - Blue to green
- `d3.interpolateBuPu` - Blue to purple
- `d3.interpolateGnBu` - Green to blue
- `d3.interpolateOrRd` - Orange to red
- `d3.interpolatePuBu` - Purple to blue
- `d3.interpolatePuBuGn` - Purple to blue-green
- `d3.interpolatePuRd` - Purple to red
- `d3.interpolateRdPu` - Red to purple
- `d3.interpolateYlGn` - Yellow to green
- `d3.interpolateYlOrBr` - Yellow to orange-brown
**Use cases:** Traditional data visualisation, familiar colour associations (temperature, vegetation, water)
## Diverging colour schemes
Diverging schemes highlight deviations from a central value using two distinct hues.
### Red-Blue (temperature)
```javascript
d3.interpolateRdBu
d3.schemeRdBu[11]
```
**Characteristics:**
- Intuitive temperature metaphor
- Strong contrast
- Clear positive/negative distinction
**Use cases:** Temperature, profit/loss, above/below average, correlation
### Red-Yellow-Blue
```javascript
d3.interpolateRdYlBu
d3.schemeRdYlBu[11]
```
**Characteristics:**
- Three-colour gradient
- Softer transition through yellow
- More visual steps
**Use cases:** When extreme values need emphasis and middle needs visibility
### Other diverging schemes
**Traffic light:**
```javascript
d3.interpolateRdYlGn // Red (bad) to green (good)
```
**Spectral (rainbow):**
```javascript
d3.interpolateSpectral // Full spectrum
```
**Other options:**
- `d3.interpolateBrBG` - Brown to blue-green
- `d3.interpolatePiYG` - Pink to yellow-green
- `d3.interpolatePRGn` - Purple to green
- `d3.interpolatePuOr` - Purple to orange
- `d3.interpolateRdGy` - Red to grey
**Use cases:** Choose based on semantic meaning and accessibility needs
## Colour-blind friendly palettes
### General guidelines
1. **Avoid red-green combinations** (most common colour blindness)
2. **Use blue-orange diverging** instead of red-green
3. **Add texture or patterns** as redundant encoding
4. **Test with simulation tools**
### Recommended colour-blind safe schemes
**Categorical:**
```javascript
// Okabe-Ito palette (colour-blind safe)
const okabePalette = [
'#E69F00', // Orange
'#56B4E9', // Sky blue
'#009E73', // Bluish green
'#F0E442', // Yellow
'#0072B2', // Blue
'#D55E00', // Vermillion
'#CC79A7', // Reddish purple
'#000000' // Black
];
const colourScale = d3.scaleOrdinal()
.domain(categories)
.range(okabePalette);
```
**Sequential:**
```javascript
// Use Viridis, Cividis, or Blues
d3.interpolateViridis // Best overall
d3.interpolateCividis // Optimised for CVD
d3.interpolateBlues // Simple, safe
```
**Diverging:**
```javascript
// Use blue-orange instead of red-green
d3.interpolateBrBG
d3.interpolatePuOr
```
## Custom colour palettes
### Creating custom sequential
```javascript
const customSequential = d3.scaleLinear()
.domain([0, 100])
.range(['#e8f4f8', '#006d9c']) // Light to dark blue
.interpolate(d3.interpolateLab); // Perceptually uniform
```
### Creating custom diverging
```javascript
const customDiverging = d3.scaleLinear()
.domain([0, 50, 100])
.range(['#ca0020', '#f7f7f7', '#0571b0']) // Red, grey, blue
.interpolate(d3.interpolateLab);
```
### Creating custom categorical
```javascript
// Brand colours
const brandPalette = [
'#FF6B6B', // Primary red
'#4ECDC4', // Secondary teal
'#45B7D1', // Tertiary blue
'#FFA07A', // Accent coral
'#98D8C8' // Accent mint
];
const colourScale = d3.scaleOrdinal()
.domain(categories)
.range(brandPalette);
```
## Semantic colour associations
### Universal colour meanings
**Red:**
- Danger, error, negative
- High temperature
- Debt, loss
**Green:**
- Success, positive
- Growth, vegetation
- Profit, gain
**Blue:**
- Trust, calm
- Water, cold
- Information, neutral
**Yellow/Orange:**
- Warning, caution
- Energy, warmth
- Attention
**Grey:**
- Neutral, inactive
- Missing data
- Background
### Context-specific palettes
**Financial:**
```javascript
const financialColours = {
profit: '#27ae60',
loss: '#e74c3c',
neutral: '#95a5a6',
highlight: '#3498db'
};
```
**Temperature:**
```javascript
const temperatureScale = d3.scaleSequential(d3.interpolateRdYlBu)
.domain([40, -10]); // Hot to cold (reversed)
```
**Traffic/Status:**
```javascript
const statusColours = {
success: '#27ae60',
warning: '#f39c12',
error: '#e74c3c',
info: '#3498db',
neutral: '#95a5a6'
};
```
## Accessibility best practices
### Contrast ratios
Ensure sufficient contrast between colours and backgrounds:
```javascript
// Good contrast example
const highContrast = {
background: '#ffffff',
text: '#2c3e50',
primary: '#3498db',
secondary: '#e74c3c'
};
```
**WCAG guidelines:**
- Normal text: 4.5:1 minimum
- Large text: 3:1 minimum
- UI components: 3:1 minimum
### Redundant encoding
Never rely solely on colour to convey information:
```javascript
// Add patterns or shapes
const symbols = ['circle', 'square', 'triangle', 'diamond'];
// Add text labels
// Use line styles (solid, dashed, dotted)
// Use size encoding
```
### Testing
Test visualisations for colour blindness:
- Chrome DevTools (Rendering > Emulate vision deficiencies)
- Colour Oracle (free desktop application)
- Coblis (online simulator)
## Professional colour recommendations
### Data journalism
```javascript
// Guardian style
const guardianPalette = [
'#005689', // Guardian blue
'#c70000', // Guardian red
'#7d0068', // Guardian pink
'#951c75', // Guardian purple
];
// FT style
const ftPalette = [
'#0f5499', // FT blue
'#990f3d', // FT red
'#593380', // FT purple
'#262a33', // FT black
];
```
### Academic/Scientific
```javascript
// Nature journal style
const naturePalette = [
'#0071b2', // Blue
'#d55e00', // Vermillion
'#009e73', // Green
'#f0e442', // Yellow
];
// Use Viridis for continuous data
const scientificScale = d3.scaleSequential(d3.interpolateViridis);
```
### Corporate/Business
```javascript
// Professional, conservative
const corporatePalette = [
'#003f5c', // Dark blue
'#58508d', // Purple
'#bc5090', // Magenta
'#ff6361', // Coral
'#ffa600' // Orange
];
```
## Dynamic colour selection
### Based on data range
```javascript
function selectColourScheme(data) {
const extent = d3.extent(data);
const hasNegative = extent[0] < 0;
const hasPositive = extent[1] > 0;
if (hasNegative && hasPositive) {
// Diverging: data crosses zero
return d3.scaleSequentialSymlog(d3.interpolateRdBu)
.domain([extent[0], 0, extent[1]]);
} else {
// Sequential: all positive or all negative
return d3.scaleSequential(d3.interpolateViridis)
.domain(extent);
}
}
```
### Based on category count
```javascript
function selectCategoricalScheme(categories) {
const n = categories.length;
if (n <= 10) {
return d3.scaleOrdinal(d3.schemeTableau10);
} else if (n <= 12) {
return d3.scaleOrdinal(d3.schemePaired);
} else {
// For many categories, use sequential with quantize
return d3.scaleQuantize()
.domain([0, n - 1])
.range(d3.quantize(d3.interpolateRainbow, n));
}
}
```
## Common colour mistakes to avoid
1. **Rainbow gradients for sequential data**
- Problem: Not perceptually uniform, hard to read
- Solution: Use Viridis, Blues, or other uniform schemes
2. **Red-green for diverging (colour blindness)**
- Problem: 8% of males can't distinguish
- Solution: Use blue-orange or purple-green
3. **Too many categorical colours**
- Problem: Hard to distinguish and remember
- Solution: Limit to 5-8 categories, use grouping
4. **Insufficient contrast**
- Problem: Poor readability
- Solution: Test contrast ratios, use darker colours on light backgrounds
5. **Culturally inconsistent colours**
- Problem: Confusing semantic meaning
- Solution: Research colour associations for target audience
6. **Inverted temperature scales**
- Problem: Counterintuitive (red = cold)
- Solution: Red/orange = hot, blue = cold
## Quick reference guide
**Need to show...**
- **Categories (≤10):** `d3.schemeCategory10` or `d3.schemeTableau10`
- **Categories (>10):** `d3.schemePaired` or group categories
- **Sequential (general):** `d3.interpolateViridis`
- **Sequential (scientific):** `d3.interpolateViridis` or `d3.interpolatePlasma`
- **Sequential (temperature):** `d3.interpolateRdYlBu` (inverted)
- **Diverging (zero):** `d3.interpolateRdBu` or `d3.interpolateBrBG`
- **Diverging (good/bad):** `d3.interpolateRdYlGn` (inverted)
- **Colour-blind safe (categorical):** Okabe-Ito palette (shown above)
- **Colour-blind safe (sequential):** `d3.interpolateCividis` or `d3.interpolateBlues`
- **Colour-blind safe (diverging):** `d3.interpolatePuOr` or `d3.interpolateBrBG`
**Always remember:**
1. Test for colour-blindness
2. Ensure sufficient contrast
3. Use semantic colours appropriately
4. Add redundant encoding (patterns, labels)
5. Keep it simple (fewer colours = clearer visualisation)

View File

@@ -0,0 +1,869 @@
# D3.js Visualisation Patterns
This reference provides detailed code patterns for common d3.js visualisation types.
## Hierarchical visualisations
### Tree diagram
```javascript
useEffect(() => {
if (!data) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
const width = 800;
const height = 600;
const tree = d3.tree().size([height - 100, width - 200]);
const root = d3.hierarchy(data);
tree(root);
const g = svg.append("g")
.attr("transform", "translate(100,50)");
// Links
g.selectAll("path")
.data(root.links())
.join("path")
.attr("d", d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x))
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-width", 2);
// Nodes
const node = g.selectAll("g")
.data(root.descendants())
.join("g")
.attr("transform", d => `translate(${d.y},${d.x})`);
node.append("circle")
.attr("r", 6)
.attr("fill", d => d.children ? "#555" : "#999");
node.append("text")
.attr("dy", "0.31em")
.attr("x", d => d.children ? -8 : 8)
.attr("text-anchor", d => d.children ? "end" : "start")
.text(d => d.data.name)
.style("font-size", "12px");
}, [data]);
```
### Treemap
```javascript
useEffect(() => {
if (!data) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
const width = 800;
const height = 600;
const root = d3.hierarchy(data)
.sum(d => d.value)
.sort((a, b) => b.value - a.value);
d3.treemap()
.size([width, height])
.padding(2)
.round(true)(root);
const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
const cell = svg.selectAll("g")
.data(root.leaves())
.join("g")
.attr("transform", d => `translate(${d.x0},${d.y0})`);
cell.append("rect")
.attr("width", d => d.x1 - d.x0)
.attr("height", d => d.y1 - d.y0)
.attr("fill", d => colourScale(d.parent.data.name))
.attr("stroke", "white")
.attr("stroke-width", 2);
cell.append("text")
.attr("x", 4)
.attr("y", 16)
.text(d => d.data.name)
.style("font-size", "12px")
.style("fill", "white");
}, [data]);
```
### Sunburst diagram
```javascript
useEffect(() => {
if (!data) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
const width = 600;
const height = 600;
const radius = Math.min(width, height) / 2;
const root = d3.hierarchy(data)
.sum(d => d.value)
.sort((a, b) => b.value - a.value);
const partition = d3.partition()
.size([2 * Math.PI, radius]);
partition(root);
const arc = d3.arc()
.startAngle(d => d.x0)
.endAngle(d => d.x1)
.innerRadius(d => d.y0)
.outerRadius(d => d.y1);
const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
const g = svg.append("g")
.attr("transform", `translate(${width / 2},${height / 2})`);
g.selectAll("path")
.data(root.descendants())
.join("path")
.attr("d", arc)
.attr("fill", d => colourScale(d.depth))
.attr("stroke", "white")
.attr("stroke-width", 1);
}, [data]);
```
### Chord diagram
```javascript
function drawChordDiagram(data) {
// data format: array of objects with source, target, and value
// Example: [{ source: 'A', target: 'B', value: 10 }, ...]
if (!data || data.length === 0) return;
const svg = d3.select('#chart');
svg.selectAll("*").remove();
const width = 600;
const height = 600;
const innerRadius = Math.min(width, height) * 0.3;
const outerRadius = innerRadius + 30;
// Create matrix from data
const nodes = Array.from(new Set(data.flatMap(d => [d.source, d.target])));
const matrix = Array.from({ length: nodes.length }, () => Array(nodes.length).fill(0));
data.forEach(d => {
const i = nodes.indexOf(d.source);
const j = nodes.indexOf(d.target);
matrix[i][j] += d.value;
matrix[j][i] += d.value;
});
// Create chord layout
const chord = d3.chord()
.padAngle(0.05)
.sortSubgroups(d3.descending);
const arc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
const ribbon = d3.ribbon()
.source(d => d.source)
.target(d => d.target);
const colourScale = d3.scaleOrdinal(d3.schemeCategory10)
.domain(nodes);
const g = svg.append("g")
.attr("transform", `translate(${width / 2},${height / 2})`);
const chords = chord(matrix);
// Draw ribbons
g.append("g")
.attr("fill-opacity", 0.67)
.selectAll("path")
.data(chords)
.join("path")
.attr("d", ribbon)
.attr("fill", d => colourScale(nodes[d.source.index]))
.attr("stroke", d => d3.rgb(colourScale(nodes[d.source.index])).darker());
// Draw groups (arcs)
const group = g.append("g")
.selectAll("g")
.data(chords.groups)
.join("g");
group.append("path")
.attr("d", arc)
.attr("fill", d => colourScale(nodes[d.index]))
.attr("stroke", d => d3.rgb(colourScale(nodes[d.index])).darker());
// Add labels
group.append("text")
.each(d => { d.angle = (d.startAngle + d.endAngle) / 2; })
.attr("dy", "0.31em")
.attr("transform", d => `rotate(${(d.angle * 180 / Math.PI) - 90})translate(${outerRadius + 30})${d.angle > Math.PI ? "rotate(180)" : ""}`)
.attr("text-anchor", d => d.angle > Math.PI ? "end" : null)
.text((d, i) => nodes[i])
.style("font-size", "12px");
}
// Data format example:
// const data = [
// { source: 'Category A', target: 'Category B', value: 100 },
// { source: 'Category A', target: 'Category C', value: 50 },
// { source: 'Category B', target: 'Category C', value: 75 }
// ];
// drawChordDiagram(data);
```
## Advanced chart types
### Heatmap
```javascript
function drawHeatmap(data) {
// data format: array of objects with row, column, and value
// Example: [{ row: 'A', column: 'X', value: 10 }, ...]
if (!data || data.length === 0) return;
const svg = d3.select('#chart');
svg.selectAll("*").remove();
const width = 800;
const height = 600;
const margin = { top: 100, right: 30, bottom: 30, left: 100 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
// Get unique rows and columns
const rows = Array.from(new Set(data.map(d => d.row)));
const columns = Array.from(new Set(data.map(d => d.column)));
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// Create scales
const xScale = d3.scaleBand()
.domain(columns)
.range([0, innerWidth])
.padding(0.01);
const yScale = d3.scaleBand()
.domain(rows)
.range([0, innerHeight])
.padding(0.01);
// Colour scale for values (sequential from light to dark red)
const colourScale = d3.scaleSequential(d3.interpolateYlOrRd)
.domain([0, d3.max(data, d => d.value)]);
// Draw rectangles
g.selectAll("rect")
.data(data)
.join("rect")
.attr("x", d => xScale(d.column))
.attr("y", d => yScale(d.row))
.attr("width", xScale.bandwidth())
.attr("height", yScale.bandwidth())
.attr("fill", d => colourScale(d.value));
// Add x-axis labels
svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`)
.selectAll("text")
.data(columns)
.join("text")
.attr("x", d => xScale(d) + xScale.bandwidth() / 2)
.attr("y", -10)
.attr("text-anchor", "middle")
.text(d => d)
.style("font-size", "12px");
// Add y-axis labels
svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`)
.selectAll("text")
.data(rows)
.join("text")
.attr("x", -10)
.attr("y", d => yScale(d) + yScale.bandwidth() / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "end")
.text(d => d)
.style("font-size", "12px");
// Add colour legend
const legendWidth = 20;
const legendHeight = 200;
const legend = svg.append("g")
.attr("transform", `translate(${width - 60},${margin.top})`);
const legendScale = d3.scaleLinear()
.domain(colourScale.domain())
.range([legendHeight, 0]);
const legendAxis = d3.axisRight(legendScale).ticks(5);
// Draw colour gradient in legend
for (let i = 0; i < legendHeight; i++) {
legend.append("rect")
.attr("y", i)
.attr("width", legendWidth)
.attr("height", 1)
.attr("fill", colourScale(legendScale.invert(i)));
}
legend.append("g")
.attr("transform", `translate(${legendWidth},0)`)
.call(legendAxis);
}
// Data format example:
// const data = [
// { row: 'Monday', column: 'Morning', value: 42 },
// { row: 'Monday', column: 'Afternoon', value: 78 },
// { row: 'Tuesday', column: 'Morning', value: 65 },
// { row: 'Tuesday', column: 'Afternoon', value: 55 }
// ];
// drawHeatmap(data);
```
### Area chart with gradient
```javascript
useEffect(() => {
if (!data || data.length === 0) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
const width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
// Define gradient
const defs = svg.append("defs");
const gradient = defs.append("linearGradient")
.attr("id", "areaGradient")
.attr("x1", "0%")
.attr("x2", "0%")
.attr("y1", "0%")
.attr("y2", "100%");
gradient.append("stop")
.attr("offset", "0%")
.attr("stop-color", "steelblue")
.attr("stop-opacity", 0.8);
gradient.append("stop")
.attr("offset", "100%")
.attr("stop-color", "steelblue")
.attr("stop-opacity", 0.1);
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const xScale = d3.scaleTime()
.domain(d3.extent(data, d => d.date))
.range([0, innerWidth]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([innerHeight, 0]);
const area = d3.area()
.x(d => xScale(d.date))
.y0(innerHeight)
.y1(d => yScale(d.value))
.curve(d3.curveMonotoneX);
g.append("path")
.datum(data)
.attr("fill", "url(#areaGradient)")
.attr("d", area);
const line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.value))
.curve(d3.curveMonotoneX);
g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2)
.attr("d", line);
g.append("g")
.attr("transform", `translate(0,${innerHeight})`)
.call(d3.axisBottom(xScale));
g.append("g")
.call(d3.axisLeft(yScale));
}, [data]);
```
### Stacked bar chart
```javascript
useEffect(() => {
if (!data || data.length === 0) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
const width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const categories = Object.keys(data[0]).filter(k => k !== 'group');
const stackedData = d3.stack().keys(categories)(data);
const xScale = d3.scaleBand()
.domain(data.map(d => d.group))
.range([0, innerWidth])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0, d3.max(stackedData[stackedData.length - 1], d => d[1])])
.range([innerHeight, 0]);
const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
g.selectAll("g")
.data(stackedData)
.join("g")
.attr("fill", (d, i) => colourScale(i))
.selectAll("rect")
.data(d => d)
.join("rect")
.attr("x", d => xScale(d.data.group))
.attr("y", d => yScale(d[1]))
.attr("height", d => yScale(d[0]) - yScale(d[1]))
.attr("width", xScale.bandwidth());
g.append("g")
.attr("transform", `translate(0,${innerHeight})`)
.call(d3.axisBottom(xScale));
g.append("g")
.call(d3.axisLeft(yScale));
}, [data]);
```
### Grouped bar chart
```javascript
useEffect(() => {
if (!data || data.length === 0) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
const width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const categories = Object.keys(data[0]).filter(k => k !== 'group');
const x0Scale = d3.scaleBand()
.domain(data.map(d => d.group))
.range([0, innerWidth])
.padding(0.1);
const x1Scale = d3.scaleBand()
.domain(categories)
.range([0, x0Scale.bandwidth()])
.padding(0.05);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => Math.max(...categories.map(c => d[c])))])
.range([innerHeight, 0]);
const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
const group = g.selectAll("g")
.data(data)
.join("g")
.attr("transform", d => `translate(${x0Scale(d.group)},0)`);
group.selectAll("rect")
.data(d => categories.map(key => ({ key, value: d[key] })))
.join("rect")
.attr("x", d => x1Scale(d.key))
.attr("y", d => yScale(d.value))
.attr("width", x1Scale.bandwidth())
.attr("height", d => innerHeight - yScale(d.value))
.attr("fill", d => colourScale(d.key));
g.append("g")
.attr("transform", `translate(0,${innerHeight})`)
.call(d3.axisBottom(x0Scale));
g.append("g")
.call(d3.axisLeft(yScale));
}, [data]);
```
### Bubble chart
```javascript
useEffect(() => {
if (!data || data.length === 0) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
const width = 800;
const height = 600;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const xScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.x)])
.range([0, innerWidth]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.y)])
.range([innerHeight, 0]);
const sizeScale = d3.scaleSqrt()
.domain([0, d3.max(data, d => d.size)])
.range([0, 50]);
const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
g.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("r", d => sizeScale(d.size))
.attr("fill", d => colourScale(d.category))
.attr("opacity", 0.6)
.attr("stroke", "white")
.attr("stroke-width", 2);
g.append("g")
.attr("transform", `translate(0,${innerHeight})`)
.call(d3.axisBottom(xScale));
g.append("g")
.call(d3.axisLeft(yScale));
}, [data]);
```
## Geographic visualisations
### Basic map with points
```javascript
useEffect(() => {
if (!geoData || !pointData) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
const width = 800;
const height = 600;
const projection = d3.geoMercator()
.fitSize([width, height], geoData);
const pathGenerator = d3.geoPath().projection(projection);
// Draw map
svg.selectAll("path")
.data(geoData.features)
.join("path")
.attr("d", pathGenerator)
.attr("fill", "#e0e0e0")
.attr("stroke", "#999")
.attr("stroke-width", 0.5);
// Draw points
svg.selectAll("circle")
.data(pointData)
.join("circle")
.attr("cx", d => projection([d.longitude, d.latitude])[0])
.attr("cy", d => projection([d.longitude, d.latitude])[1])
.attr("r", 5)
.attr("fill", "steelblue")
.attr("opacity", 0.7);
}, [geoData, pointData]);
```
### Choropleth map
```javascript
useEffect(() => {
if (!geoData || !valueData) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
const width = 800;
const height = 600;
const projection = d3.geoMercator()
.fitSize([width, height], geoData);
const pathGenerator = d3.geoPath().projection(projection);
// Create value lookup
const valueLookup = new Map(valueData.map(d => [d.id, d.value]));
// Colour scale
const colourScale = d3.scaleSequential(d3.interpolateBlues)
.domain([0, d3.max(valueData, d => d.value)]);
svg.selectAll("path")
.data(geoData.features)
.join("path")
.attr("d", pathGenerator)
.attr("fill", d => {
const value = valueLookup.get(d.id);
return value ? colourScale(value) : "#e0e0e0";
})
.attr("stroke", "#999")
.attr("stroke-width", 0.5);
}, [geoData, valueData]);
```
## Advanced interactions
### Brush and zoom
```javascript
useEffect(() => {
if (!data || data.length === 0) return;
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
const width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
const xScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.x)])
.range([0, innerWidth]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.y)])
.range([innerHeight, 0]);
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const circles = g.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("r", 5)
.attr("fill", "steelblue");
// Add brush
const brush = d3.brush()
.extent([[0, 0], [innerWidth, innerHeight]])
.on("start brush", (event) => {
if (!event.selection) return;
const [[x0, y0], [x1, y1]] = event.selection;
circles.attr("fill", d => {
const cx = xScale(d.x);
const cy = yScale(d.y);
return (cx >= x0 && cx <= x1 && cy >= y0 && cy <= y1)
? "orange"
: "steelblue";
});
});
g.append("g")
.attr("class", "brush")
.call(brush);
}, [data]);
```
### Linked brushing between charts
```javascript
function LinkedCharts({ data }) {
const [selectedPoints, setSelectedPoints] = useState(new Set());
const svg1Ref = useRef();
const svg2Ref = useRef();
useEffect(() => {
// Chart 1: Scatter plot
const svg1 = d3.select(svg1Ref.current);
svg1.selectAll("*").remove();
// ... create first chart ...
const circles1 = svg1.selectAll("circle")
.data(data)
.join("circle")
.attr("fill", d => selectedPoints.has(d.id) ? "orange" : "steelblue");
// Chart 2: Bar chart
const svg2 = d3.select(svg2Ref.current);
svg2.selectAll("*").remove();
// ... create second chart ...
const bars = svg2.selectAll("rect")
.data(data)
.join("rect")
.attr("fill", d => selectedPoints.has(d.id) ? "orange" : "steelblue");
// Add brush to first chart
const brush = d3.brush()
.on("start brush end", (event) => {
if (!event.selection) {
setSelectedPoints(new Set());
return;
}
const [[x0, y0], [x1, y1]] = event.selection;
const selected = new Set();
data.forEach(d => {
const x = xScale(d.x);
const y = yScale(d.y);
if (x >= x0 && x <= x1 && y >= y0 && y <= y1) {
selected.add(d.id);
}
});
setSelectedPoints(selected);
});
svg1.append("g").call(brush);
}, [data, selectedPoints]);
return (
<div>
<svg ref={svg1Ref} width="400" height="300" />
<svg ref={svg2Ref} width="400" height="300" />
</div>
);
}
```
## Animation patterns
### Enter, update, exit with transitions
```javascript
useEffect(() => {
if (!data || data.length === 0) return;
const svg = d3.select(svgRef.current);
const circles = svg.selectAll("circle")
.data(data, d => d.id); // Key function for object constancy
// EXIT: Remove old elements
circles.exit()
.transition()
.duration(500)
.attr("r", 0)
.remove();
// UPDATE: Modify existing elements
circles
.transition()
.duration(500)
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("fill", "steelblue");
// ENTER: Add new elements
circles.enter()
.append("circle")
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("r", 0)
.attr("fill", "steelblue")
.transition()
.duration(500)
.attr("r", 5);
}, [data]);
```
### Path morphing
```javascript
useEffect(() => {
if (!data1 || !data2) return;
const svg = d3.select(svgRef.current);
const line = d3.line()
.x(d => xScale(d.x))
.y(d => yScale(d.y))
.curve(d3.curveMonotoneX);
const path = svg.select("path");
// Morph from data1 to data2
path
.datum(data1)
.attr("d", line)
.transition()
.duration(1000)
.attrTween("d", function() {
const previous = d3.select(this).attr("d");
const current = line(data2);
return d3.interpolatePath(previous, current);
});
}, [data1, data2]);
```

View File

@@ -0,0 +1,509 @@
# D3.js Scale Reference
Comprehensive guide to all d3 scale types with examples and use cases.
## Continuous scales
### Linear scale
Maps continuous input domain to continuous output range with linear interpolation.
```javascript
const scale = d3.scaleLinear()
.domain([0, 100])
.range([0, 500]);
scale(50); // Returns 250
scale(0); // Returns 0
scale(100); // Returns 500
// Invert scale (get input from output)
scale.invert(250); // Returns 50
```
**Use cases:**
- Most common scale for quantitative data
- Axes, bar lengths, position encoding
- Temperature, prices, counts, measurements
**Methods:**
- `.domain([min, max])` - Set input domain
- `.range([min, max])` - Set output range
- `.invert(value)` - Get domain value from range value
- `.clamp(true)` - Restrict output to range bounds
- `.nice()` - Extend domain to nice round values
### Power scale
Maps continuous input to continuous output with exponential transformation.
```javascript
const sqrtScale = d3.scalePow()
.exponent(0.5) // Square root
.domain([0, 100])
.range([0, 500]);
const squareScale = d3.scalePow()
.exponent(2) // Square
.domain([0, 100])
.range([0, 500]);
// Shorthand for square root
const sqrtScale2 = d3.scaleSqrt()
.domain([0, 100])
.range([0, 500]);
```
**Use cases:**
- Perceptual scaling (human perception is non-linear)
- Area encoding (use square root to map values to circle radii)
- Emphasising differences in small or large values
### Logarithmic scale
Maps continuous input to continuous output with logarithmic transformation.
```javascript
const logScale = d3.scaleLog()
.domain([1, 1000]) // Must be positive
.range([0, 500]);
logScale(1); // Returns 0
logScale(10); // Returns ~167
logScale(100); // Returns ~333
logScale(1000); // Returns 500
```
**Use cases:**
- Data spanning multiple orders of magnitude
- Population, GDP, wealth distributions
- Logarithmic axes
- Exponential growth visualisations
**Important:** Domain values must be strictly positive (>0).
### Time scale
Specialised linear scale for temporal data.
```javascript
const timeScale = d3.scaleTime()
.domain([new Date(2020, 0, 1), new Date(2024, 0, 1)])
.range([0, 800]);
timeScale(new Date(2022, 0, 1)); // Returns 400
// Invert to get date
timeScale.invert(400); // Returns Date object for mid-2022
```
**Use cases:**
- Time series visualisations
- Timeline axes
- Temporal animations
- Date-based interactions
**Methods:**
- `.nice()` - Extend domain to nice time intervals
- `.ticks(count)` - Generate nicely-spaced tick values
- All linear scale methods apply
### Quantize scale
Maps continuous input to discrete output buckets.
```javascript
const quantizeScale = d3.scaleQuantize()
.domain([0, 100])
.range(['low', 'medium', 'high']);
quantizeScale(25); // Returns 'low'
quantizeScale(50); // Returns 'medium'
quantizeScale(75); // Returns 'high'
// Get the threshold values
quantizeScale.thresholds(); // Returns [33.33, 66.67]
```
**Use cases:**
- Binning continuous data
- Heat map colours
- Risk categories (low/medium/high)
- Age groups, income brackets
### Quantile scale
Maps continuous input to discrete output based on quantiles.
```javascript
const quantileScale = d3.scaleQuantile()
.domain([3, 6, 7, 8, 8, 10, 13, 15, 16, 20, 24]) // Sample data
.range(['low', 'medium', 'high']);
quantileScale(8); // Returns based on quantile position
quantileScale.quantiles(); // Returns quantile thresholds
```
**Use cases:**
- Equal-size groups regardless of distribution
- Percentile-based categorisation
- Handling skewed distributions
### Threshold scale
Maps continuous input to discrete output with custom thresholds.
```javascript
const thresholdScale = d3.scaleThreshold()
.domain([0, 10, 20])
.range(['freezing', 'cold', 'warm', 'hot']);
thresholdScale(-5); // Returns 'freezing'
thresholdScale(5); // Returns 'cold'
thresholdScale(15); // Returns 'warm'
thresholdScale(25); // Returns 'hot'
```
**Use cases:**
- Custom breakpoints
- Grade boundaries (A, B, C, D, F)
- Temperature categories
- Air quality indices
## Sequential scales
### Sequential colour scale
Maps continuous input to continuous colour gradient.
```javascript
const colourScale = d3.scaleSequential(d3.interpolateBlues)
.domain([0, 100]);
colourScale(0); // Returns lightest blue
colourScale(50); // Returns mid blue
colourScale(100); // Returns darkest blue
```
**Available interpolators:**
**Single hue:**
- `d3.interpolateBlues`, `d3.interpolateGreens`, `d3.interpolateReds`
- `d3.interpolateOranges`, `d3.interpolatePurples`, `d3.interpolateGreys`
**Multi-hue:**
- `d3.interpolateViridis`, `d3.interpolateInferno`, `d3.interpolateMagma`
- `d3.interpolatePlasma`, `d3.interpolateWarm`, `d3.interpolateCool`
- `d3.interpolateCubehelixDefault`, `d3.interpolateTurbo`
**Use cases:**
- Heat maps, choropleth maps
- Continuous data visualisation
- Temperature, elevation, density
### Diverging colour scale
Maps continuous input to diverging colour gradient with a midpoint.
```javascript
const divergingScale = d3.scaleDiverging(d3.interpolateRdBu)
.domain([-10, 0, 10]);
divergingScale(-10); // Returns red
divergingScale(0); // Returns white/neutral
divergingScale(10); // Returns blue
```
**Available interpolators:**
- `d3.interpolateRdBu` - Red to blue
- `d3.interpolateRdYlBu` - Red, yellow, blue
- `d3.interpolateRdYlGn` - Red, yellow, green
- `d3.interpolatePiYG` - Pink, yellow, green
- `d3.interpolateBrBG` - Brown, blue-green
- `d3.interpolatePRGn` - Purple, green
- `d3.interpolatePuOr` - Purple, orange
- `d3.interpolateRdGy` - Red, grey
- `d3.interpolateSpectral` - Rainbow spectrum
**Use cases:**
- Data with meaningful midpoint (zero, average, neutral)
- Positive/negative values
- Above/below comparisons
- Correlation matrices
### Sequential quantile scale
Combines sequential colour with quantile mapping.
```javascript
const sequentialQuantileScale = d3.scaleSequentialQuantile(d3.interpolateBlues)
.domain([3, 6, 7, 8, 8, 10, 13, 15, 16, 20, 24]);
// Maps based on quantile position
```
**Use cases:**
- Perceptually uniform binning
- Handling outliers
- Skewed distributions
## Ordinal scales
### Band scale
Maps discrete input to continuous bands (rectangles) with optional padding.
```javascript
const bandScale = d3.scaleBand()
.domain(['A', 'B', 'C', 'D'])
.range([0, 400])
.padding(0.1);
bandScale('A'); // Returns start position (e.g., 0)
bandScale('B'); // Returns start position (e.g., 110)
bandScale.bandwidth(); // Returns width of each band (e.g., 95)
bandScale.step(); // Returns total step including padding
bandScale.paddingInner(); // Returns inner padding (between bands)
bandScale.paddingOuter(); // Returns outer padding (at edges)
```
**Use cases:**
- Bar charts (most common use case)
- Grouped elements
- Categorical axes
- Heat map cells
**Padding options:**
- `.padding(value)` - Sets both inner and outer padding (0-1)
- `.paddingInner(value)` - Padding between bands (0-1)
- `.paddingOuter(value)` - Padding at edges (0-1)
- `.align(value)` - Alignment of bands (0-1, default 0.5)
### Point scale
Maps discrete input to continuous points (no width).
```javascript
const pointScale = d3.scalePoint()
.domain(['A', 'B', 'C', 'D'])
.range([0, 400])
.padding(0.5);
pointScale('A'); // Returns position (e.g., 50)
pointScale('B'); // Returns position (e.g., 150)
pointScale('C'); // Returns position (e.g., 250)
pointScale('D'); // Returns position (e.g., 350)
pointScale.step(); // Returns distance between points
```
**Use cases:**
- Line chart categorical x-axis
- Scatter plot with categorical axis
- Node positions in network graphs
- Any point positioning for categories
### Ordinal colour scale
Maps discrete input to discrete output (colours, shapes, etc.).
```javascript
const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
colourScale('apples'); // Returns first colour
colourScale('oranges'); // Returns second colour
colourScale('apples'); // Returns same first colour (consistent)
// Custom range
const customScale = d3.scaleOrdinal()
.domain(['cat1', 'cat2', 'cat3'])
.range(['#FF6B6B', '#4ECDC4', '#45B7D1']);
```
**Built-in colour schemes:**
**Categorical:**
- `d3.schemeCategory10` - 10 colours
- `d3.schemeAccent` - 8 colours
- `d3.schemeDark2` - 8 colours
- `d3.schemePaired` - 12 colours
- `d3.schemePastel1` - 9 colours
- `d3.schemePastel2` - 8 colours
- `d3.schemeSet1` - 9 colours
- `d3.schemeSet2` - 8 colours
- `d3.schemeSet3` - 12 colours
- `d3.schemeTableau10` - 10 colours
**Use cases:**
- Category colours
- Legend items
- Multi-series charts
- Network node types
## Scale utilities
### Nice domain
Extend domain to nice round values.
```javascript
const scale = d3.scaleLinear()
.domain([0.201, 0.996])
.nice();
scale.domain(); // Returns [0.2, 1.0]
// With count (approximate tick count)
const scale2 = d3.scaleLinear()
.domain([0.201, 0.996])
.nice(5);
```
### Clamping
Restrict output to range bounds.
```javascript
const scale = d3.scaleLinear()
.domain([0, 100])
.range([0, 500])
.clamp(true);
scale(-10); // Returns 0 (clamped)
scale(150); // Returns 500 (clamped)
```
### Copy scales
Create independent copies.
```javascript
const scale1 = d3.scaleLinear()
.domain([0, 100])
.range([0, 500]);
const scale2 = scale1.copy();
// scale2 is independent of scale1
```
### Tick generation
Generate nice tick values for axes.
```javascript
const scale = d3.scaleLinear()
.domain([0, 100])
.range([0, 500]);
scale.ticks(10); // Generate ~10 ticks
scale.tickFormat(10); // Get format function for ticks
scale.tickFormat(10, ".2f"); // Custom format (2 decimal places)
// Time scale ticks
const timeScale = d3.scaleTime()
.domain([new Date(2020, 0, 1), new Date(2024, 0, 1)]);
timeScale.ticks(d3.timeYear); // Yearly ticks
timeScale.ticks(d3.timeMonth, 3); // Every 3 months
timeScale.tickFormat(5, "%Y-%m"); // Format as year-month
```
## Colour spaces and interpolation
### RGB interpolation
```javascript
const scale = d3.scaleLinear()
.domain([0, 100])
.range(["blue", "red"]);
// Default: RGB interpolation
```
### HSL interpolation
```javascript
const scale = d3.scaleLinear()
.domain([0, 100])
.range(["blue", "red"])
.interpolate(d3.interpolateHsl);
// Smoother colour transitions
```
### Lab interpolation
```javascript
const scale = d3.scaleLinear()
.domain([0, 100])
.range(["blue", "red"])
.interpolate(d3.interpolateLab);
// Perceptually uniform
```
### HCL interpolation
```javascript
const scale = d3.scaleLinear()
.domain([0, 100])
.range(["blue", "red"])
.interpolate(d3.interpolateHcl);
// Perceptually uniform with hue
```
## Common patterns
### Diverging scale with custom midpoint
```javascript
const scale = d3.scaleLinear()
.domain([min, midpoint, max])
.range(["red", "white", "blue"])
.interpolate(d3.interpolateHcl);
```
### Multi-stop gradient scale
```javascript
const scale = d3.scaleLinear()
.domain([0, 25, 50, 75, 100])
.range(["#d53e4f", "#fc8d59", "#fee08b", "#e6f598", "#66c2a5"]);
```
### Radius scale for circles (perceptual)
```javascript
const radiusScale = d3.scaleSqrt()
.domain([0, d3.max(data, d => d.value)])
.range([0, 50]);
// Use with circles
circle.attr("r", d => radiusScale(d.value));
```
### Adaptive scale based on data range
```javascript
function createAdaptiveScale(data) {
const extent = d3.extent(data);
const range = extent[1] - extent[0];
// Use log scale if data spans >2 orders of magnitude
if (extent[1] / extent[0] > 100) {
return d3.scaleLog()
.domain(extent)
.range([0, width]);
}
// Otherwise use linear
return d3.scaleLinear()
.domain(extent)
.range([0, width]);
}
```
### Colour scale with explicit categories
```javascript
const colourScale = d3.scaleOrdinal()
.domain(['Low Risk', 'Medium Risk', 'High Risk'])
.range(['#2ecc71', '#f39c12', '#e74c3c'])
.unknown('#95a5a6'); // Fallback for unknown values
```

Submodule skills/loki-mode deleted from be9270dfb5

View File

@@ -0,0 +1,57 @@
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
# Optional: Only run on specific file changes
# paths:
# - "src/**/*.ts"
# - "src/**/*.tsx"
# - "src/**/*.js"
# - "src/**/*.jsx"
jobs:
claude-review:
# Optional: Filter by PR author
# if: |
# github.event.pull_request.user.login == 'external-contributor' ||
# github.event.pull_request.user.login == 'new-developer' ||
# github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude Code Review
id: claude-review
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
prompt: |
REPO: ${{ github.repository }}
PR NUMBER: ${{ github.event.pull_request.number }}
Please review this pull request and provide feedback on:
- Code quality and best practices
- Potential bugs or issues
- Performance considerations
- Security concerns
- Test coverage
Use the repository's CLAUDE.md for guidance on style and conventions. Be constructive and helpful in your feedback.
Use `gh pr comment` with your Bash tool to leave your review as a comment on the PR.
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
# or https://code.claude.com/docs/en/cli-reference for available options
claude_args: '--allowed-tools "Bash(gh issue view:*),Bash(gh search:*),Bash(gh issue list:*),Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*),Bash(gh pr list:*)"'

View File

@@ -0,0 +1,50 @@
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
jobs:
claude:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
# This is an optional setting that allows Claude to read CI results on PRs
additional_permissions: |
actions: read
# Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
# prompt: 'Update the pull request description to include a summary of changes.'
# Optional: Add claude_args to customize behavior and configuration
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
# or https://code.claude.com/docs/en/cli-reference for available options
# claude_args: '--allowed-tools Bash(gh pr:*)'

View File

@@ -0,0 +1,128 @@
name: Release
on:
push:
paths:
- 'VERSION'
branches:
- main
jobs:
release:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Read version
id: version
run: |
VERSION=$(cat VERSION | tr -d '\n')
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "tag=v$VERSION" >> $GITHUB_OUTPUT
- name: Check if tag exists
id: check_tag
run: |
if git rev-parse "v${{ steps.version.outputs.version }}" >/dev/null 2>&1; then
echo "exists=true" >> $GITHUB_OUTPUT
else
echo "exists=false" >> $GITHUB_OUTPUT
fi
- name: Create release artifacts
if: steps.check_tag.outputs.exists == 'false'
run: |
mkdir -p release
# ============================================
# Artifact 1: loki-mode.zip (for Claude.ai website)
# SKILL.md at ROOT level for direct upload
# ============================================
mkdir -p release/skill-root
cp SKILL.md release/skill-root/
cp -r references release/skill-root/
cd release/skill-root
zip -r ../loki-mode-${{ steps.version.outputs.version }}.zip .
cd ../..
# Also create .skill file (same as zip, different extension)
cp release/loki-mode-${{ steps.version.outputs.version }}.zip release/loki-mode-${{ steps.version.outputs.version }}.skill
# ============================================
# Artifact 2: loki-mode-api.zip (for console.anthropic.com)
# SKILL.md inside loki-mode/ folder (API requires folder wrapper)
# ============================================
mkdir -p release/api-package/loki-mode
cp SKILL.md release/api-package/loki-mode/
cp -r references release/api-package/loki-mode/
cd release/api-package
zip -r ../loki-mode-api-${{ steps.version.outputs.version }}.zip loki-mode
cd ../..
# ============================================
# Artifact 3: loki-mode-claude-code.zip
# For Claude Code: full package with loki-mode/ folder
# Extract to ~/.claude/skills/
# ============================================
mkdir -p release/loki-mode
cp SKILL.md release/loki-mode/
cp README.md release/loki-mode/
cp LICENSE release/loki-mode/ 2>/dev/null || true
cp VERSION release/loki-mode/
cp CHANGELOG.md release/loki-mode/
cp -r references release/loki-mode/
cp -r examples release/loki-mode/
cp -r tests release/loki-mode/
cp -r scripts release/loki-mode/
cp -r autonomy release/loki-mode/
cd release
zip -r loki-mode-claude-code-${{ steps.version.outputs.version }}.zip loki-mode
tar -czvf loki-mode-claude-code-${{ steps.version.outputs.version }}.tar.gz loki-mode
cd ..
- name: Create Git Tag
if: steps.check_tag.outputs.exists == 'false'
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -a "v${{ steps.version.outputs.version }}" -m "Release v${{ steps.version.outputs.version }}"
git push origin "v${{ steps.version.outputs.version }}"
- name: Extract changelog for this version
if: steps.check_tag.outputs.exists == 'false'
id: changelog
run: |
VERSION="${{ steps.version.outputs.version }}"
CHANGELOG=$(awk "/^## \[$VERSION\]/{flag=1; next} /^## \[/{flag=0} flag" CHANGELOG.md)
if [ -z "$CHANGELOG" ]; then
CHANGELOG="Release v$VERSION"
fi
echo "$CHANGELOG" > changelog_body.txt
- name: Create GitHub Release
if: steps.check_tag.outputs.exists == 'false'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create "v${{ steps.version.outputs.version }}" \
release/loki-mode-${{ steps.version.outputs.version }}.zip \
release/loki-mode-${{ steps.version.outputs.version }}.skill \
release/loki-mode-api-${{ steps.version.outputs.version }}.zip \
release/loki-mode-claude-code-${{ steps.version.outputs.version }}.zip \
release/loki-mode-claude-code-${{ steps.version.outputs.version }}.tar.gz \
--title "Loki Mode v${{ steps.version.outputs.version }}" \
--notes-file changelog_body.txt
- name: Skip message
if: steps.check_tag.outputs.exists == 'true'
run: |
echo "Tag v${{ steps.version.outputs.version }} already exists. Skipping release."

1
skills/loki-mode/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.DS_Store

View File

@@ -0,0 +1,184 @@
# Acknowledgements
Loki Mode stands on the shoulders of giants. This project incorporates research, patterns, and insights from the leading AI labs, academic institutions, and practitioners in the field.
---
## Research Labs
### Anthropic
Loki Mode is built for Claude and incorporates Anthropic's cutting-edge research on AI safety and agent development.
| Paper/Resource | Contribution to Loki Mode |
|----------------|---------------------------|
| [Constitutional AI: Harmlessness from AI Feedback](https://www.anthropic.com/research/constitutional-ai-harmlessness-from-ai-feedback) | Self-critique against principles, revision workflow |
| [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents) | Evaluator-optimizer pattern, parallelization, routing |
| [Claude Code Best Practices](https://www.anthropic.com/engineering/claude-code-best-practices) | Explore-Plan-Code workflow, context management |
| [Simple Probes Can Catch Sleeper Agents](https://www.anthropic.com/research/probes-catch-sleeper-agents) | Defection probes, anomaly detection patterns |
| [Alignment Faking in Large Language Models](https://www.anthropic.com/research/alignment-faking) | Monitoring for strategic compliance |
| [Visible Extended Thinking](https://www.anthropic.com/research/visible-extended-thinking) | Thinking levels (think, think hard, ultrathink) |
| [Computer Use Safety](https://www.anthropic.com/news/3-5-models-and-computer-use) | Safe autonomous operation patterns |
| [Sabotage Evaluations](https://www.anthropic.com/research/sabotage-evaluations-for-frontier-models) | Safety evaluation methodology |
| [Effective Harnesses for Long-Running Agents](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents) | One-feature-at-a-time pattern, Playwright MCP for E2E |
| [Claude Agent SDK Overview](https://platform.claude.com/docs/en/agent-sdk/overview) | Task tool, subagents, resume parameter, hooks |
### Google DeepMind
DeepMind's research on world models, hierarchical reasoning, and scalable oversight informs Loki Mode's architecture.
| Paper/Resource | Contribution to Loki Mode |
|----------------|---------------------------|
| [SIMA 2: Generalist AI Agent](https://deepmind.google/blog/sima-2-an-agent-that-plays-reasons-and-learns-with-you-in-virtual-3d-worlds/) | Self-improvement loop, reward model training |
| [Gemini Robotics 1.5](https://deepmind.google/blog/gemini-robotics-15-brings-ai-agents-into-the-physical-world/) | Hierarchical reasoning (planner + executor) |
| [Dreamer 4: World Model Training](https://danijar.com/project/dreamer4/) | Simulation-first testing, safe exploration |
| [Genie 3: World Models](https://deepmind.google/blog/genie-3-a-new-frontier-for-world-models/) | World model architecture patterns |
| [Scalable AI Safety via Doubly-Efficient Debate](https://deepmind.google/research/publications/34920/) | Debate-based verification for critical changes |
| [Human-AI Complementarity for Amplified Oversight](https://deepmindsafetyresearch.medium.com/human-ai-complementarity-a-goal-for-amplified-oversight-0ad8a44cae0a) | AI-assisted human supervision |
| [Technical AGI Safety Approach](https://arxiv.org/html/2504.01849v1) | Safety-first agent design |
### OpenAI
OpenAI's Agents SDK and deep research patterns provide foundational patterns for agent orchestration.
| Paper/Resource | Contribution to Loki Mode |
|----------------|---------------------------|
| [Agents SDK Documentation](https://openai.github.io/openai-agents-python/) | Tracing spans, guardrails, tripwires |
| [A Practical Guide to Building Agents](https://cdn.openai.com/business-guides-and-resources/a-practical-guide-to-building-agents.pdf) | Agent architecture best practices |
| [Building Agents Track](https://developers.openai.com/tracks/building-agents/) | Development patterns, handoff callbacks |
| [AGENTS.md Specification](https://agents.md/) | Standardized agent instructions |
| [Introducing Deep Research](https://openai.com/index/introducing-deep-research/) | Adaptive planning, backtracking |
| [Deep Research System Card](https://cdn.openai.com/deep-research-system-card.pdf) | Safety considerations for research agents |
| [Introducing o3 and o4-mini](https://openai.com/index/introducing-o3-and-o4-mini/) | Reasoning model guidance |
| [Reasoning Best Practices](https://platform.openai.com/docs/guides/reasoning-best-practices) | Extended thinking patterns |
| [Chain of Thought Monitoring](https://openai.com/index/chain-of-thought-monitoring/) | Reasoning trace monitoring |
| [Agent Builder Safety](https://platform.openai.com/docs/guides/agent-builder-safety) | Safety patterns for agent builders |
| [Computer-Using Agent](https://openai.com/index/computer-using-agent/) | Computer use patterns |
| [Agentic AI Foundation](https://openai.com/index/agentic-ai-foundation/) | Industry standards, interoperability |
### Amazon Web Services (AWS)
AWS Bedrock's multi-agent collaboration patterns inform Loki Mode's routing and dispatch strategies.
| Paper/Resource | Contribution to Loki Mode |
|----------------|---------------------------|
| [Multi-Agent Orchestration Guidance](https://aws.amazon.com/solutions/guidance/multi-agent-orchestration-on-aws/) | Three coordination mechanisms, architectural patterns |
| [Bedrock Multi-Agent Collaboration](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-multi-agent-collaboration.html) | Supervisor mode, routing mode, 10-agent limit |
| [Multi-Agent Collaboration Announcement](https://aws.amazon.com/blogs/aws/introducing-multi-agent-collaboration-capability-for-amazon-bedrock/) | Intent classification, selective context sharing |
| [AgentCore for SRE](https://aws.amazon.com/blogs/machine-learning/build-multi-agent-site-reliability-engineering-assistants-with-amazon-bedrock-agentcore/) | Gateway, Memory, Identity, Observability components |
**Key Pattern Adopted:** Routing Mode Optimization - Direct dispatch for simple tasks (lower latency), supervisor orchestration for complex tasks (full coordination).
---
## Academic Research
### Multi-Agent Systems
| Paper | Authors/Source | Contribution |
|-------|----------------|--------------|
| [Multi-Agent Collaboration Mechanisms Survey](https://arxiv.org/abs/2501.06322) | arXiv 2501.06322 | Collaboration structures, coopetition |
| [CONSENSAGENT: Anti-Sycophancy Framework](https://aclanthology.org/2025.findings-acl.1141/) | ACL 2025 Findings | Blind review, devil's advocate |
| [GoalAct: Hierarchical Execution](https://arxiv.org/abs/2504.16563) | arXiv 2504.16563 | Global planning, skill decomposition |
| [A-Mem: Agentic Memory System](https://arxiv.org/html/2502.12110v11) | arXiv 2502.12110 | Zettelkasten-style memory linking |
| [Multi-Agent Reflexion (MAR)](https://arxiv.org/html/2512.20845) | arXiv 2512.20845 | Structured debate, persona-based critics |
| [Iter-VF: Iterative Verification-First](https://arxiv.org/html/2511.21734v1) | arXiv 2511.21734 | Answer-only verification, Markovian retry |
### Evaluation & Safety
| Paper | Authors/Source | Contribution |
|-------|----------------|--------------|
| [Assessment Framework for Agentic AI](https://arxiv.org/html/2512.12791v1) | arXiv 2512.12791 | Four-pillar evaluation framework |
| [Measurement Imbalance in Agentic AI](https://arxiv.org/abs/2506.02064) | arXiv 2506.02064 | Multi-dimensional evaluation axes |
| [Demo-to-Deployment Gap](https://www.marktechpost.com/2025/12/24/) | Stanford/Harvard | Tool reliability vs tool selection |
---
## Industry Resources
### Tools & Frameworks
| Resource | Contribution |
|----------|--------------|
| [NVIDIA ToolOrchestra](https://github.com/NVlabs/ToolOrchestra) | Efficiency metrics, three-reward signal framework, dynamic agent selection |
| [LerianStudio/ring](https://github.com/LerianStudio/ring) | Subagent-driven-development pattern |
| [Awesome Agentic Patterns](https://github.com/nibzard/awesome-agentic-patterns) | 105+ production patterns catalog |
### Best Practices Guides
| Resource | Contribution |
|----------|--------------|
| [Maxim AI: Production Multi-Agent Systems](https://www.getmaxim.ai/articles/best-practices-for-building-production-ready-multi-agent-systems/) | Correlation IDs, failure handling |
| [UiPath: Agent Builder Best Practices](https://www.uipath.com/blog/ai/agent-builder-best-practices) | Single-responsibility agents |
| [GitHub: Speed Without Control](https://github.blog/) | Static analysis + AI review, guardrails |
---
## Hacker News Community
Battle-tested insights from practitioners deploying agents in production.
### Discussions
| Thread | Key Insight |
|--------|-------------|
| [What Actually Works in Production for Autonomous Agents](https://news.ycombinator.com/item?id=44623207) | "Zero companies without human in the loop" |
| [Coding with LLMs in Summer 2025](https://news.ycombinator.com/item?id=44623953) | Context curation beats automatic RAG |
| [Superpowers: How I'm Using Coding Agents](https://news.ycombinator.com/item?id=45547344) | Sub-agents for context isolation (Simon Willison) |
| [Claude Code Experience After Two Weeks](https://news.ycombinator.com/item?id=44596472) | Fresh contexts yield better results |
| [AI Agent Benchmarks Are Broken](https://news.ycombinator.com/item?id=44531697) | LLM-as-judge has shared blind spots |
| [How to Orchestrate Multi-Agent Workflows](https://news.ycombinator.com/item?id=45955997) | Event-driven, decoupled coordination |
| [Context Engineering vs Prompt Engineering](https://news.ycombinator.com/item?id=44427757) | Manual context selection principles |
### Show HN Projects
| Project | Contribution |
|---------|--------------|
| [Self-Evolving Agents Repository](https://news.ycombinator.com/item?id=45099226) | Self-improvement patterns |
| [Package Manager for Agent Skills](https://news.ycombinator.com/item?id=46422264) | Skills architecture |
| [Wispbit - AI Code Review Agent](https://news.ycombinator.com/item?id=44722603) | Code review patterns |
| [Agtrace - Monitoring for AI Coding Agents](https://news.ycombinator.com/item?id=46425670) | Agent monitoring patterns |
---
## Individual Contributors
Special thanks to thought leaders whose patterns and insights shaped Loki Mode:
| Contributor | Contribution |
|-------------|--------------|
| **Boris Cherny** (Creator of Claude Code) | Self-verification loop (2-3x quality improvement), extended thinking mode, "Less prompting, more systems" philosophy |
| **Ivan Steshov** | Centralized constitution, agent lineage tracking, structured artifacts as contracts |
| **Addy Osmani** | Git checkpoint system, specification-first approach, visual aids (Mermaid diagrams) |
| **Simon Willison** | Sub-agents for context isolation, skills system, context curation patterns |
---
## Production Patterns Summary
Key patterns incorporated from practitioner experience:
| Pattern | Source | Implementation |
|---------|--------|----------------|
| Human-in-the-Loop (HITL) | HN Production Discussions | Confidence-based escalation thresholds |
| Narrow Scope (3-5 steps) | Multiple Practitioners | Task scope constraints |
| Deterministic Validation | Production Teams | Rule-based outer loops (not LLM-judged) |
| Context Curation | Simon Willison | Manual selection, focused context |
| Blind Review + Devil's Advocate | CONSENSAGENT | Anti-sycophancy protocol |
| Hierarchical Reasoning | DeepMind Gemini | Orchestrator + specialized executors |
| Constitutional Self-Critique | Anthropic | Principles-based revision |
| Debate Verification | DeepMind | Critical change verification |
| One Feature at a Time | Anthropic Harness | Single feature per iteration, full verification |
| E2E Browser Testing | Anthropic Harness | Playwright MCP for visual verification |
---
## License
This acknowledgements file documents the research and resources that influenced Loki Mode's design. All referenced works retain their original licenses and copyrights.
Loki Mode itself is released under the MIT License.
---
*Last updated: v2.35.0*

File diff suppressed because it is too large Load Diff

120
skills/loki-mode/CLAUDE.md Normal file
View File

@@ -0,0 +1,120 @@
# Loki Mode - Claude Code Skill
Multi-agent autonomous startup system for Claude Code. Takes PRD to fully deployed, revenue-generating product with zero human intervention.
## Quick Start
```bash
# Launch Claude Code with autonomous permissions
claude --dangerously-skip-permissions
# Then invoke:
# "Loki Mode" or "Loki Mode with PRD at path/to/prd"
```
## Project Structure
```
SKILL.md # Main skill definition (read this first)
references/ # Detailed documentation (loaded progressively)
openai-patterns.md # OpenAI Agents SDK: guardrails, tripwires, handoffs
lab-research-patterns.md # DeepMind + Anthropic: Constitutional AI, debate
production-patterns.md # HN 2025: What actually works in production
advanced-patterns.md # 2025 research patterns (MAR, Iter-VF, GoalAct)
tool-orchestration.md # ToolOrchestra-inspired efficiency & rewards
memory-system.md # Episodic/semantic memory architecture
quality-control.md # Code review, anti-sycophancy, guardrails
agent-types.md # 37 specialized agent definitions
sdlc-phases.md # Full SDLC workflow
task-queue.md # Queue system, circuit breakers
spec-driven-dev.md # OpenAPI-first development
architecture.md # Directory structure, state schemas
core-workflow.md # RARV cycle, autonomy rules
claude-best-practices.md # Boris Cherny patterns
deployment.md # Cloud deployment instructions
business-ops.md # Business operation workflows
mcp-integration.md # MCP server capabilities
autonomy/ # Runtime state and constitution
benchmarks/ # SWE-bench and HumanEval benchmarks
```
## Key Concepts
### RARV Cycle
Every iteration follows: **R**eason -> **A**ct -> **R**eflect -> **V**erify
### Model Selection
- **Opus**: Planning and architecture ONLY (system design, high-level decisions)
- **Sonnet**: Development and functional testing (implementation, integration tests)
- **Haiku**: Unit tests, monitoring, and simple tasks - use extensively for parallelization
### Quality Gates
1. Static analysis (CodeQL, ESLint)
2. 3-reviewer parallel system (blind review)
3. Anti-sycophancy checks (devil's advocate on unanimous approval)
4. Severity-based blocking (Critical/High/Medium = BLOCK)
5. Test coverage gates (>80% unit, 100% pass)
### Memory System
- **Episodic**: Specific interaction traces (`.loki/memory/episodic/`)
- **Semantic**: Generalized patterns (`.loki/memory/semantic/`)
- **Procedural**: Learned skills (`.loki/memory/skills/`)
### Metrics System (ToolOrchestra-inspired)
- **Efficiency**: Task cost tracking (`.loki/metrics/efficiency/`)
- **Rewards**: Outcome/efficiency/preference signals (`.loki/metrics/rewards/`)
## Development Guidelines
### When Modifying SKILL.md
- Keep under 500 lines (currently ~370)
- Reference detailed docs in `references/` instead of inlining
- Update version in header AND footer
- Update CHANGELOG.md with new version entry
### Version Numbering
Follows semantic versioning: MAJOR.MINOR.PATCH
- Current: v2.35.0
- MINOR bump for new features
- PATCH bump for fixes
### Code Style
- No emojis in code or documentation
- Clear, concise comments only when necessary
- Follow existing patterns in codebase
## Testing
```bash
# Run benchmarks
./benchmarks/run-benchmarks.sh humaneval --execute --loki
./benchmarks/run-benchmarks.sh swebench --execute --loki
```
## Research Foundation
Built on 2025 research from three major AI labs:
**OpenAI:**
- Agents SDK (guardrails, tripwires, handoffs, tracing)
- AGENTS.md / Agentic AI Foundation (AAIF) standards
**Google DeepMind:**
- SIMA 2 (self-improvement, hierarchical reasoning)
- Gemini Robotics (VLA models, planning)
- Dreamer 4 (world model training)
- Scalable Oversight via Debate
**Anthropic:**
- Constitutional AI (principles-based self-critique)
- Alignment Faking Detection (sleeper agent probes)
- Claude Code Best Practices (Explore-Plan-Code)
**Academic:**
- CONSENSAGENT (anti-sycophancy)
- GoalAct (hierarchical planning)
- A-Mem/MIRIX (memory systems)
- Multi-Agent Reflexion (MAR)
- NVIDIA ToolOrchestra (efficiency metrics)
See `references/openai-patterns.md`, `references/lab-research-patterns.md`, and `references/advanced-patterns.md`.

View File

@@ -0,0 +1,206 @@
# Loki Mode - Conversation Context Export
**Date:** 2025-12-28
**Version:** 2.5.0
**Repository:** https://github.com/asklokesh/loki-mode
---
## Project Overview
**Loki Mode** is a Claude Code skill that provides a multi-agent autonomous startup system. It dynamically orchestrates specialized agents across 6 swarms to take a PRD from idea to fully deployed product. It spawns only the agents needed - from a few for simple projects to 100+ for complex startups.
### Key Features
- 37 specialized agent types across 6 swarms (Engineering, Operations, Business, Data, Product, Growth)
- Dynamic agent scaling based on project complexity
- Task tool for subagent dispatch with fresh context
- Distributed task queue (pending, in-progress, completed, failed, dead-letter)
- Circuit breakers for per-agent failure handling
- Timeout/stuck agent detection with heartbeat monitoring
- State recovery via checkpoints in `.loki/state/`
- Autonomous execution with auto-resume on rate limits
---
## File Structure
```
loki-mode/
├── SKILL.md # The main skill file (YAML frontmatter required)
├── VERSION # Current version: 2.4.0
├── CHANGELOG.md # Full version history
├── README.md # Main documentation
├── references/
│ ├── agents.md # 37 agent type definitions
│ ├── deployment.md # Cloud deployment guides
│ └── business-ops.md # Business operation workflows
├── examples/
│ ├── simple-todo-app.md # Simple PRD for testing
│ ├── api-only.md # Backend-only PRD
│ ├── static-landing-page.md # Frontend/marketing PRD
│ └── full-stack-demo.md # Complete bookmark manager PRD
├── tests/
│ ├── run-all-tests.sh # Main test runner (53 tests)
│ ├── test-bootstrap.sh # 8 tests
│ ├── test-task-queue.sh # 8 tests
│ ├── test-circuit-breaker.sh # 8 tests
│ ├── test-agent-timeout.sh # 9 tests
│ ├── test-state-recovery.sh # 8 tests
│ └── test-wrapper.sh # 12 tests
├── scripts/
│ ├── loki-wrapper.sh # Legacy wrapper (deprecated)
│ └── export-to-vibe-kanban.sh # Optional Vibe Kanban export
├── integrations/
│ └── vibe-kanban.md # Vibe Kanban integration guide
├── autonomy/
│ ├── run.sh # ⭐ MAIN ENTRY POINT - handles everything
│ └── README.md # Autonomy documentation
└── .github/workflows/
└── release.yml # GitHub Actions for releases
```
---
## How to Use
### Quick Start (Recommended)
```bash
./autonomy/run.sh ./docs/requirements.md
```
### What run.sh Does
1. Checks prerequisites (Claude CLI, Python, Git, curl)
2. Verifies skill installation
3. Initializes `.loki/` directory
4. Starts status monitor (updates `.loki/STATUS.txt` every 5s)
5. Runs Claude Code with live output
6. Auto-resumes on rate limits with exponential backoff
7. Continues until completion or max retries
### Monitor Progress
```bash
# In another terminal
watch -n 2 cat .loki/STATUS.txt
```
---
## Key Technical Details
### Claude Code Invocation
The autonomy runner pipes the prompt through stdin for live output:
```bash
echo "$prompt" | claude --dangerously-skip-permissions
```
**Important:** Using `-p` flag doesn't stream output properly. Piping through stdin shows interactive output.
### State Files
- `.loki/state/orchestrator.json` - Current phase, metrics
- `.loki/autonomy-state.json` - Retry count, status, PID
- `.loki/queue/*.json` - Task queues
- `.loki/STATUS.txt` - Human-readable status (updated every 5s)
- `.loki/logs/*.log` - Execution logs
### Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `LOKI_MAX_RETRIES` | 50 | Max retry attempts |
| `LOKI_BASE_WAIT` | 60 | Base wait time (seconds) |
| `LOKI_MAX_WAIT` | 3600 | Max wait time (1 hour) |
| `LOKI_SKIP_PREREQS` | false | Skip prerequisite checks |
---
## Version History Summary
| Version | Key Changes |
|---------|-------------|
| 2.5.0 | Real streaming output (stream-json), Web dashboard with Anthropic design |
| 2.4.0 | Live output fix (stdin pipe), STATUS.txt monitor |
| 2.3.0 | Unified autonomy runner (`autonomy/run.sh`) |
| 2.2.0 | Vibe Kanban integration |
| 2.1.0 | Autonomous wrapper with auto-resume |
| 2.0.x | Test suite, macOS compatibility, release workflow |
| 1.x.x | Initial skill with agents, deployment guides |
---
## Known Issues & Solutions
### 1. "Blank output when running autonomously"
**Cause:** Using `-p` flag doesn't stream output
**Solution:** Use stdin pipe: `echo "$prompt" | claude --dangerously-skip-permissions`
### 2. "Vibe Kanban not showing tasks"
**Cause:** Vibe Kanban is UI-driven, doesn't read JSON files automatically
**Solution:** Use `.loki/STATUS.txt` for monitoring, or run Vibe Kanban separately
### 3. "timeout command not found on macOS"
**Cause:** macOS doesn't have GNU coreutils
**Solution:** Perl-based fallback in test scripts
### 4. "TTY raw mode error"
**Cause:** Running Claude in non-interactive mode
**Solution:** Latest commit (008ed86) adds `--no-input` flag
---
## Git Configuration
**Committer:** asklokesh (never use Claude as co-author)
**Commit format:**
```
Short description (vX.X.X)
Detailed bullet points of changes
```
---
## Test Suite
Run all tests:
```bash
./tests/run-all-tests.sh
```
53 tests across 6 test suites - all should pass.
---
## Pending/Future Work
1. **Vibe Kanban proper integration** - Vibe Kanban doesn't read files, would need API integration
2. **Better live output** - Current stdin pipe works but may have edge cases
3. **Task visualization** - Could add a simple TUI for task monitoring
---
## Important Files to Read First
When starting a new session, read these files:
1. `SKILL.md` - The actual skill instructions
2. `autonomy/run.sh` - Main entry point
3. `VERSION` and `CHANGELOG.md` - Current state
4. This file (`CONTEXT-EXPORT.md`) - Full context
---
## User Preferences
- Always use `asklokesh` as committer
- Never use Claude as co-author
- Keep skill files clean, autonomy separate
- Test before pushing
- Live output is important - user wants to see what's happening
---
## Last Known State
- **Version:** 2.5.0
- **Latest Commit:** (pending push)
- **Tests:** All 53 passing
- **Features Added:** Real-time streaming output via stream-json, web dashboard with Anthropic design

View File

@@ -0,0 +1,384 @@
# Loki Mode Installation Guide
Complete installation instructions for all platforms and use cases.
---
## Table of Contents
- [Quick Install (Recommended)](#quick-install-recommended)
- [Claude Code (CLI)](#claude-code-cli)
- [Claude.ai (Web)](#claudeai-web)
- [Anthropic API Console](#anthropic-api-console)
- [Verify Installation](#verify-installation)
- [Troubleshooting](#troubleshooting)
---
## Quick Install (Recommended)
**For Claude Code users:**
```bash
# Clone to your skills directory
git clone https://github.com/asklokesh/loki-mode.git ~/.claude/skills/loki-mode
```
**Done!** Skip to [Verify Installation](#verify-installation).
---
## Claude Code (CLI)
Loki Mode can be installed for Claude Code in three ways:
### Option A: Git Clone (Recommended)
**Personal installation (available in all projects):**
```bash
git clone https://github.com/asklokesh/loki-mode.git ~/.claude/skills/loki-mode
```
**Project-specific installation:**
```bash
# Navigate to your project directory first
cd /path/to/your/project
# Clone to local skills directory
git clone https://github.com/asklokesh/loki-mode.git .claude/skills/loki-mode
```
### Option B: Download from Releases
```bash
# Navigate to skills directory
cd ~/.claude/skills
# Get latest version number
VERSION=$(curl -s https://api.github.com/repos/asklokesh/loki-mode/releases/latest | grep tag_name | cut -d'"' -f4 | tr -d 'v')
# Download and extract
curl -L -o loki-mode.zip "https://github.com/asklokesh/loki-mode/releases/download/v${VERSION}/loki-mode-claude-code-${VERSION}.zip"
unzip loki-mode.zip && rm loki-mode.zip
```
**Result:** Creates `~/.claude/skills/loki-mode/SKILL.md`
### Option C: Minimal Install (curl)
If you only want the essential files without the full repository:
```bash
# Create directory structure
mkdir -p ~/.claude/skills/loki-mode/references
# Download core skill file
curl -o ~/.claude/skills/loki-mode/SKILL.md \
https://raw.githubusercontent.com/asklokesh/loki-mode/main/SKILL.md
# Download agent definitions
curl -o ~/.claude/skills/loki-mode/references/agents.md \
https://raw.githubusercontent.com/asklokesh/loki-mode/main/references/agents.md
# Download deployment guides
curl -o ~/.claude/skills/loki-mode/references/deployment.md \
https://raw.githubusercontent.com/asklokesh/loki-mode/main/references/deployment.md
# Download business operations reference
curl -o ~/.claude/skills/loki-mode/references/business-ops.md \
https://raw.githubusercontent.com/asklokesh/loki-mode/main/references/business-ops.md
```
**Note:** This minimal install won't include examples, tests, or the autonomous runner. Use Option A or B for full functionality.
---
## Claude.ai (Web)
For using Loki Mode on the Claude.ai web interface:
### Step 1: Download the Skill Package
1. Go to [Releases](https://github.com/asklokesh/loki-mode/releases)
2. Download **either**:
- `loki-mode-X.X.X.zip` (standard format)
- `loki-mode-X.X.X.skill` (skill format)
Both contain the same skill and will work.
### Step 2: Upload to Claude.ai
1. Open [Claude.ai](https://claude.ai)
2. Go to **Settings** (gear icon)
3. Navigate to **Features → Skills**
4. Click **Upload Skill**
5. Select the downloaded `.zip` or `.skill` file
**File Structure:** The Claude.ai package has `SKILL.md` at the root level as required by the web interface.
---
## Anthropic API Console
For using Loki Mode through the Anthropic API Console (console.anthropic.com):
### Step 1: Download the API Package
1. Go to [Releases](https://github.com/asklokesh/loki-mode/releases)
2. Download **`loki-mode-api-X.X.X.zip`** (note the `-api-` version)
**Important:** The API version has a different file structure than the web version.
### Step 2: Upload to API Console
1. Go to [console.anthropic.com](https://console.anthropic.com)
2. Navigate to **Skills** section
3. Click **Upload Skill**
4. Select the downloaded `loki-mode-api-X.X.X.zip` file
**File Structure:** The API package has `SKILL.md` inside a `loki-mode/` folder as required by the API.
---
## Verify Installation
### For Claude Code (CLI)
Check that the skill file is in place:
```bash
cat ~/.claude/skills/loki-mode/SKILL.md | head -10
```
**Expected output:** Should show YAML frontmatter starting with:
```yaml
---
name: loki-mode
description: Multi-Agent Autonomous Startup System
...
---
```
### For Claude.ai (Web)
1. Start a new conversation
2. Type: `Loki Mode`
3. Claude should recognize the skill and ask for a PRD
### For API Console
1. Create a new API call with skills enabled
2. Include the skill in your request
3. The skill should be available for use
---
## File Structure
After installation, you should have this structure:
```
loki-mode/
├── SKILL.md # Main skill file (required)
├── README.md # Documentation
├── INSTALLATION.md # This file
├── CHANGELOG.md # Version history
├── VERSION # Current version number
├── LICENSE # MIT License
├── references/ # Agent and deployment references
│ ├── agents.md
│ ├── deployment.md
│ └── business-ops.md
├── autonomy/ # Autonomous runner (CLI only)
│ ├── run.sh
│ └── README.md
├── examples/ # Sample PRDs for testing
│ ├── simple-todo-app.md
│ ├── api-only.md
│ ├── static-landing-page.md
│ └── full-stack-demo.md
├── tests/ # Test suite (CLI only)
│ ├── run-all-tests.sh
│ ├── test-bootstrap.sh
│ └── ...
└── integrations/ # Third-party integrations
└── vibe-kanban.md
```
**Note:** Some files/directories (autonomy, tests, examples) are only available with full installation (Options A or B).
---
## Troubleshooting
### Skill Not Found
**Problem:** Claude doesn't recognize "Loki Mode" command.
**Solutions:**
1. **Check installation path:**
```bash
ls -la ~/.claude/skills/loki-mode/SKILL.md
```
2. **Verify YAML frontmatter:**
```bash
cat ~/.claude/skills/loki-mode/SKILL.md | head -5
```
Should show `name: loki-mode`
3. **Restart Claude Code:**
```bash
# Exit and restart claude command
```
### Permission Denied
**Problem:** Cannot create directories or download files.
**Solution:**
```bash
# Ensure skills directory exists
mkdir -p ~/.claude/skills
# Check permissions
ls -la ~/.claude/
```
### Download Fails
**Problem:** curl or wget commands fail.
**Solutions:**
1. **Check internet connection**
2. **Try alternate download method:**
```bash
# Use wget instead of curl
wget -O ~/.claude/skills/loki-mode/SKILL.md \
https://raw.githubusercontent.com/asklokesh/loki-mode/main/SKILL.md
```
3. **Manual download:**
- Visit the URL in a browser
- Save file manually to `~/.claude/skills/loki-mode/`
### Autonomous Runner Won't Start
**Problem:** `./autonomy/run.sh` gives "command not found" or permission errors.
**Solutions:**
1. **Make executable:**
```bash
chmod +x autonomy/run.sh
```
2. **Run from repository root:**
```bash
# Make sure you're in the loki-mode directory
cd ~/.claude/skills/loki-mode
./autonomy/run.sh
```
3. **Check prerequisites:**
```bash
# Ensure Claude Code is installed
claude --version
# Ensure Python 3 is available
python3 --version
```
### References Not Loading
**Problem:** Skill loads but agent definitions or deployment guides are missing.
**Solution:**
```bash
# Ensure all reference files are present
ls -la ~/.claude/skills/loki-mode/references/
# Should show:
# agents.md
# deployment.md
# business-ops.md
# If missing, download them:
curl -o ~/.claude/skills/loki-mode/references/agents.md \
https://raw.githubusercontent.com/asklokesh/loki-mode/main/references/agents.md
```
---
## Updating Loki Mode
### For Git Installations
```bash
cd ~/.claude/skills/loki-mode
git pull origin main
```
### For Manual Installations
1. Download the latest release
2. Extract to the same directory (overwrite existing files)
3. Or delete old installation and reinstall
### Check Current Version
```bash
cat ~/.claude/skills/loki-mode/VERSION
```
---
## Uninstalling
### Claude Code (CLI)
```bash
# Remove the skill directory
rm -rf ~/.claude/skills/loki-mode
```
### Claude.ai (Web)
1. Go to **Settings → Features → Skills**
2. Find "loki-mode" in the list
3. Click **Remove**
### API Console
1. Go to **Skills** section
2. Find "loki-mode"
3. Click **Delete**
---
## Next Steps
After installation:
1. **Quick Test:** Run a simple example
```bash
./autonomy/run.sh examples/simple-todo-app.md
```
2. **Read Documentation:** Check out [README.md](README.md) for usage guides
3. **Create Your First PRD:** See the Quick Start section in README
4. **Join the Community:** Report issues or contribute at [GitHub](https://github.com/asklokesh/loki-mode)
---
## Need Help?
- **Issues/Bugs:** [GitHub Issues](https://github.com/asklokesh/loki-mode/issues)
- **Discussions:** [GitHub Discussions](https://github.com/asklokesh/loki-mode/discussions)
- **Documentation:** [README.md](README.md)
---
**Happy Building!**

21
skills/loki-mode/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Loki Mode Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

548
skills/loki-mode/README.md Normal file
View File

@@ -0,0 +1,548 @@
# Loki Mode
**The First Truly Autonomous Multi-Agent Startup System**
[![Claude Code](https://img.shields.io/badge/Claude-Code-orange)](https://claude.ai)
[![Agent Types](https://img.shields.io/badge/Agent%20Types-37-blue)]()
[![Loki Mode](https://img.shields.io/badge/Loki%20Mode-98.78%25%20Pass%401-blueviolet)](benchmarks/results/)
[![HumanEval](https://img.shields.io/badge/HumanEval-98.17%25%20Pass%401-brightgreen)](benchmarks/results/)
[![SWE-bench](https://img.shields.io/badge/SWE--bench-99.67%25%20Patch%20Gen-brightgreen)](benchmarks/results/)
[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
> **PRD → Deployed Product in Zero Human Intervention**
>
> Loki Mode transforms a Product Requirements Document into a fully built, tested, deployed, and revenue-generating product while you sleep. No manual steps. No intervention. Just results.
---
## Demo
[![asciicast](https://asciinema.org/a/EqNo5IVTaPJfCjLmnYgZ9TC3E.svg)](https://asciinema.org/a/EqNo5IVTaPJfCjLmnYgZ9TC3E)
*Click to watch Loki Mode build a complete Todo App from PRD - zero human intervention*
---
## Benchmark Results
### Three-Way Comparison (HumanEval)
| System | Pass@1 | Details |
|--------|--------|---------|
| **Loki Mode (Multi-Agent)** | **98.78%** | 162/164 problems, RARV cycle recovered 2 |
| Direct Claude | 98.17% | 161/164 problems (baseline) |
| MetaGPT | 85.9-87.7% | Published benchmark |
**Loki Mode beats MetaGPT by +11-13%** thanks to the RARV (Reason-Act-Reflect-Verify) cycle.
### Full Results
| Benchmark | Score | Details |
|-----------|-------|---------|
| **Loki Mode HumanEval** | **98.78% Pass@1** | 162/164 (multi-agent with RARV) |
| **Direct Claude HumanEval** | **98.17% Pass@1** | 161/164 (single agent baseline) |
| **Direct Claude SWE-bench** | **99.67% patch gen** | 299/300 problems |
| **Loki Mode SWE-bench** | **99.67% patch gen** | 299/300 problems |
| Model | Claude Opus 4.5 | |
**Key Finding:** Multi-agent RARV matches single-agent performance on both benchmarks after timeout optimization. The 4-agent pipeline (Architect->Engineer->QA->Reviewer) achieves the same 99.67% patch generation as direct Claude.
See [benchmarks/results/](benchmarks/results/) for full methodology and solutions.
---
## What is Loki Mode?
Loki Mode is a Claude Code skill that orchestrates **37 specialized AI agent types** across **6 swarms** to autonomously build, test, deploy, and scale complete startups. It dynamically spawns only the agents you need—**5-10 for simple projects, 100+ for complex startups**—working in parallel with continuous self-verification.
```
PRD → Research → Architecture → Development → Testing → Deployment → Marketing → Revenue
```
**Just say "Loki Mode" and point to a PRD. Walk away. Come back to a deployed product.**
---
## Why Loki Mode?
### **Better Than Anything Out There**
| What Others Do | What Loki Mode Does |
|----------------|---------------------|
| **Single agent** writes code linearly | **100+ agents** work in parallel across engineering, ops, business, data, product, and growth |
| **Manual deployment** required | **Autonomous deployment** to AWS, GCP, Azure, Vercel, Railway with blue-green and canary strategies |
| **No testing** or basic unit tests | **14 automated quality gates**: security scans, load tests, accessibility audits, code reviews |
| **Code only** - you handle the rest | **Full business operations**: marketing, sales, legal, HR, finance, investor relations |
| **Stops on errors** | **Self-healing**: circuit breakers, dead letter queues, exponential backoff, automatic recovery |
| **No visibility** into progress | **Real-time dashboard** with agent monitoring, task queues, and live status updates |
| **"Done" when code is written** | **Never "done"**: continuous optimization, A/B testing, customer feedback loops, perpetual improvement |
### **Core Advantages**
1. **Truly Autonomous**: RARV (Reason-Act-Reflect-Verify) cycle with self-verification achieves 2-3x quality improvement
2. **Massively Parallel**: 100+ agents working simultaneously, not sequential single-agent bottlenecks
3. **Production-Ready**: Not just code—handles deployment, monitoring, incident response, and business operations
4. **Self-Improving**: Learns from mistakes, updates continuity logs, prevents repeated errors
5. **Zero Babysitting**: Auto-resumes on rate limits, recovers from failures, runs until completion
6. **Efficiency Optimized**: ToolOrchestra-inspired metrics track cost per task, reward signals drive continuous improvement
---
## Dashboard & Real-Time Monitoring
Monitor your autonomous startup being built in real-time through the Loki Mode dashboard:
### **Agent Monitoring**
<img width="1200" alt="Loki Mode Dashboard - Active Agents" src="docs/screenshots/dashboard-agents.png" />
**Track all active agents in real-time:**
- **Agent ID** and **Type** (frontend, backend, QA, DevOps, etc.)
- **Model Badge** (Sonnet, Haiku, Opus) with color coding
- **Current Work** being performed
- **Runtime** and **Tasks Completed**
- **Status** (active, completed)
### **Task Queue Visualization**
<img width="1200" alt="Loki Mode Dashboard - Task Queue" src="docs/screenshots/dashboard-tasks.png" />
**Four-column kanban view:**
- **Pending**: Queued tasks waiting for agents
- **In Progress**: Currently being worked on
- **Completed**: Successfully finished (shows last 10)
- **Failed**: Tasks requiring attention
### **Live Status Monitor**
```bash
# Watch status updates in terminal
watch -n 2 cat .loki/STATUS.txt
```
```
╔════════════════════════════════════════════════════════════════╗
║ LOKI MODE STATUS ║
╚════════════════════════════════════════════════════════════════╝
Phase: DEVELOPMENT
Active Agents: 47
├─ Engineering: 18
├─ Operations: 12
├─ QA: 8
└─ Business: 9
Tasks:
├─ Pending: 10
├─ In Progress: 47
├─ Completed: 203
└─ Failed: 0
Last Updated: 2026-01-04 20:45:32
```
**Access the dashboard:**
```bash
# Automatically opens when running autonomously
./autonomy/run.sh ./docs/requirements.md
# Or open manually
open .loki/dashboard/index.html
```
Auto-refreshes every 3 seconds. Works with any modern browser.
---
## Autonomous Capabilities
### **RARV Cycle: Reason-Act-Reflect-Verify**
Loki Mode doesn't just write code—it **thinks, acts, learns, and verifies**:
```
1. REASON
└─ Read .loki/CONTINUITY.md including "Mistakes & Learnings"
└─ Check .loki/state/ and .loki/queue/
└─ Identify next task or improvement
2. ACT
└─ Execute task, write code
└─ Commit changes atomically (git checkpoint)
3. REFLECT
└─ Update .loki/CONTINUITY.md with progress
└─ Update state files
└─ Identify NEXT improvement
4. VERIFY
└─ Run automated tests (unit, integration, E2E)
└─ Check compilation/build
└─ Verify against spec
IF VERIFICATION FAILS:
├─ Capture error details (stack trace, logs)
├─ Analyze root cause
├─ UPDATE "Mistakes & Learnings" in CONTINUITY.md
├─ Rollback to last good git checkpoint if needed
└─ Apply learning and RETRY from REASON
```
**Result:** 2-3x quality improvement through continuous self-verification.
### **Perpetual Improvement Mode**
There is **NEVER** a "finished" state. After completing the PRD, Loki Mode:
- Runs performance optimizations
- Adds missing test coverage
- Improves documentation
- Refactors code smells
- Updates dependencies
- Enhances user experience
- Implements A/B test learnings
**It keeps going until you stop it.**
### **Auto-Resume & Self-Healing**
**Rate limits?** Exponential backoff and automatic resume.
**Errors?** Circuit breakers, dead letter queues, retry logic.
**Interruptions?** State checkpoints every 5 seconds—just restart.
```bash
# Start autonomous mode
./autonomy/run.sh ./docs/requirements.md
# Hit rate limit? Script automatically:
# ├─ Saves state checkpoint
# ├─ Waits with exponential backoff (60s → 120s → 240s...)
# ├─ Resumes from exact point
# └─ Continues until completion or max retries (default: 50)
```
---
## Quick Start
### **1. Install**
```bash
# Clone to your Claude Code skills directory
git clone https://github.com/asklokesh/loki-mode.git ~/.claude/skills/loki-mode
```
See [INSTALLATION.md](INSTALLATION.md) for other installation methods (Web, API Console, minimal curl install).
### **2. Create a PRD**
```markdown
# Product: AI-Powered Todo App
## Overview
Build a todo app with AI-powered task suggestions and deadline predictions.
## Features
- User authentication (email/password)
- Create, read, update, delete todos
- AI suggests next tasks based on patterns
- Smart deadline predictions
- Mobile-responsive design
## Tech Stack
- Next.js 14 with TypeScript
- PostgreSQL database
- OpenAI API for suggestions
- Deploy to Vercel
```
Save as `my-prd.md`.
### **3. Run Loki Mode**
```bash
# Autonomous mode (recommended)
./autonomy/run.sh ./my-prd.md
# Or manual mode
claude --dangerously-skip-permissions
> Loki Mode with PRD at ./my-prd.md
```
### **4. Monitor Progress**
Open the dashboard in your browser (auto-opens) or check status:
```bash
watch -n 2 cat .loki/STATUS.txt
```
### **5. Walk Away**
Seriously. Go get coffee. It'll be deployed when you get back.
**That's it.** No configuration. No manual steps. No intervention.
---
## Agent Swarms (37 Types)
Loki Mode has **37 predefined agent types** organized into **6 specialized swarms**. The orchestrator spawns only what you need—simple projects use 5-10 agents, complex startups spawn 100+.
<img width="5309" height="979" alt="Agent Swarms Visualization" src="https://github.com/user-attachments/assets/7d18635d-a606-401f-8d9f-430e6e4ee689" />
### **Engineering (8 types)**
`eng-frontend` `eng-backend` `eng-database` `eng-mobile` `eng-api` `eng-qa` `eng-perf` `eng-infra`
### **Operations (8 types)**
`ops-devops` `ops-sre` `ops-security` `ops-monitor` `ops-incident` `ops-release` `ops-cost` `ops-compliance`
### **Business (8 types)**
`biz-marketing` `biz-sales` `biz-finance` `biz-legal` `biz-support` `biz-hr` `biz-investor` `biz-partnerships`
### **Data (3 types)**
`data-ml` `data-eng` `data-analytics`
### **Product (3 types)**
`prod-pm` `prod-design` `prod-techwriter`
### **Growth (4 types)**
`growth-hacker` `growth-community` `growth-success` `growth-lifecycle`
### **Review (3 types)**
`review-code` `review-business` `review-security`
See [references/agents.md](references/agents.md) for complete agent type definitions.
---
## How It Works
### **Phase Execution**
| Phase | Description |
|-------|-------------|
| **0. Bootstrap** | Create `.loki/` directory structure, initialize state |
| **1. Discovery** | Parse PRD, competitive research via web search |
| **2. Architecture** | Tech stack selection with self-reflection |
| **3. Infrastructure** | Provision cloud, CI/CD, monitoring |
| **4. Development** | Implement with TDD, parallel code review |
| **5. QA** | 14 quality gates, security audit, load testing |
| **6. Deployment** | Blue-green deploy, auto-rollback on errors |
| **7. Business** | Marketing, sales, legal, support setup |
| **8. Growth** | Continuous optimization, A/B testing, feedback loops |
### **Parallel Code Review**
Every code change goes through **3 specialized reviewers simultaneously**:
```
IMPLEMENT → REVIEW (parallel) → AGGREGATE → FIX → RE-REVIEW → COMPLETE
├─ code-reviewer (Opus) - Code quality, patterns, best practices
├─ business-logic-reviewer (Opus) - Requirements, edge cases, UX
└─ security-reviewer (Opus) - Vulnerabilities, OWASP Top 10
```
**Severity-based issue handling:**
- **Critical/High/Medium**: Block. Fix immediately. Re-review.
- **Low**: Add `// TODO(review): ...` comment, continue.
- **Cosmetic**: Add `// FIXME(nitpick): ...` comment, continue.
### **Directory Structure**
```
.loki/
├── state/ # Orchestrator and agent states
├── queue/ # Task queue (pending, in-progress, completed, dead-letter)
├── memory/ # Episodic, semantic, and procedural memory
├── metrics/ # Efficiency tracking and reward signals
├── messages/ # Inter-agent communication
├── logs/ # Audit logs
├── config/ # Configuration files
├── prompts/ # Agent role prompts
├── artifacts/ # Releases, reports, backups
├── dashboard/ # Real-time monitoring dashboard
└── scripts/ # Helper scripts
```
---
## Example PRDs
Test Loki Mode with these pre-built PRDs in the `examples/` directory:
| PRD | Complexity | Est. Time | Description |
|-----|------------|-----------|-------------|
| `simple-todo-app.md` | Low | ~10 min | Basic todo app - tests core functionality |
| `api-only.md` | Low | ~10 min | REST API only - tests backend agents |
| `static-landing-page.md` | Low | ~5 min | HTML/CSS only - tests frontend/marketing |
| `full-stack-demo.md` | Medium | ~30-60 min | Complete bookmark manager - full test |
```bash
# Example: Run with simple todo app
./autonomy/run.sh examples/simple-todo-app.md
```
---
## Configuration
### **Autonomy Settings**
Customize the autonomous runner with environment variables:
```bash
LOKI_MAX_RETRIES=100 \
LOKI_BASE_WAIT=120 \
LOKI_MAX_WAIT=7200 \
./autonomy/run.sh ./docs/requirements.md
```
| Variable | Default | Description |
|----------|---------|-------------|
| `LOKI_MAX_RETRIES` | 50 | Maximum retry attempts before giving up |
| `LOKI_BASE_WAIT` | 60 | Base wait time in seconds |
| `LOKI_MAX_WAIT` | 3600 | Maximum wait time (1 hour) |
| `LOKI_SKIP_PREREQS` | false | Skip prerequisite checks |
### **Circuit Breakers**
```yaml
# .loki/config/circuit-breakers.yaml
defaults:
failureThreshold: 5
cooldownSeconds: 300
```
### **External Alerting**
```yaml
# .loki/config/alerting.yaml
channels:
slack:
webhook_url: "${SLACK_WEBHOOK_URL}"
severity: [critical, high]
pagerduty:
integration_key: "${PAGERDUTY_KEY}"
severity: [critical]
```
---
## Requirements
- **Claude Code** with `--dangerously-skip-permissions` flag
- **Internet access** for competitive research and deployment
- **Cloud provider credentials** (for deployment phase)
- **Python 3** (for test suite)
**Optional but recommended:**
- Git (for version control and checkpoints)
- Node.js/npm (for dashboard and web projects)
- Docker (for containerized deployments)
---
## Integrations
### **Vibe Kanban (Visual Dashboard)**
Integrate with [Vibe Kanban](https://github.com/BloopAI/vibe-kanban) for a visual kanban board:
```bash
# Install Vibe Kanban
npx vibe-kanban
# Export Loki tasks to Vibe Kanban
./scripts/export-to-vibe-kanban.sh
```
**Benefits:**
- Visual progress tracking of all active agents
- Manual intervention/prioritization when needed
- Code review with visual diffs
- Multi-project dashboard
See [integrations/vibe-kanban.md](integrations/vibe-kanban.md) for full setup guide.
---
## Testing
Run the comprehensive test suite:
```bash
# Run all tests
./tests/run-all-tests.sh
# Or run individual test suites
./tests/test-bootstrap.sh # Directory structure, state init
./tests/test-task-queue.sh # Queue operations, priorities
./tests/test-circuit-breaker.sh # Failure handling, recovery
./tests/test-agent-timeout.sh # Timeout, stuck process handling
./tests/test-state-recovery.sh # Checkpoints, recovery
```
---
## Contributing
Contributions welcome! Please:
1. Read [SKILL.md](SKILL.md) to understand the architecture
2. Check [references/agents.md](references/agents.md) for agent definitions
3. Open an issue for bugs or feature requests
4. Submit PRs with clear descriptions and tests
---
## License
MIT License - see [LICENSE](LICENSE) for details.
---
## Acknowledgments
Loki Mode incorporates research and patterns from leading AI labs and practitioners:
### Research Foundation
| Source | Key Contribution |
|--------|------------------|
| [Anthropic: Building Effective Agents](https://www.anthropic.com/research/building-effective-agents) | Evaluator-optimizer pattern, parallelization |
| [Anthropic: Constitutional AI](https://www.anthropic.com/research/constitutional-ai-harmlessness-from-ai-feedback) | Self-critique against principles |
| [DeepMind: Scalable Oversight via Debate](https://deepmind.google/research/publications/34920/) | Debate-based verification |
| [DeepMind: SIMA 2](https://deepmind.google/blog/sima-2-an-agent-that-plays-reasons-and-learns-with-you-in-virtual-3d-worlds/) | Self-improvement loop |
| [OpenAI: Agents SDK](https://openai.github.io/openai-agents-python/) | Guardrails, tripwires, tracing |
| [NVIDIA ToolOrchestra](https://github.com/NVlabs/ToolOrchestra) | Efficiency metrics, reward signals |
| [CONSENSAGENT (ACL 2025)](https://aclanthology.org/2025.findings-acl.1141/) | Anti-sycophancy, blind review |
| [GoalAct](https://arxiv.org/abs/2504.16563) | Hierarchical planning |
### Practitioner Insights
- **Boris Cherny** (Claude Code creator) - Self-verification loop, extended thinking
- **Simon Willison** - Sub-agents for context isolation, skills system
- **Hacker News Community** - [Production patterns](https://news.ycombinator.com/item?id=44623207) from real deployments
### Inspirations
- [LerianStudio/ring](https://github.com/LerianStudio/ring) - Subagent-driven-development pattern
- [Awesome Agentic Patterns](https://github.com/nibzard/awesome-agentic-patterns) - 105+ production patterns
**[Full Acknowledgements](ACKNOWLEDGEMENTS.md)** - Complete list of 50+ research papers, articles, and resources
Built for the [Claude Code](https://claude.ai) ecosystem, powered by Anthropic's Claude models (Sonnet, Haiku, Opus).
---
**Ready to build a startup while you sleep?**
```bash
git clone https://github.com/asklokesh/loki-mode.git ~/.claude/skills/loki-mode
./autonomy/run.sh your-prd.md
```
---
**Keywords:** claude-code, claude-skills, ai-agents, autonomous-development, multi-agent-system, sdlc-automation, startup-automation, devops, mlops, deployment-automation, self-healing, perpetual-improvement

721
skills/loki-mode/SKILL.md Normal file
View File

@@ -0,0 +1,721 @@
---
name: loki-mode
description: Multi-agent autonomous startup system for Claude Code. Triggers on "Loki Mode". Orchestrates 100+ specialized agents across engineering, QA, DevOps, security, data/ML, business operations, marketing, HR, and customer success. Takes PRD to fully deployed, revenue-generating product with zero human intervention. Features Task tool for subagent dispatch, parallel code review with 3 specialized reviewers, severity-based issue triage, distributed task queue with dead letter handling, automatic deployment to cloud providers, A/B testing, customer feedback loops, incident response, circuit breakers, and self-healing. Handles rate limits via distributed state checkpoints and auto-resume with exponential backoff. Requires --dangerously-skip-permissions flag.
---
# Loki Mode - Multi-Agent Autonomous Startup System
> **Version 2.35.0** | PRD to Production | Zero Human Intervention
> Research-enhanced: OpenAI SDK, DeepMind, Anthropic, AWS Bedrock, Agent SDK, HN Production (2025)
---
## Quick Reference
### Critical First Steps (Every Turn)
1. **READ** `.loki/CONTINUITY.md` - Your working memory + "Mistakes & Learnings"
2. **RETRIEVE** Relevant memories from `.loki/memory/` (episodic patterns, anti-patterns)
3. **CHECK** `.loki/state/orchestrator.json` - Current phase/metrics
4. **REVIEW** `.loki/queue/pending.json` - Next tasks
5. **FOLLOW** RARV cycle: REASON, ACT, REFLECT, **VERIFY** (test your work!)
6. **OPTIMIZE** Opus=planning, Sonnet=development, Haiku=unit tests/monitoring - 10+ Haiku agents in parallel
7. **TRACK** Efficiency metrics: tokens, time, agent count per task
8. **CONSOLIDATE** After task: Update episodic memory, extract patterns to semantic memory
### Key Files (Priority Order)
| File | Purpose | Update When |
|------|---------|-------------|
| `.loki/CONTINUITY.md` | Working memory - what am I doing NOW? | Every turn |
| `.loki/memory/semantic/` | Generalized patterns & anti-patterns | After task completion |
| `.loki/memory/episodic/` | Specific interaction traces | After each action |
| `.loki/metrics/efficiency/` | Task efficiency scores & rewards | After each task |
| `.loki/specs/openapi.yaml` | API spec - source of truth | Architecture changes |
| `CLAUDE.md` | Project context - arch & patterns | Significant changes |
| `.loki/queue/*.json` | Task states | Every task change |
### Decision Tree: What To Do Next?
```
START
|
+-- Read CONTINUITY.md ----------+
| |
+-- Task in-progress? |
| +-- YES: Resume |
| +-- NO: Check pending queue |
| |
+-- Pending tasks? |
| +-- YES: Claim highest priority
| +-- NO: Check phase completion
| |
+-- Phase done? |
| +-- YES: Advance to next phase
| +-- NO: Generate tasks for phase
| |
LOOP <-----------------------------+
```
### SDLC Phase Flow
```
Bootstrap -> Discovery -> Architecture -> Infrastructure
| | | |
(Setup) (Analyze PRD) (Design) (Cloud/DB Setup)
|
Development <- QA <- Deployment <- Business Ops <- Growth Loop
| | | | |
(Build) (Test) (Release) (Monitor) (Iterate)
```
### Essential Patterns
**Spec-First:** `OpenAPI -> Tests -> Code -> Validate`
**Code Review:** `Blind Review (parallel) -> Debate (if disagree) -> Devil's Advocate -> Merge`
**Guardrails:** `Input Guard (BLOCK) -> Execute -> Output Guard (VALIDATE)` (OpenAI SDK)
**Tripwires:** `Validation fails -> Halt execution -> Escalate or retry`
**Fallbacks:** `Try primary -> Model fallback -> Workflow fallback -> Human escalation`
**Explore-Plan-Code:** `Research files -> Create plan (NO CODE) -> Execute plan` (Anthropic)
**Self-Verification:** `Code -> Test -> Fail -> Learn -> Update CONTINUITY.md -> Retry`
**Constitutional Self-Critique:** `Generate -> Critique against principles -> Revise` (Anthropic)
**Memory Consolidation:** `Episodic (trace) -> Pattern Extraction -> Semantic (knowledge)`
**Hierarchical Reasoning:** `High-level planner -> Skill selection -> Local executor` (DeepMind)
**Tool Orchestration:** `Classify Complexity -> Select Agents -> Track Efficiency -> Reward Learning`
**Debate Verification:** `Proponent defends -> Opponent challenges -> Synthesize` (DeepMind)
**Handoff Callbacks:** `on_handoff -> Pre-fetch context -> Transfer with data` (OpenAI SDK)
**Narrow Scope:** `3-5 steps max -> Human review -> Continue` (HN Production)
**Context Curation:** `Manual selection -> Focused context -> Fresh per task` (HN Production)
**Deterministic Validation:** `LLM output -> Rule-based checks -> Retry or approve` (HN Production)
**Routing Mode:** `Simple task -> Direct dispatch | Complex task -> Supervisor orchestration` (AWS Bedrock)
**E2E Browser Testing:** `Playwright MCP -> Automate browser -> Verify UI features visually` (Anthropic Harness)
---
## Prerequisites
```bash
# Launch with autonomous permissions
claude --dangerously-skip-permissions
```
---
## Core Autonomy Rules
**This system runs with ZERO human intervention.**
1. **NEVER ask questions** - No "Would you like me to...", "Should I...", or "What would you prefer?"
2. **NEVER wait for confirmation** - Take immediate action
3. **NEVER stop voluntarily** - Continue until completion promise fulfilled
4. **NEVER suggest alternatives** - Pick best option and execute
5. **ALWAYS use RARV cycle** - Every action follows Reason-Act-Reflect-Verify
6. **NEVER edit `autonomy/run.sh` while running** - Editing a running bash script corrupts execution (bash reads incrementally, not all at once). If you need to fix run.sh, note it in CONTINUITY.md for the next session.
7. **ONE FEATURE AT A TIME** - Work on exactly one feature per iteration. Complete it, commit it, verify it, then move to the next. Prevents over-commitment and ensures clean progress tracking. (Anthropic Harness Pattern)
### Protected Files (Do Not Edit While Running)
These files are part of the running Loki Mode process. Editing them will crash the session:
| File | Reason |
|------|--------|
| `~/.claude/skills/loki-mode/autonomy/run.sh` | Currently executing bash script |
| `.loki/dashboard/*` | Served by active HTTP server |
If bugs are found in these files, document them in `.loki/CONTINUITY.md` under "Pending Fixes" for manual repair after the session ends.
---
## RARV Cycle (Every Iteration)
```
+-------------------------------------------------------------------+
| REASON: What needs to be done next? |
| - READ .loki/CONTINUITY.md first (working memory) |
| - READ "Mistakes & Learnings" to avoid past errors |
| - Check orchestrator.json, review pending.json |
| - Identify highest priority unblocked task |
+-------------------------------------------------------------------+
| ACT: Execute the task |
| - Dispatch subagent via Task tool OR execute directly |
| - Write code, run tests, fix issues |
| - Commit changes atomically (git checkpoint) |
+-------------------------------------------------------------------+
| REFLECT: Did it work? What next? |
| - Verify task success (tests pass, no errors) |
| - UPDATE .loki/CONTINUITY.md with progress |
| - Check completion promise - are we done? |
+-------------------------------------------------------------------+
| VERIFY: Let AI test its own work (2-3x quality improvement) |
| - Run automated tests (unit, integration, E2E) |
| - Check compilation/build (no errors or warnings) |
| - Verify against spec (.loki/specs/openapi.yaml) |
| |
| IF VERIFICATION FAILS: |
| 1. Capture error details (stack trace, logs) |
| 2. Analyze root cause |
| 3. UPDATE CONTINUITY.md "Mistakes & Learnings" |
| 4. Rollback to last good git checkpoint (if needed) |
| 5. Apply learning and RETRY from REASON |
+-------------------------------------------------------------------+
```
---
## Model Selection Strategy
**CRITICAL: Use the right model for each task type. Opus is ONLY for planning/architecture.**
| Model | Use For | Examples |
|-------|---------|----------|
| **Opus 4.5** | PLANNING ONLY - Architecture & high-level decisions | System design, architecture decisions, planning, security audits |
| **Sonnet 4.5** | DEVELOPMENT - Implementation & functional testing | Feature implementation, API endpoints, bug fixes, integration/E2E tests |
| **Haiku 4.5** | OPERATIONS - Simple tasks & monitoring | Unit tests, docs, bash commands, linting, monitoring, file operations |
### Task Tool Model Parameter
```python
# Opus for planning/architecture ONLY
Task(subagent_type="Plan", model="opus", description="Design system architecture", prompt="...")
# Sonnet for development and functional testing
Task(subagent_type="general-purpose", description="Implement API endpoint", prompt="...")
Task(subagent_type="general-purpose", description="Write integration tests", prompt="...")
# Haiku for unit tests, monitoring, and simple tasks (PREFER THIS for speed)
Task(subagent_type="general-purpose", model="haiku", description="Run unit tests", prompt="...")
Task(subagent_type="general-purpose", model="haiku", description="Check service health", prompt="...")
```
### Opus Task Categories (RESTRICTED - Planning Only)
- System architecture design
- High-level planning and strategy
- Security audits and threat modeling
- Major refactoring decisions
- Technology selection
### Sonnet Task Categories (Development)
- Feature implementation
- API endpoint development
- Bug fixes (non-trivial)
- Integration tests and E2E tests
- Code refactoring
- Database migrations
### Haiku Task Categories (Operations - Use Extensively)
- Writing/running unit tests
- Generating documentation
- Running bash commands (npm install, git operations)
- Simple bug fixes (typos, imports, formatting)
- File operations, linting, static analysis
- Monitoring, health checks, log analysis
- Simple data transformations, boilerplate generation
### Parallelization Strategy
```python
# Launch 10+ Haiku agents in parallel for unit test suite
for test_file in test_files:
Task(subagent_type="general-purpose", model="haiku",
description=f"Run unit tests: {test_file}",
run_in_background=True)
```
### Advanced Task Tool Parameters
**Background Agents:**
```python
# Launch background agent - returns immediately with output_file path
Task(description="Long analysis task", run_in_background=True, prompt="...")
# Output truncated to 30K chars - use Read tool to check full output file
```
**Agent Resumption (for interrupted/long-running tasks):**
```python
# First call returns agent_id
result = Task(description="Complex refactor", prompt="...")
# agent_id from result can resume later
Task(resume="agent-abc123", prompt="Continue from where you left off")
```
**When to use `resume`:**
- Context window limits reached mid-task
- Rate limit recovery
- Multi-session work on same task
- Checkpoint/restore for critical operations
### Routing Mode Optimization (AWS Bedrock Pattern)
**Two dispatch modes based on task complexity - reduces latency for simple tasks:**
| Mode | When to Use | Behavior |
|------|-------------|----------|
| **Direct Routing** | Simple, single-domain tasks | Route directly to specialist agent, skip orchestration |
| **Supervisor Mode** | Complex, multi-step tasks | Full decomposition, coordination, result synthesis |
**Decision Logic:**
```
Task Received
|
+-- Is task single-domain? (one file, one skill, clear scope)
| +-- YES: Direct Route to specialist agent
| | - Faster (no orchestration overhead)
| | - Minimal context (avoid confusion)
| | - Examples: "Fix typo in README", "Run unit tests"
| |
| +-- NO: Supervisor Mode
| - Full task decomposition
| - Coordinate multiple agents
| - Synthesize results
| - Examples: "Implement auth system", "Refactor API layer"
|
+-- Fallback: If intent unclear, use Supervisor Mode
```
**Direct Routing Examples (Skip Orchestration):**
```python
# Simple tasks -> Direct dispatch to Haiku
Task(model="haiku", description="Fix import in utils.py", prompt="...") # Direct
Task(model="haiku", description="Run linter on src/", prompt="...") # Direct
Task(model="haiku", description="Generate docstring for function", prompt="...") # Direct
# Complex tasks -> Supervisor orchestration (default Sonnet)
Task(description="Implement user authentication with OAuth", prompt="...") # Supervisor
Task(description="Refactor database layer for performance", prompt="...") # Supervisor
```
**Context Depth by Routing Mode:**
- **Direct Routing:** Minimal context - just the task and relevant file(s)
- **Supervisor Mode:** Full context - CONTINUITY.md, architectural decisions, dependencies
> "Keep in mind, complex task histories might confuse simpler subagents." - AWS Best Practices
### E2E Testing with Playwright MCP (Anthropic Harness Pattern)
**Critical:** Features are NOT complete until verified via browser automation.
```python
# Enable Playwright MCP for E2E testing
# In settings or via mcp_servers config:
mcp_servers = {
"playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}
}
# Agent can then automate browser to verify features work visually
```
**E2E Verification Flow:**
1. Feature implemented and unit tests pass
2. Start dev server via init script
3. Use Playwright MCP to automate browser
4. Verify UI renders correctly
5. Test user interactions (clicks, forms, navigation)
6. Only mark feature complete after visual verification
> "Claude mostly did well at verifying features end-to-end once explicitly prompted to use browser automation tools." - Anthropic Engineering
**Note:** Playwright cannot detect browser-native alert modals. Use custom UI for confirmations.
---
## Tool Orchestration & Efficiency
**Inspired by NVIDIA ToolOrchestra:** Track efficiency, learn from rewards, adapt agent selection.
### Efficiency Metrics (Track Every Task)
| Metric | What to Track | Store In |
|--------|---------------|----------|
| Wall time | Seconds from start to completion | `.loki/metrics/efficiency/` |
| Agent count | Number of subagents spawned | `.loki/metrics/efficiency/` |
| Retry count | Attempts before success | `.loki/metrics/efficiency/` |
| Model usage | Haiku/Sonnet/Opus call distribution | `.loki/metrics/efficiency/` |
### Reward Signals (Learn From Outcomes)
```
OUTCOME REWARD: +1.0 (success) | 0.0 (partial) | -1.0 (failure)
EFFICIENCY REWARD: 0.0-1.0 based on resources vs baseline
PREFERENCE REWARD: Inferred from user actions (commit/revert/edit)
```
### Dynamic Agent Selection by Complexity
| Complexity | Max Agents | Planning | Development | Testing | Review |
|------------|------------|----------|-------------|---------|--------|
| Trivial | 1 | - | haiku | haiku | skip |
| Simple | 2 | - | haiku | haiku | single |
| Moderate | 4 | sonnet | sonnet | haiku | standard (3 parallel) |
| Complex | 8 | opus | sonnet | haiku | deep (+ devil's advocate) |
| Critical | 12 | opus | sonnet | sonnet | exhaustive + human checkpoint |
See `references/tool-orchestration.md` for full implementation details.
---
## Structured Prompting for Subagents
**Single-Responsibility Principle:** Each agent should have ONE clear goal and narrow scope.
([UiPath Best Practices](https://www.uipath.com/blog/ai/agent-builder-best-practices))
**Every subagent dispatch MUST include:**
```markdown
## GOAL (What success looks like)
[High-level objective, not just the action]
Example: "Refactor authentication for maintainability and testability"
NOT: "Refactor the auth file"
## CONSTRAINTS (What you cannot do)
- No third-party dependencies without approval
- Maintain backwards compatibility with v1.x API
- Keep response time under 200ms
## CONTEXT (What you need to know)
- Related files: [list with brief descriptions]
- Previous attempts: [what was tried, why it failed]
## OUTPUT FORMAT (What to deliver)
- [ ] Pull request with Why/What/Trade-offs description
- [ ] Unit tests with >90% coverage
- [ ] Update API documentation
## WHEN COMPLETE
Report back with: WHY, WHAT, TRADE-OFFS, RISKS
```
---
## Quality Gates
**Never ship code without passing all quality gates:**
1. **Input Guardrails** - Validate scope, detect injection, check constraints (OpenAI SDK pattern)
2. **Static Analysis** - CodeQL, ESLint/Pylint, type checking
3. **Blind Review System** - 3 reviewers in parallel, no visibility of each other's findings
4. **Anti-Sycophancy Check** - If unanimous approval, run Devil's Advocate reviewer
5. **Output Guardrails** - Validate code quality, spec compliance, no secrets (tripwire on fail)
6. **Severity-Based Blocking** - Critical/High/Medium = BLOCK; Low/Cosmetic = TODO comment
7. **Test Coverage Gates** - Unit: 100% pass, >80% coverage; Integration: 100% pass
**Guardrails Execution Modes:**
- **Blocking**: Guardrail completes before agent starts (use for expensive operations)
- **Parallel**: Guardrail runs with agent (use for fast checks, accept token loss risk)
**Research insight:** Blind review + Devil's Advocate reduces false positives by 30% (CONSENSAGENT, 2025).
**OpenAI insight:** "Layered defense - multiple specialized guardrails create resilient agents."
See `references/quality-control.md` and `references/openai-patterns.md` for details.
---
## Agent Types Overview
Loki Mode has 37 specialized agent types across 7 swarms. The orchestrator spawns only agents needed for your project.
| Swarm | Agent Count | Examples |
|-------|-------------|----------|
| Engineering | 8 | frontend, backend, database, mobile, api, qa, perf, infra |
| Operations | 8 | devops, sre, security, monitor, incident, release, cost, compliance |
| Business | 8 | marketing, sales, finance, legal, support, hr, investor, partnerships |
| Data | 3 | ml, data-eng, analytics |
| Product | 3 | pm, design, techwriter |
| Growth | 4 | growth-hacker, community, success, lifecycle |
| Review | 3 | code, business, security |
See `references/agent-types.md` for complete definitions and capabilities.
---
## Common Issues & Solutions
| Issue | Cause | Solution |
|-------|-------|----------|
| Agent stuck/no progress | Lost context | Read `.loki/CONTINUITY.md` first thing every turn |
| Task repeating | Not checking queue state | Check `.loki/queue/*.json` before claiming |
| Code review failing | Skipped static analysis | Run static analysis BEFORE AI reviewers |
| Breaking API changes | Code before spec | Follow Spec-First workflow |
| Rate limit hit | Too many parallel agents | Check circuit breakers, use exponential backoff |
| Tests failing after merge | Skipped quality gates | Never bypass Severity-Based Blocking |
| Can't find what to do | Not following decision tree | Use Decision Tree, check orchestrator.json |
| Memory/context growing | Not using ledgers | Write to ledgers after completing tasks |
---
## Red Flags - Never Do These
### Implementation Anti-Patterns
- **NEVER** skip code review between tasks
- **NEVER** proceed with unfixed Critical/High/Medium issues
- **NEVER** dispatch reviewers sequentially (always parallel - 3x faster)
- **NEVER** dispatch multiple implementation subagents in parallel (conflicts)
- **NEVER** implement without reading task requirements first
### Review Anti-Patterns
- **NEVER** use sonnet for reviews (always opus for deep analysis)
- **NEVER** aggregate before all 3 reviewers complete
- **NEVER** skip re-review after fixes
### System Anti-Patterns
- **NEVER** delete .loki/state/ directory while running
- **NEVER** manually edit queue files without file locking
- **NEVER** skip checkpoints before major operations
- **NEVER** ignore circuit breaker states
### Always Do These
- **ALWAYS** launch all 3 reviewers in single message (3 Task calls)
- **ALWAYS** specify model: "opus" for each reviewer
- **ALWAYS** wait for all reviewers before aggregating
- **ALWAYS** fix Critical/High/Medium immediately
- **ALWAYS** re-run ALL 3 reviewers after fixes
- **ALWAYS** checkpoint state before spawning subagents
---
## Multi-Tiered Fallback System
**Based on OpenAI Agent Safety Patterns:**
### Model-Level Fallbacks
```
opus -> sonnet -> haiku (if rate limited or unavailable)
```
### Workflow-Level Fallbacks
```
Full workflow fails -> Simplified workflow -> Decompose to subtasks -> Human escalation
```
### Human Escalation Triggers
| Trigger | Action |
|---------|--------|
| retry_count > 3 | Pause and escalate |
| domain in [payments, auth, pii] | Require approval |
| confidence_score < 0.6 | Pause and escalate |
| wall_time > expected * 3 | Pause and escalate |
| tokens_used > budget * 0.8 | Pause and escalate |
See `references/openai-patterns.md` for full fallback implementation.
---
## AGENTS.md Integration
**Read target project's AGENTS.md if exists** (OpenAI/AAIF standard):
```
Context Priority:
1. AGENTS.md (closest to current file)
2. CLAUDE.md (Claude-specific)
3. .loki/CONTINUITY.md (session state)
4. Package docs
5. README.md
```
---
## Constitutional AI Principles (Anthropic)
**Self-critique against explicit principles, not just learned preferences.**
### Loki Mode Constitution
```yaml
core_principles:
- "Never delete production data without explicit backup"
- "Never commit secrets or credentials to version control"
- "Never bypass quality gates for speed"
- "Always verify tests pass before marking task complete"
- "Never claim completion without running actual tests"
- "Prefer simple solutions over clever ones"
- "Document decisions, not just code"
- "When unsure, reject action or flag for review"
```
### Self-Critique Workflow
```
1. Generate response/code
2. Critique against each principle
3. Revise if any principle violated
4. Only then proceed with action
```
See `references/lab-research-patterns.md` for Constitutional AI implementation.
---
## Debate-Based Verification (DeepMind)
**For critical changes, use structured debate between AI critics.**
```
Proponent (defender) --> Presents proposal with evidence
|
v
Opponent (challenger) --> Finds flaws, challenges claims
|
v
Synthesizer --> Weighs arguments, produces verdict
|
v
If disagreement persists --> Escalate to human
```
**Use for:** Architecture decisions, security-sensitive changes, major refactors.
See `references/lab-research-patterns.md` for debate verification details.
---
## Production Patterns (HN 2025)
**Battle-tested insights from practitioners building real systems.**
### Narrow Scope Wins
```yaml
task_constraints:
max_steps_before_review: 3-5
characteristics:
- Specific, well-defined objectives
- Pre-classified inputs
- Deterministic success criteria
- Verifiable outputs
```
### Confidence-Based Routing
```
confidence >= 0.95 --> Auto-approve with audit log
confidence >= 0.70 --> Quick human review
confidence >= 0.40 --> Detailed human review
confidence < 0.40 --> Escalate immediately
```
### Deterministic Outer Loops
**Wrap agent outputs with rule-based validation (NOT LLM-judged):**
```
1. Agent generates output
2. Run linter (deterministic)
3. Run tests (deterministic)
4. Check compilation (deterministic)
5. Only then: human or AI review
```
### Context Engineering
```yaml
principles:
- "Less is more" - focused beats comprehensive
- Manual selection outperforms automatic RAG
- Fresh conversations per major task
- Remove outdated information aggressively
context_budget:
target: "< 10k tokens for context"
reserve: "90% for model reasoning"
```
### Sub-Agents for Context Isolation
**Use sub-agents to prevent token waste on noisy subtasks:**
```
Main agent (focused) --> Sub-agent (file search)
--> Sub-agent (test running)
--> Sub-agent (linting)
```
See `references/production-patterns.md` for full practitioner patterns.
---
## Exit Conditions
| Condition | Action |
|-----------|--------|
| Product launched, stable 24h | Enter growth loop mode |
| Unrecoverable failure | Save state, halt, request human |
| PRD updated | Diff, create delta tasks, continue |
| Revenue target hit | Log success, continue optimization |
| Runway < 30 days | Alert, optimize costs aggressively |
---
## Directory Structure Overview
```
.loki/
+-- CONTINUITY.md # Working memory (read/update every turn)
+-- specs/
| +-- openapi.yaml # API spec - source of truth
+-- queue/
| +-- pending.json # Tasks waiting to be claimed
| +-- in-progress.json # Currently executing tasks
| +-- completed.json # Finished tasks
| +-- dead-letter.json # Failed tasks for review
+-- state/
| +-- orchestrator.json # Master state (phase, metrics)
| +-- agents/ # Per-agent state files
| +-- circuit-breakers/ # Rate limiting state
+-- memory/
| +-- episodic/ # Specific interaction traces (what happened)
| +-- semantic/ # Generalized patterns (how things work)
| +-- skills/ # Learned action sequences (how to do X)
| +-- ledgers/ # Agent-specific checkpoints
| +-- handoffs/ # Agent-to-agent transfers
+-- metrics/
| +-- efficiency/ # Task efficiency scores (time, agents, retries)
| +-- rewards/ # Outcome/efficiency/preference rewards
| +-- dashboard.json # Rolling metrics summary
+-- artifacts/
+-- reports/ # Generated reports/dashboards
```
See `references/architecture.md` for full structure and state schemas.
---
## Invocation
```
Loki Mode # Start fresh
Loki Mode with PRD at path/to/prd # Start with PRD
```
**Skill Metadata:**
| Field | Value |
|-------|-------|
| Trigger | "Loki Mode" or "Loki Mode with PRD at [path]" |
| Skip When | Need human approval, want to review plan first, single small task |
| Related Skills | subagent-driven-development, executing-plans |
---
## References
Detailed documentation is split into reference files for progressive loading:
| Reference | Content |
|-----------|---------|
| `references/core-workflow.md` | Full RARV cycle, CONTINUITY.md template, autonomy rules |
| `references/quality-control.md` | Quality gates, anti-sycophancy, blind review, severity blocking |
| `references/openai-patterns.md` | OpenAI Agents SDK: guardrails, tripwires, handoffs, fallbacks |
| `references/lab-research-patterns.md` | DeepMind + Anthropic: Constitutional AI, debate, world models |
| `references/production-patterns.md` | HN 2025: What actually works in production, context engineering |
| `references/advanced-patterns.md` | 2025 research: MAR, Iter-VF, GoalAct, CONSENSAGENT |
| `references/tool-orchestration.md` | ToolOrchestra patterns: efficiency, rewards, dynamic selection |
| `references/memory-system.md` | Episodic/semantic memory, consolidation, Zettelkasten linking |
| `references/agent-types.md` | All 37 agent types with full capabilities |
| `references/task-queue.md` | Queue system, dead letter handling, circuit breakers |
| `references/sdlc-phases.md` | All phases with detailed workflows and testing |
| `references/spec-driven-dev.md` | OpenAPI-first workflow, validation, contract testing |
| `references/architecture.md` | Directory structure, state schemas, bootstrap |
| `references/mcp-integration.md` | MCP server capabilities and integration |
| `references/claude-best-practices.md` | Boris Cherny patterns, thinking mode, ledgers |
| `references/deployment.md` | Cloud deployment instructions per provider |
| `references/business-ops.md` | Business operation workflows |
---
**Version:** 2.32.0 | **Lines:** ~600 | **Research-Enhanced: Labs + HN Production Patterns**

1
skills/loki-mode/VERSION Normal file
View File

@@ -0,0 +1 @@
2.35.1

View File

@@ -0,0 +1,497 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Loki Mode Dashboard</title>
<style>
:root {
--bg-cream: #FDF6E3;
--bg-dark: #1a1a2e;
--coral: #FF6B6B;
--coral-light: #FF8E8E;
--teal: #4ECDC4;
--purple: #A78BFA;
--yellow: #FCD34D;
--green: #10B981;
--red: #EF4444;
--text-dark: #2D3748;
--text-light: #718096;
--card-bg: #FFFFFF;
--border: #E2E8F0;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: var(--bg-cream);
color: var(--text-dark);
min-height: 100vh;
padding: 24px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 32px;
}
.logo {
display: flex;
align-items: center;
gap: 12px;
}
.logo-icon {
width: 48px;
height: 48px;
background: linear-gradient(135deg, var(--coral), var(--coral-light));
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
color: white;
font-weight: bold;
}
.logo-text {
font-size: 28px;
font-weight: 700;
color: var(--text-dark);
}
.status-bar {
display: flex;
gap: 16px;
align-items: center;
}
.status-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: var(--card-bg);
border-radius: 8px;
border: 1px solid var(--border);
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.status-dot.active { background: var(--green); }
.status-dot.warning { background: var(--yellow); }
.status-dot.error { background: var(--red); }
.section {
margin-bottom: 32px;
}
.section-title {
font-size: 20px;
font-weight: 600;
margin-bottom: 16px;
color: var(--text-dark);
}
.agents-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: 16px;
}
.agent-card {
background: var(--card-bg);
border-radius: 12px;
padding: 20px;
border: 1px solid var(--border);
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.agent-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 12px;
}
.agent-id {
font-weight: 600;
font-size: 14px;
color: var(--text-dark);
}
.agent-type {
font-size: 12px;
color: var(--text-light);
margin-top: 4px;
}
.model-badge {
padding: 4px 10px;
border-radius: 12px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
}
.model-badge.sonnet {
background: #E0E7FF;
color: #4338CA;
}
.model-badge.haiku {
background: #D1FAE5;
color: #065F46;
}
.model-badge.opus {
background: #FDE68A;
color: #92400E;
}
.agent-work {
font-size: 13px;
color: var(--text-dark);
line-height: 1.5;
margin-bottom: 16px;
}
.agent-stats {
display: flex;
gap: 16px;
font-size: 12px;
color: var(--text-light);
}
.stat {
display: flex;
align-items: center;
gap: 4px;
}
.agent-status {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.status-active {
color: var(--green);
}
.status-completed {
color: var(--purple);
}
/* Task Queue Section */
.queue-columns {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 16px;
}
.queue-column {
background: var(--card-bg);
border-radius: 12px;
padding: 16px;
border: 1px solid var(--border);
min-height: 300px;
}
.queue-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
padding-bottom: 12px;
border-bottom: 2px solid var(--border);
}
.queue-title {
font-weight: 600;
font-size: 14px;
}
.queue-count {
background: var(--bg-cream);
padding: 4px 10px;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
}
.queue-column.pending .queue-header { border-color: var(--yellow); }
.queue-column.in-progress .queue-header { border-color: var(--teal); }
.queue-column.completed .queue-header { border-color: var(--green); }
.queue-column.failed .queue-header { border-color: var(--red); }
.task-card {
background: var(--bg-cream);
border-radius: 8px;
padding: 12px;
margin-bottom: 8px;
font-size: 12px;
}
.task-id {
font-weight: 600;
color: var(--text-dark);
margin-bottom: 4px;
}
.task-type {
display: inline-block;
padding: 2px 8px;
background: var(--card-bg);
border-radius: 4px;
font-size: 10px;
color: var(--text-light);
margin-bottom: 8px;
}
.task-desc {
color: var(--text-dark);
line-height: 1.4;
}
.last-updated {
text-align: center;
color: var(--text-light);
font-size: 12px;
margin-top: 24px;
}
@media (max-width: 1024px) {
.queue-columns {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 640px) {
.queue-columns {
grid-template-columns: 1fr;
}
.agents-grid {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="header">
<div class="logo">
<div class="logo-icon">L</div>
<span class="logo-text">Loki Mode Dashboard</span>
</div>
<div class="status-bar">
<div class="status-item">
<div class="status-dot active"></div>
<span>Phase: DEVELOPMENT</span>
</div>
<div class="status-item">
<span>v2.18.0</span>
</div>
</div>
</div>
<div class="section" id="agents-section">
<h2 class="section-title">Active Agents</h2>
<div class="agents-grid" id="agents-grid">
<!-- Agent cards populated by JS -->
</div>
</div>
<div class="section" id="queue-section">
<h2 class="section-title">Task Queue</h2>
<div class="queue-columns" id="queue-columns">
<div class="queue-column pending">
<div class="queue-header">
<span class="queue-title">Pending</span>
<span class="queue-count" id="pending-count">0</span>
</div>
<div id="pending-tasks"></div>
</div>
<div class="queue-column in-progress">
<div class="queue-header">
<span class="queue-title">In Progress</span>
<span class="queue-count" id="in-progress-count">0</span>
</div>
<div id="in-progress-tasks"></div>
</div>
<div class="queue-column completed">
<div class="queue-header">
<span class="queue-title">Completed</span>
<span class="queue-count" id="completed-count">0</span>
</div>
<div id="completed-tasks"></div>
</div>
<div class="queue-column failed">
<div class="queue-header">
<span class="queue-title">Failed</span>
<span class="queue-count" id="failed-count">0</span>
</div>
<div id="failed-tasks"></div>
</div>
</div>
</div>
<div class="last-updated" id="last-updated">
Last updated: --
</div>
<script>
// Demo data for screenshots
const demoAgents = [
{
id: 'eng-001-backend-api',
type: 'Engineering Backend',
model: 'sonnet',
work: 'Implementing POST /api/todos endpoint with validation and SQLite storage',
runtime: '12m 34s',
tasks: 5,
status: 'active'
},
{
id: 'eng-002-frontend-ui',
type: 'Engineering Frontend',
model: 'sonnet',
work: 'Building React components for todo list with Tailwind styling',
runtime: '8m 21s',
tasks: 3,
status: 'active'
},
{
id: 'qa-001-testing',
type: 'QA Testing',
model: 'haiku',
work: 'Writing unit tests for authentication module',
runtime: '5m 45s',
tasks: 8,
status: 'active'
},
{
id: 'review-security-001',
type: 'Security Review',
model: 'opus',
work: 'Analyzing auth flow for OWASP vulnerabilities',
runtime: '3m 12s',
tasks: 2,
status: 'active'
},
{
id: 'ops-devops-001',
type: 'Operations DevOps',
model: 'sonnet',
work: 'Configuring GitHub Actions CI/CD pipeline',
runtime: '15m 08s',
tasks: 4,
status: 'active'
},
{
id: 'biz-marketing-001',
type: 'Business Marketing',
model: 'haiku',
work: 'Creating landing page copy and SEO meta tags',
runtime: '6m 33s',
tasks: 2,
status: 'completed'
}
];
const demoTasks = {
pending: [
{ id: 'task-015', type: 'eng-database', desc: 'Create migration for user preferences table' },
{ id: 'task-016', type: 'eng-frontend', desc: 'Implement dark mode toggle component' },
{ id: 'task-017', type: 'qa-testing', desc: 'Write E2E tests for checkout flow' }
],
inProgress: [
{ id: 'task-012', type: 'eng-backend', desc: 'Implement JWT refresh token rotation' },
{ id: 'task-013', type: 'eng-frontend', desc: 'Add form validation to signup page' }
],
completed: [
{ id: 'task-001', type: 'eng-backend', desc: 'Setup Express server with TypeScript' },
{ id: 'task-002', type: 'eng-database', desc: 'Create initial SQLite schema' },
{ id: 'task-003', type: 'eng-frontend', desc: 'Initialize React with Vite' },
{ id: 'task-004', type: 'ops-devops', desc: 'Configure ESLint and Prettier' },
{ id: 'task-005', type: 'eng-backend', desc: 'Implement user registration endpoint' }
],
failed: []
};
function renderAgents() {
const grid = document.getElementById('agents-grid');
grid.innerHTML = demoAgents.map(agent => `
<div class="agent-card">
<div class="agent-header">
<div>
<div class="agent-id">${agent.id}</div>
<div class="agent-type">${agent.type}</div>
</div>
<span class="model-badge ${agent.model}">${agent.model}</span>
</div>
<div class="agent-work">${agent.work}</div>
<div class="agent-stats">
<span class="stat">Runtime: ${agent.runtime}</span>
<span class="stat">Tasks: ${agent.tasks}</span>
</div>
<div class="agent-status ${agent.status === 'active' ? 'status-active' : 'status-completed'}">
<div class="status-dot ${agent.status === 'active' ? 'active' : ''}"></div>
${agent.status === 'active' ? 'Active' : 'Completed'}
</div>
</div>
`).join('');
}
function renderTasks() {
const renderTaskList = (tasks, containerId) => {
const container = document.getElementById(containerId);
container.innerHTML = tasks.map(task => `
<div class="task-card">
<div class="task-id">${task.id}</div>
<span class="task-type">${task.type}</span>
<div class="task-desc">${task.desc}</div>
</div>
`).join('');
};
renderTaskList(demoTasks.pending, 'pending-tasks');
renderTaskList(demoTasks.inProgress, 'in-progress-tasks');
renderTaskList(demoTasks.completed.slice(0, 5), 'completed-tasks');
renderTaskList(demoTasks.failed, 'failed-tasks');
document.getElementById('pending-count').textContent = demoTasks.pending.length;
document.getElementById('in-progress-count').textContent = demoTasks.inProgress.length;
document.getElementById('completed-count').textContent = demoTasks.completed.length;
document.getElementById('failed-count').textContent = demoTasks.failed.length;
}
function updateTimestamp() {
const now = new Date().toLocaleString();
document.getElementById('last-updated').textContent = `Last updated: ${now}`;
}
// Initial render
renderAgents();
renderTasks();
updateTimestamp();
// Auto-refresh every 3 seconds (in production, would fetch real data)
setInterval(updateTimestamp, 3000);
</script>
</body>
</html>

View File

@@ -0,0 +1,402 @@
# Loki Mode Agent Constitution
> **Machine-Enforceable Behavioral Contract for All Agents**
> Version 1.0.0 | Immutable Principles | Context-Preserved Lineage
---
## Core Principles (Inviolable)
### 1. Specification-First Development
**RULE:** No code shall be written before the specification exists.
**Enforcement:**
```
IF task.type == "implementation" AND !exists(spec_file):
BLOCK with error: "SPEC_MISSING"
REQUIRE: Create OpenAPI spec first
```
**Rationale:** Specs are contracts. Code is implementation. Contract before implementation.
### 2. Git Checkpoint System
**RULE:** Every completed task MUST create a git checkpoint.
**Enforcement:**
```
ON task.status == "completed":
git add <modified_files>
git commit -m "[Loki] Task ${task.id}: ${task.title}"
UPDATE CONTINUITY.md with commit SHA
```
**Rationale:** Git history is proof of progress. Every task is a save point.
### 3. Context Preservation
**RULE:** All agents MUST inherit and preserve context from their spawning agent.
**Enforcement:**
```
ON agent.spawn():
agent.context.parent_id = spawner.agent_id
agent.context.lineage = [...spawner.lineage, spawner.agent_id]
agent.context.inherited_memory = spawner.memory.export()
WRITE .agent/sub-agents/${agent.agent_id}.json
```
**Rationale:** Context drift kills multi-agent systems. Lineage is truth.
### 4. Iterative Specification Questions
**RULE:** During spec generation, agents MUST ask clarifying questions before assuming.
**Enforcement:**
```
WHILE generating_spec:
IF ambiguity_detected OR assumption_required:
questions = generate_clarifying_questions()
IF orchestrator_mode:
answers = infer_from_prd()
ELSE:
answers = ask_user(questions)
UPDATE spec WITH answers
```
**Rationale:** Assumptions create bugs. Questions create clarity.
### 5. Machine-Readable Rules
**RULE:** All behavioral rules MUST be represented as structured artifacts, not just prose.
**Enforcement:**
```
rules/
├── pre-commit.schema.json # Validation rules
├── quality-gates.yaml # Quality thresholds
├── agent-contracts.json # Agent responsibilities
└── invariants.ts # Runtime assertions
```
**Rationale:** Humans read markdown. Machines enforce JSON/YAML.
---
## Agent Behavioral Contracts
### Orchestrator Agent
**Responsibilities:**
- Initialize .loki/ directory structure
- Maintain CONTINUITY.md (working memory)
- Coordinate task queue (pending → in-progress → completed)
- Enforce quality gates
- Manage git checkpoints
**Prohibited Actions:**
- Writing implementation code directly
- Skipping spec generation
- Modifying completed tasks without explicit override
**Context Obligations:**
- MUST read CONTINUITY.md before every action
- MUST update orchestrator.json after phase transitions
- MUST preserve task lineage in completed.json
### Engineering Swarm Agents
**Responsibilities:**
- Implement features per OpenAPI spec
- Write contract tests before implementation
- Create git commits for completed tasks
- Ask clarifying questions when spec is ambiguous
**Prohibited Actions:**
- Implementing without spec
- Skipping tests
- Ignoring linter/type errors
**Context Obligations:**
- MUST inherit parent agent's context
- MUST log all decisions to .agent/sub-agents/${agent_id}.md
- MUST reference spec in all implementation commits
### QA Swarm Agents
**Responsibilities:**
- Generate test cases from OpenAPI spec
- Run contract validation tests
- Report discrepancies between code and spec
- Create bug reports in dead-letter queue
**Prohibited Actions:**
- Modifying implementation code
- Skipping failing tests
- Approving incomplete features
**Context Obligations:**
- MUST validate against spec as source of truth
- MUST log test results to ledgers/
- MUST create git commits for test additions
### DevOps Swarm Agents
**Responsibilities:**
- Automate deployment pipelines
- Monitor service health
- Configure infrastructure as code
- Manage environment secrets
**Prohibited Actions:**
- Storing secrets in plaintext
- Deploying without health checks
- Skipping rollback procedures
**Context Obligations:**
- MUST log all deployments to deployment ledger
- MUST preserve deployment context for rollback
- MUST track infrastructure state in orchestrator.json
---
## Quality Gates (Machine-Enforceable)
### Pre-Commit Hook (BLOCKING)
```yaml
quality_gates:
linting:
enabled: true
auto_fix: true
block_on_failure: true
type_checking:
enabled: true
strict_mode: true
block_on_failure: true
contract_tests:
enabled: true
min_coverage: 80%
block_on_failure: true
spec_validation:
enabled: true
validator: spectral
block_on_failure: true
```
### Post-Implementation Review (AUTO-FIX)
```yaml
auto_review:
static_analysis:
tools: [eslint, prettier, tsc]
auto_fix: true
security_scan:
tools: [semgrep, snyk]
severity_threshold: medium
auto_create_issues: true
performance_check:
lighthouse_score: 90
bundle_size_limit: 500kb
warn_only: true
```
---
## Memory Hierarchy (Priority Order)
### 1. CONTINUITY.md (Volatile - Every Turn)
**Purpose:** What am I doing RIGHT NOW?
**Update Frequency:** Every turn
**Content:** Current task, phase, blockers, next steps
### 2. CONSTITUTION.md (Immutable - This File)
**Purpose:** How MUST I behave?
**Update Frequency:** Version bumps only
**Content:** Behavioral contracts, quality gates, invariants
### 3. CLAUDE.md (Semi-Stable - Significant Changes)
**Purpose:** What is this project?
**Update Frequency:** Architecture changes
**Content:** Tech stack, patterns, project context
### 4. Ledgers (Append-Only - Checkpoint)
**Purpose:** What happened?
**Update Frequency:** After significant events
**Content:** Decisions, deployments, reviews
### 5. .agent/sub-agents/*.json (Lineage Tracking)
**Purpose:** Who did what and why?
**Update Frequency:** Agent lifecycle events
**Content:** Agent context, decisions, inherited memory
---
## Context Lineage Schema
```json
{
"agent_id": "eng-001-backend-api",
"agent_type": "general-purpose",
"model": "haiku",
"spawned_at": "2026-01-04T05:30:00Z",
"spawned_by": "orchestrator-main",
"lineage": ["orchestrator-main", "eng-001-backend-api"],
"inherited_context": {
"phase": "development",
"current_task": "task-005",
"spec_reference": ".loki/specs/openapi.yaml#/paths/~1api~1todos",
"tech_stack": ["Node.js", "Express", "TypeScript", "SQLite"]
},
"decisions_made": [
{
"timestamp": "2026-01-04T05:31:15Z",
"question": "Should we use Prisma or raw SQL?",
"answer": "Raw SQL with better-sqlite3 for simplicity",
"rationale": "PRD requires minimal dependencies, synchronous ops preferred"
}
],
"tasks_completed": ["task-005"],
"commits_created": ["abc123f", "def456a"],
"status": "completed",
"completed_at": "2026-01-04T05:45:00Z"
}
```
---
## Git Checkpoint Protocol
### Commit Message Format
```
[Loki] ${agent_type}-${task_id}: ${task_title}
${detailed_description}
Agent: ${agent_id}
Parent: ${parent_agent_id}
Spec: ${spec_reference}
Tests: ${test_files}
```
### Example
```
[Loki] eng-005-backend: Implement POST /api/todos endpoint
Created todo creation endpoint per OpenAPI spec.
- Input validation for title field
- SQLite insertion with timestamps
- Returns 201 with created todo object
- Contract tests passing
Agent: eng-001-backend-api
Parent: orchestrator-main
Spec: .loki/specs/openapi.yaml#/paths/~1api~1todos/post
Tests: backend/tests/todos.contract.test.ts
```
---
## Invariants (Runtime Assertions)
```typescript
// .loki/rules/invariants.ts
export const INVARIANTS = {
// Spec must exist before implementation
SPEC_BEFORE_CODE: (task: Task) => {
if (task.type === 'implementation') {
assert(exists(task.spec_reference), 'SPEC_MISSING');
}
},
// All tasks must have git commits
TASK_HAS_COMMIT: (task: Task) => {
if (task.status === 'completed') {
assert(task.git_commit_sha, 'COMMIT_MISSING');
}
},
// Agent lineage must be preserved
AGENT_HAS_LINEAGE: (agent: Agent) => {
assert(agent.lineage.length > 0, 'LINEAGE_MISSING');
assert(agent.spawned_by, 'PARENT_MISSING');
},
// CONTINUITY.md must always exist
CONTINUITY_EXISTS: () => {
assert(exists('.loki/CONTINUITY.md'), 'CONTINUITY_MISSING');
},
// Quality gates must pass before merge
QUALITY_GATES_PASSED: (task: Task) => {
if (task.status === 'completed') {
assert(task.quality_checks.all_passed, 'QUALITY_GATE_FAILED');
}
}
};
```
---
## Visual Specification Aids
### Mermaid Diagram Generation (Required for Complex Features)
**RULE:** Architecture decisions and complex workflows MUST include Mermaid diagrams.
**Example - Authentication Flow:**
```mermaid
sequenceDiagram
participant C as Client
participant A as API
participant D as Database
C->>A: POST /api/auth/login
A->>A: Validate credentials
A->>D: Query user
D-->>A: User record
A->>A: Generate JWT token
A-->>C: 200 OK {token}
```
**Storage Location:** `.loki/diagrams/${feature_name}.mmd`
**When Required:**
- Multi-step workflows (3+ steps)
- System architecture changes
- Complex state machines
- Integration points between services
---
## Amendment Process
This constitution can only be amended through:
1. Version bump in header
2. Git commit with `[CONSTITUTION]` prefix
3. Changelog entry documenting what changed and why
4. Re-validation of all existing agents against new rules
**Example Amendment Commit:**
```
[CONSTITUTION] v1.1.0: Add visual specification requirement
Added requirement for Mermaid diagrams on complex features to prevent
ambiguity in multi-step workflows. Based on Addy Osmani's insight that
visual aids significantly improve AI-to-AI communication.
Breaking changes: None
New rules: Section "Visual Specification Aids"
```
---
## Enforcement
All rules in this constitution are **machine-enforceable** and **MUST** be implemented as:
1. Pre-commit hooks (Git)
2. Runtime assertions (TypeScript invariants)
3. Quality gate validators (YAML configs)
4. Agent behavior validators (JSON schemas)
**Human guidance is advisory. Machine enforcement is mandatory.**
---
*"In autonomous systems, trust is built on invariants, not intentions."*

View File

@@ -0,0 +1,201 @@
# Loki Mode - Autonomous Runner
Single script that handles everything: prerequisites, setup, Vibe Kanban monitoring, and autonomous execution with auto-resume.
## Quick Start
```bash
# Run with a PRD
./autonomy/run.sh ./docs/requirements.md
# Run interactively
./autonomy/run.sh
```
That's it! The script will:
1. Check all prerequisites (Claude CLI, Python, Git, etc.)
2. Verify skill installation
3. Initialize the `.loki/` directory
4. **Start Vibe Kanban background sync** (monitor tasks in real-time)
5. Start Claude Code with **live output** (no more waiting blindly)
6. Auto-resume on rate limits or interruptions
7. Continue until completion or max retries
## Live Output
Claude's output is displayed in real-time - you can see exactly what's happening:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CLAUDE CODE OUTPUT (live)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
[Claude's output appears here in real-time...]
```
## Status Monitor (Built-in)
The runner updates `.loki/STATUS.txt` every 5 seconds with task progress:
```
╔════════════════════════════════════════════════════════════════╗
║ LOKI MODE STATUS ║
╚════════════════════════════════════════════════════════════════╝
Updated: Sat Dec 28 15:30:00 PST 2025
Phase: DEVELOPMENT
Tasks:
├─ Pending: 10
├─ In Progress: 1
├─ Completed: 5
└─ Failed: 0
Monitor: watch -n 2 cat .loki/STATUS.txt
```
### Monitor in Another Terminal
```bash
# Watch status updates live
watch -n 2 cat .loki/STATUS.txt
# Or view once
cat .loki/STATUS.txt
```
## What Gets Checked
| Prerequisite | Required | Notes |
|--------------|----------|-------|
| Claude Code CLI | Yes | Install from https://claude.ai/code |
| Python 3 | Yes | For state management |
| Git | Yes | For version control |
| curl | Yes | For web fetches |
| Node.js | No | Needed for some builds |
| jq | No | Helpful for JSON parsing |
## Configuration
Environment variables:
```bash
# Retry settings
export LOKI_MAX_RETRIES=50 # Max retry attempts (default: 50)
export LOKI_BASE_WAIT=60 # Base wait time in seconds (default: 60)
export LOKI_MAX_WAIT=3600 # Max wait time in seconds (default: 3600)
# Skip prerequisite checks (for CI/CD or repeat runs)
export LOKI_SKIP_PREREQS=true
# Run with custom settings
LOKI_MAX_RETRIES=100 LOKI_BASE_WAIT=120 ./autonomy/run.sh ./docs/prd.md
```
## How Auto-Resume Works
```
┌─────────────────────────────────────────────────────────────┐
│ ./autonomy/run.sh prd.md │
└─────────────────────────────────────────────────────────────┘
┌───────────────────────┐
│ Check Prerequisites │
└───────────────────────┘
┌───────────────────────┐
│ Initialize .loki/ │
└───────────────────────┘
┌────────────────────────────────┐
│ Run Claude Code with prompt │◄────────────────┐
└────────────────────────────────┘ │
│ │
▼ │
┌───────────────────────┐ │
│ Claude exits │ │
└───────────────────────┘ │
│ │
┌───────────┴───────────┐ │
▼ ▼ │
┌───────────────┐ ┌───────────────┐ │
│ Completed? │──Yes──│ SUCCESS! │ │
└───────────────┘ └───────────────┘ │
│ No │
▼ │
┌───────────────┐ │
│ Wait (backoff)│─────────────────────────────────────┘
└───────────────┘
```
## State Files
The autonomy runner creates:
```
.loki/
├── autonomy-state.json # Runner state (retry count, status)
├── logs/
│ └── autonomy-*.log # Execution logs
├── state/
│ └── orchestrator.json # Loki Mode phase tracking
└── COMPLETED # Created when done
```
## Resuming After Interruption
If you stop the script (Ctrl+C) or it crashes, just run it again:
```bash
# State is saved, will resume from last checkpoint
./autonomy/run.sh ./docs/requirements.md
```
The script detects the previous state and continues from where it left off.
## Differences from Manual Mode
| Feature | Manual Mode | Autonomy Mode |
|---------|-------------|---------------|
| Start | `claude --dangerously-skip-permissions` | `./autonomy/run.sh` |
| Prereq check | Manual | Automatic |
| Rate limit handling | Manual restart | Auto-resume |
| State persistence | Manual checkpoint | Automatic |
| Logging | Console only | Console + file |
| Max runtime | Session-based | Configurable retries |
## Troubleshooting
### "Claude Code CLI not found"
```bash
npm install -g @anthropic-ai/claude-code
# or visit https://claude.ai/code
```
### "SKILL.md not found"
Make sure you're running from the loki-mode directory or have installed the skill:
```bash
# Option 1: Run from project directory
cd /path/to/loki-mode
./autonomy/run.sh
# Option 2: Install skill globally
cp -r . ~/.claude/skills/loki-mode/
```
### "Max retries exceeded"
The task is taking too long or repeatedly failing. Check:
```bash
# View logs
cat .loki/logs/autonomy-*.log | tail -100
# Check orchestrator state
cat .loki/state/orchestrator.json
# Increase retries
LOKI_MAX_RETRIES=200 ./autonomy/run.sh ./docs/prd.md
```

1991
skills/loki-mode/autonomy/run.sh Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,164 @@
{"task_id": "HumanEval/0", "prompt": "from typing import List\n\n\ndef has_close_elements(numbers: List[float], threshold: float) -> bool:\n \"\"\" Check if in given list of numbers, are any two numbers closer to each other than\n given threshold.\n >>> has_close_elements([1.0, 2.0, 3.0], 0.5)\n False\n >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)\n True\n \"\"\"\n", "entry_point": "has_close_elements", "canonical_solution": " for idx, elem in enumerate(numbers):\n for idx2, elem2 in enumerate(numbers):\n if idx != idx2:\n distance = abs(elem - elem2)\n if distance < threshold:\n return True\n\n return False\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3) == True\n assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05) == False\n assert candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.95) == True\n assert candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.8) == False\n assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1) == True\n assert candidate([1.1, 2.2, 3.1, 4.1, 5.1], 1.0) == True\n assert candidate([1.1, 2.2, 3.1, 4.1, 5.1], 0.5) == False\n\n"}
{"task_id": "HumanEval/1", "prompt": "from typing import List\n\n\ndef separate_paren_groups(paren_string: str) -> List[str]:\n \"\"\" Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n separate those group into separate strings and return the list of those.\n Separate groups are balanced (each open brace is properly closed) and not nested within each other\n Ignore any spaces in the input string.\n >>> separate_paren_groups('( ) (( )) (( )( ))')\n ['()', '(())', '(()())']\n \"\"\"\n", "entry_point": "separate_paren_groups", "canonical_solution": " result = []\n current_string = []\n current_depth = 0\n\n for c in paren_string:\n if c == '(':\n current_depth += 1\n current_string.append(c)\n elif c == ')':\n current_depth -= 1\n current_string.append(c)\n\n if current_depth == 0:\n result.append(''.join(current_string))\n current_string.clear()\n\n return result\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('(()()) ((())) () ((())()())') == [\n '(()())', '((()))', '()', '((())()())'\n ]\n assert candidate('() (()) ((())) (((())))') == [\n '()', '(())', '((()))', '(((())))'\n ]\n assert candidate('(()(())((())))') == [\n '(()(())((())))'\n ]\n assert candidate('( ) (( )) (( )( ))') == ['()', '(())', '(()())']\n"}
{"task_id": "HumanEval/2", "prompt": "\n\ndef truncate_number(number: float) -> float:\n \"\"\" Given a positive floating point number, it can be decomposed into\n and integer part (largest integer smaller than given number) and decimals\n (leftover part always smaller than 1).\n\n Return the decimal part of the number.\n >>> truncate_number(3.5)\n 0.5\n \"\"\"\n", "entry_point": "truncate_number", "canonical_solution": " return number % 1.0\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(3.5) == 0.5\n assert abs(candidate(1.33) - 0.33) < 1e-6\n assert abs(candidate(123.456) - 0.456) < 1e-6\n"}
{"task_id": "HumanEval/3", "prompt": "from typing import List\n\n\ndef below_zero(operations: List[int]) -> bool:\n \"\"\" You're given a list of deposit and withdrawal operations on a bank account that starts with\n zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n at that point function should return True. Otherwise it should return False.\n >>> below_zero([1, 2, 3])\n False\n >>> below_zero([1, 2, -4, 5])\n True\n \"\"\"\n", "entry_point": "below_zero", "canonical_solution": " balance = 0\n\n for op in operations:\n balance += op\n if balance < 0:\n return True\n\n return False\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([]) == False\n assert candidate([1, 2, -3, 1, 2, -3]) == False\n assert candidate([1, 2, -4, 5, 6]) == True\n assert candidate([1, -1, 2, -2, 5, -5, 4, -4]) == False\n assert candidate([1, -1, 2, -2, 5, -5, 4, -5]) == True\n assert candidate([1, -2, 2, -2, 5, -5, 4, -4]) == True\n"}
{"task_id": "HumanEval/4", "prompt": "from typing import List\n\n\ndef mean_absolute_deviation(numbers: List[float]) -> float:\n \"\"\" For a given list of input numbers, calculate Mean Absolute Deviation\n around the mean of this dataset.\n Mean Absolute Deviation is the average absolute difference between each\n element and a centerpoint (mean in this case):\n MAD = average | x - x_mean |\n >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])\n 1.0\n \"\"\"\n", "entry_point": "mean_absolute_deviation", "canonical_solution": " mean = sum(numbers) / len(numbers)\n return sum(abs(x - mean) for x in numbers) / len(numbers)\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert abs(candidate([1.0, 2.0, 3.0]) - 2.0/3.0) < 1e-6\n assert abs(candidate([1.0, 2.0, 3.0, 4.0]) - 1.0) < 1e-6\n assert abs(candidate([1.0, 2.0, 3.0, 4.0, 5.0]) - 6.0/5.0) < 1e-6\n\n"}
{"task_id": "HumanEval/5", "prompt": "from typing import List\n\n\ndef intersperse(numbers: List[int], delimeter: int) -> List[int]:\n \"\"\" Insert a number 'delimeter' between every two consecutive elements of input list `numbers'\n >>> intersperse([], 4)\n []\n >>> intersperse([1, 2, 3], 4)\n [1, 4, 2, 4, 3]\n \"\"\"\n", "entry_point": "intersperse", "canonical_solution": " if not numbers:\n return []\n\n result = []\n\n for n in numbers[:-1]:\n result.append(n)\n result.append(delimeter)\n\n result.append(numbers[-1])\n\n return result\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([], 7) == []\n assert candidate([5, 6, 3, 2], 8) == [5, 8, 6, 8, 3, 8, 2]\n assert candidate([2, 2, 2], 2) == [2, 2, 2, 2, 2]\n"}
{"task_id": "HumanEval/6", "prompt": "from typing import List\n\n\ndef parse_nested_parens(paren_string: str) -> List[int]:\n \"\"\" Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n For each of the group, output the deepest level of nesting of parentheses.\n E.g. (()()) has maximum two levels of nesting while ((())) has three.\n\n >>> parse_nested_parens('(()()) ((())) () ((())()())')\n [2, 3, 1, 3]\n \"\"\"\n", "entry_point": "parse_nested_parens", "canonical_solution": " def parse_paren_group(s):\n depth = 0\n max_depth = 0\n for c in s:\n if c == '(':\n depth += 1\n max_depth = max(depth, max_depth)\n else:\n depth -= 1\n\n return max_depth\n\n return [parse_paren_group(x) for x in paren_string.split(' ') if x]\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('(()()) ((())) () ((())()())') == [2, 3, 1, 3]\n assert candidate('() (()) ((())) (((())))') == [1, 2, 3, 4]\n assert candidate('(()(())((())))') == [4]\n"}
{"task_id": "HumanEval/7", "prompt": "from typing import List\n\n\ndef filter_by_substring(strings: List[str], substring: str) -> List[str]:\n \"\"\" Filter an input list of strings only for ones that contain given substring\n >>> filter_by_substring([], 'a')\n []\n >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a')\n ['abc', 'bacd', 'array']\n \"\"\"\n", "entry_point": "filter_by_substring", "canonical_solution": " return [x for x in strings if substring in x]\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([], 'john') == []\n assert candidate(['xxx', 'asd', 'xxy', 'john doe', 'xxxAAA', 'xxx'], 'xxx') == ['xxx', 'xxxAAA', 'xxx']\n assert candidate(['xxx', 'asd', 'aaaxxy', 'john doe', 'xxxAAA', 'xxx'], 'xx') == ['xxx', 'aaaxxy', 'xxxAAA', 'xxx']\n assert candidate(['grunt', 'trumpet', 'prune', 'gruesome'], 'run') == ['grunt', 'prune']\n"}
{"task_id": "HumanEval/8", "prompt": "from typing import List, Tuple\n\n\ndef sum_product(numbers: List[int]) -> Tuple[int, int]:\n \"\"\" For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.\n Empty sum should be equal to 0 and empty product should be equal to 1.\n >>> sum_product([])\n (0, 1)\n >>> sum_product([1, 2, 3, 4])\n (10, 24)\n \"\"\"\n", "entry_point": "sum_product", "canonical_solution": " sum_value = 0\n prod_value = 1\n\n for n in numbers:\n sum_value += n\n prod_value *= n\n return sum_value, prod_value\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([]) == (0, 1)\n assert candidate([1, 1, 1]) == (3, 1)\n assert candidate([100, 0]) == (100, 0)\n assert candidate([3, 5, 7]) == (3 + 5 + 7, 3 * 5 * 7)\n assert candidate([10]) == (10, 10)\n"}
{"task_id": "HumanEval/9", "prompt": "from typing import List, Tuple\n\n\ndef rolling_max(numbers: List[int]) -> List[int]:\n \"\"\" From a given list of integers, generate a list of rolling maximum element found until given moment\n in the sequence.\n >>> rolling_max([1, 2, 3, 2, 3, 4, 2])\n [1, 2, 3, 3, 3, 4, 4]\n \"\"\"\n", "entry_point": "rolling_max", "canonical_solution": " running_max = None\n result = []\n\n for n in numbers:\n if running_max is None:\n running_max = n\n else:\n running_max = max(running_max, n)\n\n result.append(running_max)\n\n return result\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([]) == []\n assert candidate([1, 2, 3, 4]) == [1, 2, 3, 4]\n assert candidate([4, 3, 2, 1]) == [4, 4, 4, 4]\n assert candidate([3, 2, 3, 100, 3]) == [3, 3, 3, 100, 100]\n"}
{"task_id": "HumanEval/10", "prompt": "\n\ndef is_palindrome(string: str) -> bool:\n \"\"\" Test if given string is a palindrome \"\"\"\n return string == string[::-1]\n\n\ndef make_palindrome(string: str) -> str:\n \"\"\" Find the shortest palindrome that begins with a supplied string.\n Algorithm idea is simple:\n - Find the longest postfix of supplied string that is a palindrome.\n - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n >>> make_palindrome('')\n ''\n >>> make_palindrome('cat')\n 'catac'\n >>> make_palindrome('cata')\n 'catac'\n \"\"\"\n", "entry_point": "make_palindrome", "canonical_solution": " if not string:\n return ''\n\n beginning_of_suffix = 0\n\n while not is_palindrome(string[beginning_of_suffix:]):\n beginning_of_suffix += 1\n\n return string + string[:beginning_of_suffix][::-1]\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('') == ''\n assert candidate('x') == 'x'\n assert candidate('xyz') == 'xyzyx'\n assert candidate('xyx') == 'xyx'\n assert candidate('jerry') == 'jerryrrej'\n"}
{"task_id": "HumanEval/11", "prompt": "from typing import List\n\n\ndef string_xor(a: str, b: str) -> str:\n \"\"\" Input are two strings a and b consisting only of 1s and 0s.\n Perform binary XOR on these inputs and return result also as a string.\n >>> string_xor('010', '110')\n '100'\n \"\"\"\n", "entry_point": "string_xor", "canonical_solution": " def xor(i, j):\n if i == j:\n return '0'\n else:\n return '1'\n\n return ''.join(xor(x, y) for x, y in zip(a, b))\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('111000', '101010') == '010010'\n assert candidate('1', '1') == '0'\n assert candidate('0101', '0000') == '0101'\n"}
{"task_id": "HumanEval/12", "prompt": "from typing import List, Optional\n\n\ndef longest(strings: List[str]) -> Optional[str]:\n \"\"\" Out of list of strings, return the longest one. Return the first one in case of multiple\n strings of the same length. Return None in case the input list is empty.\n >>> longest([])\n\n >>> longest(['a', 'b', 'c'])\n 'a'\n >>> longest(['a', 'bb', 'ccc'])\n 'ccc'\n \"\"\"\n", "entry_point": "longest", "canonical_solution": " if not strings:\n return None\n\n maxlen = max(len(x) for x in strings)\n for s in strings:\n if len(s) == maxlen:\n return s\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([]) == None\n assert candidate(['x', 'y', 'z']) == 'x'\n assert candidate(['x', 'yyy', 'zzzz', 'www', 'kkkk', 'abc']) == 'zzzz'\n"}
{"task_id": "HumanEval/13", "prompt": "\n\ndef greatest_common_divisor(a: int, b: int) -> int:\n \"\"\" Return a greatest common divisor of two integers a and b\n >>> greatest_common_divisor(3, 5)\n 1\n >>> greatest_common_divisor(25, 15)\n 5\n \"\"\"\n", "entry_point": "greatest_common_divisor", "canonical_solution": " while b:\n a, b = b, a % b\n return a\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(3, 7) == 1\n assert candidate(10, 15) == 5\n assert candidate(49, 14) == 7\n assert candidate(144, 60) == 12\n"}
{"task_id": "HumanEval/14", "prompt": "from typing import List\n\n\ndef all_prefixes(string: str) -> List[str]:\n \"\"\" Return list of all prefixes from shortest to longest of the input string\n >>> all_prefixes('abc')\n ['a', 'ab', 'abc']\n \"\"\"\n", "entry_point": "all_prefixes", "canonical_solution": " result = []\n\n for i in range(len(string)):\n result.append(string[:i+1])\n return result\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('') == []\n assert candidate('asdfgh') == ['a', 'as', 'asd', 'asdf', 'asdfg', 'asdfgh']\n assert candidate('WWW') == ['W', 'WW', 'WWW']\n"}
{"task_id": "HumanEval/15", "prompt": "\n\ndef string_sequence(n: int) -> str:\n \"\"\" Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n >>> string_sequence(0)\n '0'\n >>> string_sequence(5)\n '0 1 2 3 4 5'\n \"\"\"\n", "entry_point": "string_sequence", "canonical_solution": " return ' '.join([str(x) for x in range(n + 1)])\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(0) == '0'\n assert candidate(3) == '0 1 2 3'\n assert candidate(10) == '0 1 2 3 4 5 6 7 8 9 10'\n"}
{"task_id": "HumanEval/16", "prompt": "\n\ndef count_distinct_characters(string: str) -> int:\n \"\"\" Given a string, find out how many distinct characters (regardless of case) does it consist of\n >>> count_distinct_characters('xyzXYZ')\n 3\n >>> count_distinct_characters('Jerry')\n 4\n \"\"\"\n", "entry_point": "count_distinct_characters", "canonical_solution": " return len(set(string.lower()))\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('') == 0\n assert candidate('abcde') == 5\n assert candidate('abcde' + 'cade' + 'CADE') == 5\n assert candidate('aaaaAAAAaaaa') == 1\n assert candidate('Jerry jERRY JeRRRY') == 5\n"}
{"task_id": "HumanEval/17", "prompt": "from typing import List\n\n\ndef parse_music(music_string: str) -> List[int]:\n \"\"\" Input to this function is a string representing musical notes in a special ASCII format.\n Your task is to parse this string and return list of integers corresponding to how many beats does each\n not last.\n\n Here is a legend:\n 'o' - whole note, lasts four beats\n 'o|' - half note, lasts two beats\n '.|' - quater note, lasts one beat\n\n >>> parse_music('o o| .| o| o| .| .| .| .| o o')\n [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]\n \"\"\"\n", "entry_point": "parse_music", "canonical_solution": " note_map = {'o': 4, 'o|': 2, '.|': 1}\n return [note_map[x] for x in music_string.split(' ') if x]\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('') == []\n assert candidate('o o o o') == [4, 4, 4, 4]\n assert candidate('.| .| .| .|') == [1, 1, 1, 1]\n assert candidate('o| o| .| .| o o o o') == [2, 2, 1, 1, 4, 4, 4, 4]\n assert candidate('o| .| o| .| o o| o o|') == [2, 1, 2, 1, 4, 2, 4, 2]\n"}
{"task_id": "HumanEval/18", "prompt": "\n\ndef how_many_times(string: str, substring: str) -> int:\n \"\"\" Find how many times a given substring can be found in the original string. Count overlaping cases.\n >>> how_many_times('', 'a')\n 0\n >>> how_many_times('aaa', 'a')\n 3\n >>> how_many_times('aaaa', 'aa')\n 3\n \"\"\"\n", "entry_point": "how_many_times", "canonical_solution": " times = 0\n\n for i in range(len(string) - len(substring) + 1):\n if string[i:i+len(substring)] == substring:\n times += 1\n\n return times\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('', 'x') == 0\n assert candidate('xyxyxyx', 'x') == 4\n assert candidate('cacacacac', 'cac') == 4\n assert candidate('john doe', 'john') == 1\n"}
{"task_id": "HumanEval/19", "prompt": "from typing import List\n\n\ndef sort_numbers(numbers: str) -> str:\n \"\"\" Input is a space-delimited string of numberals from 'zero' to 'nine'.\n Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n Return the string with numbers sorted from smallest to largest\n >>> sort_numbers('three one five')\n 'one three five'\n \"\"\"\n", "entry_point": "sort_numbers", "canonical_solution": " value_map = {\n 'zero': 0,\n 'one': 1,\n 'two': 2,\n 'three': 3,\n 'four': 4,\n 'five': 5,\n 'six': 6,\n 'seven': 7,\n 'eight': 8,\n 'nine': 9\n }\n return ' '.join(sorted([x for x in numbers.split(' ') if x], key=lambda x: value_map[x]))\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('') == ''\n assert candidate('three') == 'three'\n assert candidate('three five nine') == 'three five nine'\n assert candidate('five zero four seven nine eight') == 'zero four five seven eight nine'\n assert candidate('six five four three two one zero') == 'zero one two three four five six'\n"}
{"task_id": "HumanEval/20", "prompt": "from typing import List, Tuple\n\n\ndef find_closest_elements(numbers: List[float]) -> Tuple[float, float]:\n \"\"\" From a supplied list of numbers (of length at least two) select and return two that are the closest to each\n other and return them in order (smaller number, larger number).\n >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])\n (2.0, 2.2)\n >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])\n (2.0, 2.0)\n \"\"\"\n", "entry_point": "find_closest_elements", "canonical_solution": " closest_pair = None\n distance = None\n\n for idx, elem in enumerate(numbers):\n for idx2, elem2 in enumerate(numbers):\n if idx != idx2:\n if distance is None:\n distance = abs(elem - elem2)\n closest_pair = tuple(sorted([elem, elem2]))\n else:\n new_distance = abs(elem - elem2)\n if new_distance < distance:\n distance = new_distance\n closest_pair = tuple(sorted([elem, elem2]))\n\n return closest_pair\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]) == (3.9, 4.0)\n assert candidate([1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9)\n assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)\n assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)\n assert candidate([1.1, 2.2, 3.1, 4.1, 5.1]) == (2.2, 3.1)\n\n"}
{"task_id": "HumanEval/21", "prompt": "from typing import List\n\n\ndef rescale_to_unit(numbers: List[float]) -> List[float]:\n \"\"\" Given list of numbers (of at least two elements), apply a linear transform to that list,\n such that the smallest number will become 0 and the largest will become 1\n >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])\n [0.0, 0.25, 0.5, 0.75, 1.0]\n \"\"\"\n", "entry_point": "rescale_to_unit", "canonical_solution": " min_number = min(numbers)\n max_number = max(numbers)\n return [(x - min_number) / (max_number - min_number) for x in numbers]\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([2.0, 49.9]) == [0.0, 1.0]\n assert candidate([100.0, 49.9]) == [1.0, 0.0]\n assert candidate([1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]\n assert candidate([2.0, 1.0, 5.0, 3.0, 4.0]) == [0.25, 0.0, 1.0, 0.5, 0.75]\n assert candidate([12.0, 11.0, 15.0, 13.0, 14.0]) == [0.25, 0.0, 1.0, 0.5, 0.75]\n"}
{"task_id": "HumanEval/22", "prompt": "from typing import List, Any\n\n\ndef filter_integers(values: List[Any]) -> List[int]:\n \"\"\" Filter given list of any python values only for integers\n >>> filter_integers(['a', 3.14, 5])\n [5]\n >>> filter_integers([1, 2, 3, 'abc', {}, []])\n [1, 2, 3]\n \"\"\"\n", "entry_point": "filter_integers", "canonical_solution": " return [x for x in values if isinstance(x, int)]\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([]) == []\n assert candidate([4, {}, [], 23.2, 9, 'adasd']) == [4, 9]\n assert candidate([3, 'c', 3, 3, 'a', 'b']) == [3, 3, 3]\n"}
{"task_id": "HumanEval/23", "prompt": "\n\ndef strlen(string: str) -> int:\n \"\"\" Return length of given string\n >>> strlen('')\n 0\n >>> strlen('abc')\n 3\n \"\"\"\n", "entry_point": "strlen", "canonical_solution": " return len(string)\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('') == 0\n assert candidate('x') == 1\n assert candidate('asdasnakj') == 9\n"}
{"task_id": "HumanEval/24", "prompt": "\n\ndef largest_divisor(n: int) -> int:\n \"\"\" For a given number n, find the largest number that divides n evenly, smaller than n\n >>> largest_divisor(15)\n 5\n \"\"\"\n", "entry_point": "largest_divisor", "canonical_solution": " for i in reversed(range(n)):\n if n % i == 0:\n return i\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(3) == 1\n assert candidate(7) == 1\n assert candidate(10) == 5\n assert candidate(100) == 50\n assert candidate(49) == 7\n"}
{"task_id": "HumanEval/25", "prompt": "from typing import List\n\n\ndef factorize(n: int) -> List[int]:\n \"\"\" Return list of prime factors of given integer in the order from smallest to largest.\n Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.\n Input number should be equal to the product of all factors\n >>> factorize(8)\n [2, 2, 2]\n >>> factorize(25)\n [5, 5]\n >>> factorize(70)\n [2, 5, 7]\n \"\"\"\n", "entry_point": "factorize", "canonical_solution": " import math\n fact = []\n i = 2\n while i <= int(math.sqrt(n) + 1):\n if n % i == 0:\n fact.append(i)\n n //= i\n else:\n i += 1\n\n if n > 1:\n fact.append(n)\n return fact\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(2) == [2]\n assert candidate(4) == [2, 2]\n assert candidate(8) == [2, 2, 2]\n assert candidate(3 * 19) == [3, 19]\n assert candidate(3 * 19 * 3 * 19) == [3, 3, 19, 19]\n assert candidate(3 * 19 * 3 * 19 * 3 * 19) == [3, 3, 3, 19, 19, 19]\n assert candidate(3 * 19 * 19 * 19) == [3, 19, 19, 19]\n assert candidate(3 * 2 * 3) == [2, 3, 3]\n"}
{"task_id": "HumanEval/26", "prompt": "from typing import List\n\n\ndef remove_duplicates(numbers: List[int]) -> List[int]:\n \"\"\" From a list of integers, remove all elements that occur more than once.\n Keep order of elements left the same as in the input.\n >>> remove_duplicates([1, 2, 3, 2, 4])\n [1, 3, 4]\n \"\"\"\n", "entry_point": "remove_duplicates", "canonical_solution": " import collections\n c = collections.Counter(numbers)\n return [n for n in numbers if c[n] <= 1]\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([]) == []\n assert candidate([1, 2, 3, 4]) == [1, 2, 3, 4]\n assert candidate([1, 2, 3, 2, 4, 3, 5]) == [1, 4, 5]\n"}
{"task_id": "HumanEval/27", "prompt": "\n\ndef flip_case(string: str) -> str:\n \"\"\" For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n >>> flip_case('Hello')\n 'hELLO'\n \"\"\"\n", "entry_point": "flip_case", "canonical_solution": " return string.swapcase()\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate('') == ''\n assert candidate('Hello!') == 'hELLO!'\n assert candidate('These violent delights have violent ends') == 'tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS'\n"}
{"task_id": "HumanEval/28", "prompt": "from typing import List\n\n\ndef concatenate(strings: List[str]) -> str:\n \"\"\" Concatenate list of strings into a single string\n >>> concatenate([])\n ''\n >>> concatenate(['a', 'b', 'c'])\n 'abc'\n \"\"\"\n", "entry_point": "concatenate", "canonical_solution": " return ''.join(strings)\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([]) == ''\n assert candidate(['x', 'y', 'z']) == 'xyz'\n assert candidate(['x', 'y', 'z', 'w', 'k']) == 'xyzwk'\n"}
{"task_id": "HumanEval/29", "prompt": "from typing import List\n\n\ndef filter_by_prefix(strings: List[str], prefix: str) -> List[str]:\n \"\"\" Filter an input list of strings only for ones that start with a given prefix.\n >>> filter_by_prefix([], 'a')\n []\n >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a')\n ['abc', 'array']\n \"\"\"\n", "entry_point": "filter_by_prefix", "canonical_solution": " return [x for x in strings if x.startswith(prefix)]\n", "test": "\n\nMETADATA = {\n 'author': 'jt',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([], 'john') == []\n assert candidate(['xxx', 'asd', 'xxy', 'john doe', 'xxxAAA', 'xxx'], 'xxx') == ['xxx', 'xxxAAA', 'xxx']\n"}
{"task_id": "HumanEval/30", "prompt": "\n\ndef get_positive(l: list):\n \"\"\"Return only positive numbers in the list.\n >>> get_positive([-1, 2, -4, 5, 6])\n [2, 5, 6]\n >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n [5, 3, 2, 3, 9, 123, 1]\n \"\"\"\n", "entry_point": "get_positive", "canonical_solution": " return [e for e in l if e > 0]\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([-1, -2, 4, 5, 6]) == [4, 5, 6]\n assert candidate([5, 3, -5, 2, 3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 3, 9, 123, 1]\n assert candidate([-1, -2]) == []\n assert candidate([]) == []\n\n"}
{"task_id": "HumanEval/31", "prompt": "\n\ndef is_prime(n):\n \"\"\"Return true if a given number is prime, and false otherwise.\n >>> is_prime(6)\n False\n >>> is_prime(101)\n True\n >>> is_prime(11)\n True\n >>> is_prime(13441)\n True\n >>> is_prime(61)\n True\n >>> is_prime(4)\n False\n >>> is_prime(1)\n False\n \"\"\"\n", "entry_point": "is_prime", "canonical_solution": " if n < 2:\n return False\n for k in range(2, n - 1):\n if n % k == 0:\n return False\n return True\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(6) == False\n assert candidate(101) == True\n assert candidate(11) == True\n assert candidate(13441) == True\n assert candidate(61) == True\n assert candidate(4) == False\n assert candidate(1) == False\n assert candidate(5) == True\n assert candidate(11) == True\n assert candidate(17) == True\n assert candidate(5 * 17) == False\n assert candidate(11 * 7) == False\n assert candidate(13441 * 19) == False\n\n"}
{"task_id": "HumanEval/32", "prompt": "import math\n\n\ndef poly(xs: list, x: float):\n \"\"\"\n Evaluates polynomial with coefficients xs at point x.\n return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n\n \"\"\"\n return sum([coeff * math.pow(x, i) for i, coeff in enumerate(xs)])\n\n\ndef find_zero(xs: list):\n \"\"\" xs are coefficients of a polynomial.\n find_zero find x such that poly(x) = 0.\n find_zero returns only only zero point, even if there are many.\n Moreover, find_zero only takes list xs having even number of coefficients\n and largest non zero coefficient as it guarantees\n a solution.\n >>> round(find_zero([1, 2]), 2) # f(x) = 1 + 2x\n -0.5\n >>> round(find_zero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3\n 1.0\n \"\"\"\n", "entry_point": "find_zero", "canonical_solution": " begin, end = -1., 1.\n while poly(xs, begin) * poly(xs, end) > 0:\n begin *= 2.0\n end *= 2.0\n while end - begin > 1e-10:\n center = (begin + end) / 2.0\n if poly(xs, center) * poly(xs, begin) > 0:\n begin = center\n else:\n end = center\n return begin\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n import math\n import random\n rng = random.Random(42)\n import copy\n for _ in range(100):\n ncoeff = 2 * rng.randint(1, 4)\n coeffs = []\n for _ in range(ncoeff):\n coeff = rng.randint(-10, 10)\n if coeff == 0:\n coeff = 1\n coeffs.append(coeff)\n solution = candidate(copy.deepcopy(coeffs))\n assert math.fabs(poly(coeffs, solution)) < 1e-4\n\n"}
{"task_id": "HumanEval/33", "prompt": "\n\ndef sort_third(l: list):\n \"\"\"This function takes a list l and returns a list l' such that\n l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal\n to the values of the corresponding indicies of l, but sorted.\n >>> sort_third([1, 2, 3])\n [1, 2, 3]\n >>> sort_third([5, 6, 3, 4, 8, 9, 2])\n [2, 6, 3, 4, 8, 9, 5]\n \"\"\"\n", "entry_point": "sort_third", "canonical_solution": " l = list(l)\n l[::3] = sorted(l[::3])\n return l\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert tuple(candidate([1, 2, 3])) == tuple(sort_third([1, 2, 3]))\n assert tuple(candidate([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])) == tuple(sort_third([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]))\n assert tuple(candidate([5, 8, -12, 4, 23, 2, 3, 11, 12, -10])) == tuple(sort_third([5, 8, -12, 4, 23, 2, 3, 11, 12, -10]))\n assert tuple(candidate([5, 6, 3, 4, 8, 9, 2])) == tuple([2, 6, 3, 4, 8, 9, 5])\n assert tuple(candidate([5, 8, 3, 4, 6, 9, 2])) == tuple([2, 8, 3, 4, 6, 9, 5])\n assert tuple(candidate([5, 6, 9, 4, 8, 3, 2])) == tuple([2, 6, 9, 4, 8, 3, 5])\n assert tuple(candidate([5, 6, 3, 4, 8, 9, 2, 1])) == tuple([2, 6, 3, 4, 8, 9, 5, 1])\n\n"}
{"task_id": "HumanEval/34", "prompt": "\n\ndef unique(l: list):\n \"\"\"Return sorted unique elements in a list\n >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])\n [0, 2, 3, 5, 9, 123]\n \"\"\"\n", "entry_point": "unique", "canonical_solution": " return sorted(list(set(l)))\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]\n\n"}
{"task_id": "HumanEval/35", "prompt": "\n\ndef max_element(l: list):\n \"\"\"Return maximum element in the list.\n >>> max_element([1, 2, 3])\n 3\n >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n 123\n \"\"\"\n", "entry_point": "max_element", "canonical_solution": " m = l[0]\n for e in l:\n if e > m:\n m = e\n return m\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([1, 2, 3]) == 3\n assert candidate([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) == 124\n"}
{"task_id": "HumanEval/36", "prompt": "\n\ndef fizz_buzz(n: int):\n \"\"\"Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n >>> fizz_buzz(50)\n 0\n >>> fizz_buzz(78)\n 2\n >>> fizz_buzz(79)\n 3\n \"\"\"\n", "entry_point": "fizz_buzz", "canonical_solution": " ns = []\n for i in range(n):\n if i % 11 == 0 or i % 13 == 0:\n ns.append(i)\n s = ''.join(list(map(str, ns)))\n ans = 0\n for c in s:\n ans += (c == '7')\n return ans\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(50) == 0\n assert candidate(78) == 2\n assert candidate(79) == 3\n assert candidate(100) == 3\n assert candidate(200) == 6\n assert candidate(4000) == 192\n assert candidate(10000) == 639\n assert candidate(100000) == 8026\n\n"}
{"task_id": "HumanEval/37", "prompt": "\n\ndef sort_even(l: list):\n \"\"\"This function takes a list l and returns a list l' such that\n l' is identical to l in the odd indicies, while its values at the even indicies are equal\n to the values of the even indicies of l, but sorted.\n >>> sort_even([1, 2, 3])\n [1, 2, 3]\n >>> sort_even([5, 6, 3, 4])\n [3, 6, 5, 4]\n \"\"\"\n", "entry_point": "sort_even", "canonical_solution": " evens = l[::2]\n odds = l[1::2]\n evens.sort()\n ans = []\n for e, o in zip(evens, odds):\n ans.extend([e, o])\n if len(evens) > len(odds):\n ans.append(evens[-1])\n return ans\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert tuple(candidate([1, 2, 3])) == tuple([1, 2, 3])\n assert tuple(candidate([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])) == tuple([-10, 3, -5, 2, -3, 3, 5, 0, 9, 1, 123])\n assert tuple(candidate([5, 8, -12, 4, 23, 2, 3, 11, 12, -10])) == tuple([-12, 8, 3, 4, 5, 2, 12, 11, 23, -10])\n\n"}
{"task_id": "HumanEval/38", "prompt": "\n\ndef encode_cyclic(s: str):\n \"\"\"\n returns encoded string by cycling groups of three characters.\n \"\"\"\n # split string to groups. Each of length 3.\n groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]\n # cycle elements in each group. Unless group has fewer elements than 3.\n groups = [(group[1:] + group[0]) if len(group) == 3 else group for group in groups]\n return \"\".join(groups)\n\n\ndef decode_cyclic(s: str):\n \"\"\"\n takes as input string encoded with encode_cyclic function. Returns decoded string.\n \"\"\"\n", "entry_point": "decode_cyclic", "canonical_solution": " return encode_cyclic(encode_cyclic(s))\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n from random import randint, choice\n import string\n\n letters = string.ascii_lowercase\n for _ in range(100):\n str = ''.join(choice(letters) for i in range(randint(10, 20)))\n encoded_str = encode_cyclic(str)\n assert candidate(encoded_str) == str\n\n"}
{"task_id": "HumanEval/39", "prompt": "\n\ndef prime_fib(n: int):\n \"\"\"\n prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n >>> prime_fib(1)\n 2\n >>> prime_fib(2)\n 3\n >>> prime_fib(3)\n 5\n >>> prime_fib(4)\n 13\n >>> prime_fib(5)\n 89\n \"\"\"\n", "entry_point": "prime_fib", "canonical_solution": " import math\n\n def is_prime(p):\n if p < 2:\n return False\n for k in range(2, min(int(math.sqrt(p)) + 1, p - 1)):\n if p % k == 0:\n return False\n return True\n f = [0, 1]\n while True:\n f.append(f[-1] + f[-2])\n if is_prime(f[-1]):\n n -= 1\n if n == 0:\n return f[-1]\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(1) == 2\n assert candidate(2) == 3\n assert candidate(3) == 5\n assert candidate(4) == 13\n assert candidate(5) == 89\n assert candidate(6) == 233\n assert candidate(7) == 1597\n assert candidate(8) == 28657\n assert candidate(9) == 514229\n assert candidate(10) == 433494437\n\n"}
{"task_id": "HumanEval/40", "prompt": "\n\ndef triples_sum_to_zero(l: list):\n \"\"\"\n triples_sum_to_zero takes a list of integers as an input.\n it returns True if there are three distinct elements in the list that\n sum to zero, and False otherwise.\n\n >>> triples_sum_to_zero([1, 3, 5, 0])\n False\n >>> triples_sum_to_zero([1, 3, -2, 1])\n True\n >>> triples_sum_to_zero([1, 2, 3, 7])\n False\n >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7])\n True\n >>> triples_sum_to_zero([1])\n False\n \"\"\"\n", "entry_point": "triples_sum_to_zero", "canonical_solution": " for i in range(len(l)):\n for j in range(i + 1, len(l)):\n for k in range(j + 1, len(l)):\n if l[i] + l[j] + l[k] == 0:\n return True\n return False\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([1, 3, 5, 0]) == False\n assert candidate([1, 3, 5, -1]) == False\n assert candidate([1, 3, -2, 1]) == True\n assert candidate([1, 2, 3, 7]) == False\n assert candidate([1, 2, 5, 7]) == False\n assert candidate([2, 4, -5, 3, 9, 7]) == True\n assert candidate([1]) == False\n assert candidate([1, 3, 5, -100]) == False\n assert candidate([100, 3, 5, -100]) == False\n\n"}
{"task_id": "HumanEval/41", "prompt": "\n\ndef car_race_collision(n: int):\n \"\"\"\n Imagine a road that's a perfectly straight infinitely long line.\n n cars are driving left to right; simultaneously, a different set of n cars\n are driving right to left. The two sets of cars start out being very far from\n each other. All cars move in the same speed. Two cars are said to collide\n when a car that's moving left to right hits a car that's moving right to left.\n However, the cars are infinitely sturdy and strong; as a result, they continue moving\n in their trajectory as if they did not collide.\n\n This function outputs the number of such collisions.\n \"\"\"\n", "entry_point": "car_race_collision", "canonical_solution": " return n**2\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(2) == 4\n assert candidate(3) == 9\n assert candidate(4) == 16\n assert candidate(8) == 64\n assert candidate(10) == 100\n\n"}
{"task_id": "HumanEval/42", "prompt": "\n\ndef incr_list(l: list):\n \"\"\"Return list with elements incremented by 1.\n >>> incr_list([1, 2, 3])\n [2, 3, 4]\n >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123])\n [6, 4, 6, 3, 4, 4, 10, 1, 124]\n \"\"\"\n", "entry_point": "incr_list", "canonical_solution": " return [(e + 1) for e in l]\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([]) == []\n assert candidate([3, 2, 1]) == [4, 3, 2]\n assert candidate([5, 2, 5, 2, 3, 3, 9, 0, 123]) == [6, 3, 6, 3, 4, 4, 10, 1, 124]\n\n"}
{"task_id": "HumanEval/43", "prompt": "\n\ndef pairs_sum_to_zero(l):\n \"\"\"\n pairs_sum_to_zero takes a list of integers as an input.\n it returns True if there are two distinct elements in the list that\n sum to zero, and False otherwise.\n >>> pairs_sum_to_zero([1, 3, 5, 0])\n False\n >>> pairs_sum_to_zero([1, 3, -2, 1])\n False\n >>> pairs_sum_to_zero([1, 2, 3, 7])\n False\n >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7])\n True\n >>> pairs_sum_to_zero([1])\n False\n \"\"\"\n", "entry_point": "pairs_sum_to_zero", "canonical_solution": " for i, l1 in enumerate(l):\n for j in range(i + 1, len(l)):\n if l1 + l[j] == 0:\n return True\n return False\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([1, 3, 5, 0]) == False\n assert candidate([1, 3, -2, 1]) == False\n assert candidate([1, 2, 3, 7]) == False\n assert candidate([2, 4, -5, 3, 5, 7]) == True\n assert candidate([1]) == False\n\n assert candidate([-3, 9, -1, 3, 2, 30]) == True\n assert candidate([-3, 9, -1, 3, 2, 31]) == True\n assert candidate([-3, 9, -1, 4, 2, 30]) == False\n assert candidate([-3, 9, -1, 4, 2, 31]) == False\n\n"}
{"task_id": "HumanEval/44", "prompt": "\n\ndef change_base(x: int, base: int):\n \"\"\"Change numerical base of input number x to base.\n return string representation after the conversion.\n base numbers are less than 10.\n >>> change_base(8, 3)\n '22'\n >>> change_base(8, 2)\n '1000'\n >>> change_base(7, 2)\n '111'\n \"\"\"\n", "entry_point": "change_base", "canonical_solution": " ret = \"\"\n while x > 0:\n ret = str(x % base) + ret\n x //= base\n return ret\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(8, 3) == \"22\"\n assert candidate(9, 3) == \"100\"\n assert candidate(234, 2) == \"11101010\"\n assert candidate(16, 2) == \"10000\"\n assert candidate(8, 2) == \"1000\"\n assert candidate(7, 2) == \"111\"\n for x in range(2, 8):\n assert candidate(x, x + 1) == str(x)\n\n"}
{"task_id": "HumanEval/45", "prompt": "\n\ndef triangle_area(a, h):\n \"\"\"Given length of a side and high return area for a triangle.\n >>> triangle_area(5, 3)\n 7.5\n \"\"\"\n", "entry_point": "triangle_area", "canonical_solution": " return a * h / 2.0\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(5, 3) == 7.5\n assert candidate(2, 2) == 2.0\n assert candidate(10, 8) == 40.0\n\n"}
{"task_id": "HumanEval/46", "prompt": "\n\ndef fib4(n: int):\n \"\"\"The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n fib4(0) -> 0\n fib4(1) -> 0\n fib4(2) -> 2\n fib4(3) -> 0\n fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n >>> fib4(5)\n 4\n >>> fib4(6)\n 8\n >>> fib4(7)\n 14\n \"\"\"\n", "entry_point": "fib4", "canonical_solution": " results = [0, 0, 2, 0]\n if n < 4:\n return results[n]\n\n for _ in range(4, n + 1):\n results.append(results[-1] + results[-2] + results[-3] + results[-4])\n results.pop(0)\n\n return results[-1]\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(5) == 4\n assert candidate(8) == 28\n assert candidate(10) == 104\n assert candidate(12) == 386\n\n"}
{"task_id": "HumanEval/47", "prompt": "\n\ndef median(l: list):\n \"\"\"Return median of elements in the list l.\n >>> median([3, 1, 2, 4, 5])\n 3\n >>> median([-10, 4, 6, 1000, 10, 20])\n 15.0\n \"\"\"\n", "entry_point": "median", "canonical_solution": " l = sorted(l)\n if len(l) % 2 == 1:\n return l[len(l) // 2]\n else:\n return (l[len(l) // 2 - 1] + l[len(l) // 2]) / 2.0\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([3, 1, 2, 4, 5]) == 3\n assert candidate([-10, 4, 6, 1000, 10, 20]) == 8.0\n assert candidate([5]) == 5\n assert candidate([6, 5]) == 5.5\n assert candidate([8, 1, 3, 9, 9, 2, 7]) == 7 \n\n"}
{"task_id": "HumanEval/48", "prompt": "\n\ndef is_palindrome(text: str):\n \"\"\"\n Checks if given string is a palindrome\n >>> is_palindrome('')\n True\n >>> is_palindrome('aba')\n True\n >>> is_palindrome('aaaaa')\n True\n >>> is_palindrome('zbcd')\n False\n \"\"\"\n", "entry_point": "is_palindrome", "canonical_solution": " for i in range(len(text)):\n if text[i] != text[len(text) - 1 - i]:\n return False\n return True\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate('') == True\n assert candidate('aba') == True\n assert candidate('aaaaa') == True\n assert candidate('zbcd') == False\n assert candidate('xywyx') == True\n assert candidate('xywyz') == False\n assert candidate('xywzx') == False\n\n"}
{"task_id": "HumanEval/49", "prompt": "\n\ndef modp(n: int, p: int):\n \"\"\"Return 2^n modulo p (be aware of numerics).\n >>> modp(3, 5)\n 3\n >>> modp(1101, 101)\n 2\n >>> modp(0, 101)\n 1\n >>> modp(3, 11)\n 8\n >>> modp(100, 101)\n 1\n \"\"\"\n", "entry_point": "modp", "canonical_solution": " ret = 1\n for i in range(n):\n ret = (2 * ret) % p\n return ret\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(3, 5) == 3\n assert candidate(1101, 101) == 2\n assert candidate(0, 101) == 1\n assert candidate(3, 11) == 8\n assert candidate(100, 101) == 1\n assert candidate(30, 5) == 4\n assert candidate(31, 5) == 3\n\n"}
{"task_id": "HumanEval/50", "prompt": "\n\ndef encode_shift(s: str):\n \"\"\"\n returns encoded string by shifting every character by 5 in the alphabet.\n \"\"\"\n return \"\".join([chr(((ord(ch) + 5 - ord(\"a\")) % 26) + ord(\"a\")) for ch in s])\n\n\ndef decode_shift(s: str):\n \"\"\"\n takes as input string encoded with encode_shift function. Returns decoded string.\n \"\"\"\n", "entry_point": "decode_shift", "canonical_solution": " return \"\".join([chr(((ord(ch) - 5 - ord(\"a\")) % 26) + ord(\"a\")) for ch in s])\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n from random import randint, choice\n import copy\n import string\n\n letters = string.ascii_lowercase\n for _ in range(100):\n str = ''.join(choice(letters) for i in range(randint(10, 20)))\n encoded_str = encode_shift(str)\n assert candidate(copy.deepcopy(encoded_str)) == str\n\n"}
{"task_id": "HumanEval/51", "prompt": "\n\ndef remove_vowels(text):\n \"\"\"\n remove_vowels is a function that takes string and returns string without vowels.\n >>> remove_vowels('')\n ''\n >>> remove_vowels(\"abcdef\\nghijklm\")\n 'bcdf\\nghjklm'\n >>> remove_vowels('abcdef')\n 'bcdf'\n >>> remove_vowels('aaaaa')\n ''\n >>> remove_vowels('aaBAA')\n 'B'\n >>> remove_vowels('zbcd')\n 'zbcd'\n \"\"\"\n", "entry_point": "remove_vowels", "canonical_solution": " return \"\".join([s for s in text if s.lower() not in [\"a\", \"e\", \"i\", \"o\", \"u\"]])\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate('') == ''\n assert candidate(\"abcdef\\nghijklm\") == 'bcdf\\nghjklm'\n assert candidate('fedcba') == 'fdcb'\n assert candidate('eeeee') == ''\n assert candidate('acBAA') == 'cB'\n assert candidate('EcBOO') == 'cB'\n assert candidate('ybcd') == 'ybcd'\n\n"}
{"task_id": "HumanEval/52", "prompt": "\n\ndef below_threshold(l: list, t: int):\n \"\"\"Return True if all numbers in the list l are below threshold t.\n >>> below_threshold([1, 2, 4, 10], 100)\n True\n >>> below_threshold([1, 20, 4, 10], 5)\n False\n \"\"\"\n", "entry_point": "below_threshold", "canonical_solution": " for e in l:\n if e >= t:\n return False\n return True\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([1, 2, 4, 10], 100)\n assert not candidate([1, 20, 4, 10], 5)\n assert candidate([1, 20, 4, 10], 21)\n assert candidate([1, 20, 4, 10], 22)\n assert candidate([1, 8, 4, 10], 11)\n assert not candidate([1, 8, 4, 10], 10)\n\n"}
{"task_id": "HumanEval/53", "prompt": "\n\ndef add(x: int, y: int):\n \"\"\"Add two numbers x and y\n >>> add(2, 3)\n 5\n >>> add(5, 7)\n 12\n \"\"\"\n", "entry_point": "add", "canonical_solution": " return x + y\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n import random\n\n assert candidate(0, 1) == 1\n assert candidate(1, 0) == 1\n assert candidate(2, 3) == 5\n assert candidate(5, 7) == 12\n assert candidate(7, 5) == 12\n\n for i in range(100):\n x, y = random.randint(0, 1000), random.randint(0, 1000)\n assert candidate(x, y) == x + y\n\n"}
{"task_id": "HumanEval/54", "prompt": "\n\ndef same_chars(s0: str, s1: str):\n \"\"\"\n Check if two words have the same characters.\n >>> same_chars('eabcdzzzz', 'dddzzzzzzzddeddabc')\n True\n >>> same_chars('abcd', 'dddddddabc')\n True\n >>> same_chars('dddddddabc', 'abcd')\n True\n >>> same_chars('eabcd', 'dddddddabc')\n False\n >>> same_chars('abcd', 'dddddddabce')\n False\n >>> same_chars('eabcdzzzz', 'dddzzzzzzzddddabc')\n False\n \"\"\"\n", "entry_point": "same_chars", "canonical_solution": " return set(s0) == set(s1)\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate('eabcdzzzz', 'dddzzzzzzzddeddabc') == True\n assert candidate('abcd', 'dddddddabc') == True\n assert candidate('dddddddabc', 'abcd') == True\n assert candidate('eabcd', 'dddddddabc') == False\n assert candidate('abcd', 'dddddddabcf') == False\n assert candidate('eabcdzzzz', 'dddzzzzzzzddddabc') == False\n assert candidate('aabb', 'aaccc') == False\n\n"}
{"task_id": "HumanEval/55", "prompt": "\n\ndef fib(n: int):\n \"\"\"Return n-th Fibonacci number.\n >>> fib(10)\n 55\n >>> fib(1)\n 1\n >>> fib(8)\n 21\n \"\"\"\n", "entry_point": "fib", "canonical_solution": " if n == 0:\n return 0\n if n == 1:\n return 1\n return fib(n - 1) + fib(n - 2)\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(10) == 55\n assert candidate(1) == 1\n assert candidate(8) == 21\n assert candidate(11) == 89\n assert candidate(12) == 144\n\n"}
{"task_id": "HumanEval/56", "prompt": "\n\ndef correct_bracketing(brackets: str):\n \"\"\" brackets is a string of \"<\" and \">\".\n return True if every opening bracket has a corresponding closing bracket.\n\n >>> correct_bracketing(\"<\")\n False\n >>> correct_bracketing(\"<>\")\n True\n >>> correct_bracketing(\"<<><>>\")\n True\n >>> correct_bracketing(\"><<>\")\n False\n \"\"\"\n", "entry_point": "correct_bracketing", "canonical_solution": " depth = 0\n for b in brackets:\n if b == \"<\":\n depth += 1\n else:\n depth -= 1\n if depth < 0:\n return False\n return depth == 0\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(\"<>\")\n assert candidate(\"<<><>>\")\n assert candidate(\"<><><<><>><>\")\n assert candidate(\"<><><<<><><>><>><<><><<>>>\")\n assert not candidate(\"<<<><>>>>\")\n assert not candidate(\"><<>\")\n assert not candidate(\"<\")\n assert not candidate(\"<<<<\")\n assert not candidate(\">\")\n assert not candidate(\"<<>\")\n assert not candidate(\"<><><<><>><>><<>\")\n assert not candidate(\"<><><<><>><>>><>\")\n\n"}
{"task_id": "HumanEval/57", "prompt": "\n\ndef monotonic(l: list):\n \"\"\"Return True is list elements are monotonically increasing or decreasing.\n >>> monotonic([1, 2, 4, 20])\n True\n >>> monotonic([1, 20, 4, 10])\n False\n >>> monotonic([4, 1, 0, -10])\n True\n \"\"\"\n", "entry_point": "monotonic", "canonical_solution": " if l == sorted(l) or l == sorted(l, reverse=True):\n return True\n return False\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([1, 2, 4, 10]) == True\n assert candidate([1, 2, 4, 20]) == True\n assert candidate([1, 20, 4, 10]) == False\n assert candidate([4, 1, 0, -10]) == True\n assert candidate([4, 1, 1, 0]) == True\n assert candidate([1, 2, 3, 2, 5, 60]) == False\n assert candidate([1, 2, 3, 4, 5, 60]) == True\n assert candidate([9, 9, 9, 9]) == True\n\n"}
{"task_id": "HumanEval/58", "prompt": "\n\ndef common(l1: list, l2: list):\n \"\"\"Return sorted unique common elements for two lists.\n >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121])\n [1, 5, 653]\n >>> common([5, 3, 2, 8], [3, 2])\n [2, 3]\n\n \"\"\"\n", "entry_point": "common", "canonical_solution": " ret = set()\n for e1 in l1:\n for e2 in l2:\n if e1 == e2:\n ret.add(e1)\n return sorted(list(ret))\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]\n assert candidate([5, 3, 2, 8], [3, 2]) == [2, 3]\n assert candidate([4, 3, 2, 8], [3, 2, 4]) == [2, 3, 4]\n assert candidate([4, 3, 2, 8], []) == []\n\n"}
{"task_id": "HumanEval/59", "prompt": "\n\ndef largest_prime_factor(n: int):\n \"\"\"Return the largest prime factor of n. Assume n > 1 and is not a prime.\n >>> largest_prime_factor(13195)\n 29\n >>> largest_prime_factor(2048)\n 2\n \"\"\"\n", "entry_point": "largest_prime_factor", "canonical_solution": " def is_prime(k):\n if k < 2:\n return False\n for i in range(2, k - 1):\n if k % i == 0:\n return False\n return True\n largest = 1\n for j in range(2, n + 1):\n if n % j == 0 and is_prime(j):\n largest = max(largest, j)\n return largest\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(15) == 5\n assert candidate(27) == 3\n assert candidate(63) == 7\n assert candidate(330) == 11\n assert candidate(13195) == 29\n\n"}
{"task_id": "HumanEval/60", "prompt": "\n\ndef sum_to_n(n: int):\n \"\"\"sum_to_n is a function that sums numbers from 1 to n.\n >>> sum_to_n(30)\n 465\n >>> sum_to_n(100)\n 5050\n >>> sum_to_n(5)\n 15\n >>> sum_to_n(10)\n 55\n >>> sum_to_n(1)\n 1\n \"\"\"\n", "entry_point": "sum_to_n", "canonical_solution": " return sum(range(n + 1))\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(1) == 1\n assert candidate(6) == 21\n assert candidate(11) == 66\n assert candidate(30) == 465\n assert candidate(100) == 5050\n\n"}
{"task_id": "HumanEval/61", "prompt": "\n\ndef correct_bracketing(brackets: str):\n \"\"\" brackets is a string of \"(\" and \")\".\n return True if every opening bracket has a corresponding closing bracket.\n\n >>> correct_bracketing(\"(\")\n False\n >>> correct_bracketing(\"()\")\n True\n >>> correct_bracketing(\"(()())\")\n True\n >>> correct_bracketing(\")(()\")\n False\n \"\"\"\n", "entry_point": "correct_bracketing", "canonical_solution": " depth = 0\n for b in brackets:\n if b == \"(\":\n depth += 1\n else:\n depth -= 1\n if depth < 0:\n return False\n return depth == 0\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(\"()\")\n assert candidate(\"(()())\")\n assert candidate(\"()()(()())()\")\n assert candidate(\"()()((()()())())(()()(()))\")\n assert not candidate(\"((()())))\")\n assert not candidate(\")(()\")\n assert not candidate(\"(\")\n assert not candidate(\"((((\")\n assert not candidate(\")\")\n assert not candidate(\"(()\")\n assert not candidate(\"()()(()())())(()\")\n assert not candidate(\"()()(()())()))()\")\n\n"}
{"task_id": "HumanEval/62", "prompt": "\n\ndef derivative(xs: list):\n \"\"\" xs represent coefficients of a polynomial.\n xs[0] + xs[1] * x + xs[2] * x^2 + ....\n Return derivative of this polynomial in the same form.\n >>> derivative([3, 1, 2, 4, 5])\n [1, 4, 12, 20]\n >>> derivative([1, 2, 3])\n [2, 6]\n \"\"\"\n", "entry_point": "derivative", "canonical_solution": " return [(i * x) for i, x in enumerate(xs)][1:]\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate([3, 1, 2, 4, 5]) == [1, 4, 12, 20]\n assert candidate([1, 2, 3]) == [2, 6]\n assert candidate([3, 2, 1]) == [2, 2]\n assert candidate([3, 2, 1, 0, 4]) == [2, 2, 0, 16]\n assert candidate([1]) == []\n\n"}
{"task_id": "HumanEval/63", "prompt": "\n\ndef fibfib(n: int):\n \"\"\"The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n fibfib(0) == 0\n fibfib(1) == 0\n fibfib(2) == 1\n fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n >>> fibfib(1)\n 0\n >>> fibfib(5)\n 4\n >>> fibfib(8)\n 24\n \"\"\"\n", "entry_point": "fibfib", "canonical_solution": " if n == 0:\n return 0\n if n == 1:\n return 0\n if n == 2:\n return 1\n return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)\n", "test": "\n\nMETADATA = {}\n\n\ndef check(candidate):\n assert candidate(2) == 1\n assert candidate(1) == 0\n assert candidate(5) == 4\n assert candidate(8) == 24\n assert candidate(10) == 81\n assert candidate(12) == 274\n assert candidate(14) == 927\n\n"}
{"task_id": "HumanEval/64", "prompt": "\nFIX = \"\"\"\nAdd more test cases.\n\"\"\"\n\ndef vowels_count(s):\n \"\"\"Write a function vowels_count which takes a string representing\n a word as input and returns the number of vowels in the string.\n Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n vowel, but only when it is at the end of the given word.\n\n Example:\n >>> vowels_count(\"abcde\")\n 2\n >>> vowels_count(\"ACEDY\")\n 3\n \"\"\"\n", "entry_point": "vowels_count", "canonical_solution": " vowels = \"aeiouAEIOU\"\n n_vowels = sum(c in vowels for c in s)\n if s[-1] == 'y' or s[-1] == 'Y':\n n_vowels += 1\n return n_vowels\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"abcde\") == 2, \"Test 1\"\n assert candidate(\"Alone\") == 3, \"Test 2\"\n assert candidate(\"key\") == 2, \"Test 3\"\n assert candidate(\"bye\") == 1, \"Test 4\"\n assert candidate(\"keY\") == 2, \"Test 5\"\n assert candidate(\"bYe\") == 1, \"Test 6\"\n assert candidate(\"ACEDY\") == 3, \"Test 7\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/65", "prompt": "\ndef circular_shift(x, shift):\n \"\"\"Circular shift the digits of the integer x, shift the digits right by shift\n and return the result as a string.\n If shift > number of digits, return digits reversed.\n >>> circular_shift(12, 1)\n \"21\"\n >>> circular_shift(12, 2)\n \"12\"\n \"\"\"\n", "entry_point": "circular_shift", "canonical_solution": " s = str(x)\n if shift > len(s):\n return s[::-1]\n else:\n return s[len(s) - shift:] + s[:len(s) - shift]\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(100, 2) == \"001\"\n assert candidate(12, 2) == \"12\"\n assert candidate(97, 8) == \"79\"\n assert candidate(12, 1) == \"21\", \"This prints if this assert fails 1 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(11, 101) == \"11\", \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/66", "prompt": "\ndef digitSum(s):\n \"\"\"Task\n Write a function that takes a string as input and returns the sum of the upper characters only'\n ASCII codes.\n\n Examples:\n digitSum(\"\") => 0\n digitSum(\"abAB\") => 131\n digitSum(\"abcCd\") => 67\n digitSum(\"helloE\") => 69\n digitSum(\"woArBld\") => 131\n digitSum(\"aAaaaXa\") => 153\n \"\"\"\n", "entry_point": "digitSum", "canonical_solution": " if s == \"\": return 0\n return sum(ord(char) if char.isupper() else 0 for char in s)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(\"\") == 0, \"Error\"\n assert candidate(\"abAB\") == 131, \"Error\"\n assert candidate(\"abcCd\") == 67, \"Error\"\n assert candidate(\"helloE\") == 69, \"Error\"\n assert candidate(\"woArBld\") == 131, \"Error\"\n assert candidate(\"aAaaaXa\") == 153, \"Error\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate(\" How are yOu?\") == 151, \"Error\"\n assert candidate(\"You arE Very Smart\") == 327, \"Error\"\n\n"}
{"task_id": "HumanEval/67", "prompt": "\ndef fruit_distribution(s,n):\n \"\"\"\n In this task, you will be given a string that represents a number of apples and oranges \n that are distributed in a basket of fruit this basket contains \n apples, oranges, and mango fruits. Given the string that represents the total number of \n the oranges and apples and an integer that represent the total number of the fruits \n in the basket return the number of the mango fruits in the basket.\n for examble:\n fruit_distribution(\"5 apples and 6 oranges\", 19) ->19 - 5 - 6 = 8\n fruit_distribution(\"0 apples and 1 oranges\",3) -> 3 - 0 - 1 = 2\n fruit_distribution(\"2 apples and 3 oranges\", 100) -> 100 - 2 - 3 = 95\n fruit_distribution(\"100 apples and 1 oranges\",120) -> 120 - 100 - 1 = 19\n \"\"\"\n", "entry_point": "fruit_distribution", "canonical_solution": " lis = list()\n for i in s.split(' '):\n if i.isdigit():\n lis.append(int(i))\n return n - sum(lis)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"5 apples and 6 oranges\",19) == 8\n assert candidate(\"5 apples and 6 oranges\",21) == 10\n assert candidate(\"0 apples and 1 oranges\",3) == 2\n assert candidate(\"1 apples and 0 oranges\",3) == 2\n assert candidate(\"2 apples and 3 oranges\",100) == 95\n assert candidate(\"2 apples and 3 oranges\",5) == 0\n assert candidate(\"1 apples and 100 oranges\",120) == 19\n"}
{"task_id": "HumanEval/68", "prompt": "\ndef pluck(arr):\n \"\"\"\n \"Given an array representing a branch of a tree that has non-negative integer nodes\n your task is to pluck one of the nodes and return it.\n The plucked node should be the node with the smallest even value.\n If multiple nodes with the same smallest even value are found return the node that has smallest index.\n\n The plucked node should be returned in a list, [ smalest_value, its index ],\n If there are no even values or the given array is empty, return [].\n\n Example 1:\n Input: [4,2,3]\n Output: [2, 1]\n Explanation: 2 has the smallest even value, and 2 has the smallest index.\n\n Example 2:\n Input: [1,2,3]\n Output: [2, 1]\n Explanation: 2 has the smallest even value, and 2 has the smallest index. \n\n Example 3:\n Input: []\n Output: []\n \n Example 4:\n Input: [5, 0, 3, 0, 4, 2]\n Output: [0, 1]\n Explanation: 0 is the smallest value, but there are two zeros,\n so we will choose the first zero, which has the smallest index.\n\n Constraints:\n * 1 <= nodes.length <= 10000\n * 0 <= node.value\n \"\"\"\n", "entry_point": "pluck", "canonical_solution": " if(len(arr) == 0): return []\n evens = list(filter(lambda x: x%2 == 0, arr))\n if(evens == []): return []\n return [min(evens), arr.index(min(evens))]\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([4,2,3]) == [2, 1], \"Error\"\n assert candidate([1,2,3]) == [2, 1], \"Error\"\n assert candidate([]) == [], \"Error\"\n assert candidate([5, 0, 3, 0, 4, 2]) == [0, 1], \"Error\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate([1, 2, 3, 0, 5, 3]) == [0, 3], \"Error\"\n assert candidate([5, 4, 8, 4 ,8]) == [4, 1], \"Error\"\n assert candidate([7, 6, 7, 1]) == [6, 1], \"Error\"\n assert candidate([7, 9, 7, 1]) == [], \"Error\"\n\n"}
{"task_id": "HumanEval/69", "prompt": "\ndef search(lst):\n '''\n You are given a non-empty list of positive integers. Return the greatest integer that is greater than \n zero, and has a frequency greater than or equal to the value of the integer itself. \n The frequency of an integer is the number of times it appears in the list.\n If no such a value exist, return -1.\n Examples:\n search([4, 1, 2, 2, 3, 1]) == 2\n search([1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3\n search([5, 5, 4, 4, 4]) == -1\n '''\n", "entry_point": "search", "canonical_solution": " frq = [0] * (max(lst) + 1)\n for i in lst:\n frq[i] += 1;\n\n ans = -1\n for i in range(1, len(frq)):\n if frq[i] >= i:\n ans = i\n \n return ans\n", "test": "def check(candidate):\n\n # manually generated tests\n assert candidate([5, 5, 5, 5, 1]) == 1\n assert candidate([4, 1, 4, 1, 4, 4]) == 4\n assert candidate([3, 3]) == -1\n assert candidate([8, 8, 8, 8, 8, 8, 8, 8]) == 8\n assert candidate([2, 3, 3, 2, 2]) == 2\n\n # automatically generated tests\n assert candidate([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1]) == 1\n assert candidate([3, 2, 8, 2]) == 2\n assert candidate([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]) == 1\n assert candidate([8, 8, 3, 6, 5, 6, 4]) == -1\n assert candidate([6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9]) == 1\n assert candidate([1, 9, 10, 1, 3]) == 1\n assert candidate([6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10]) == 5\n assert candidate([1]) == 1\n assert candidate([8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5]) == 4\n assert candidate([2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10]) == 2\n assert candidate([1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]) == 1\n assert candidate([9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4]) == 4\n assert candidate([2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7]) == 4\n assert candidate([9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1]) == 2\n assert candidate([5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8]) == -1\n assert candidate([10]) == -1\n assert candidate([9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]) == 2\n assert candidate([5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]) == 1\n assert candidate([7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6]) == 1\n assert candidate([3, 10, 10, 9, 2]) == -1\n\n"}
{"task_id": "HumanEval/70", "prompt": "\ndef strange_sort_list(lst):\n '''\n Given list of integers, return list in strange order.\n Strange sorting, is when you start with the minimum value,\n then maximum of the remaining integers, then minimum and so on.\n\n Examples:\n strange_sort_list([1, 2, 3, 4]) == [1, 4, 2, 3]\n strange_sort_list([5, 5, 5, 5]) == [5, 5, 5, 5]\n strange_sort_list([]) == []\n '''\n", "entry_point": "strange_sort_list", "canonical_solution": " res, switch = [], True\n while lst:\n res.append(min(lst) if switch else max(lst))\n lst.remove(res[-1])\n switch = not switch\n return res\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([1, 2, 3, 4]) == [1, 4, 2, 3]\n assert candidate([5, 6, 7, 8, 9]) == [5, 9, 6, 8, 7]\n assert candidate([1, 2, 3, 4, 5]) == [1, 5, 2, 4, 3]\n assert candidate([5, 6, 7, 8, 9, 1]) == [1, 9, 5, 8, 6, 7]\n assert candidate([5, 5, 5, 5]) == [5, 5, 5, 5]\n assert candidate([]) == []\n assert candidate([1,2,3,4,5,6,7,8]) == [1, 8, 2, 7, 3, 6, 4, 5]\n assert candidate([0,2,2,2,5,5,-5,-5]) == [-5, 5, -5, 5, 0, 2, 2, 2]\n assert candidate([111111]) == [111111]\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/71", "prompt": "\ndef triangle_area(a, b, c):\n '''\n Given the lengths of the three sides of a triangle. Return the area of\n the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n Otherwise return -1\n Three sides make a valid triangle when the sum of any two sides is greater \n than the third side.\n Example:\n triangle_area(3, 4, 5) == 6.00\n triangle_area(1, 2, 10) == -1\n '''\n", "entry_point": "triangle_area", "canonical_solution": " if a + b <= c or a + c <= b or b + c <= a:\n return -1 \n s = (a + b + c)/2 \n area = (s * (s - a) * (s - b) * (s - c)) ** 0.5\n area = round(area, 2)\n return area\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(3, 4, 5) == 6.00, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(1, 2, 10) == -1\n assert candidate(4, 8, 5) == 8.18\n assert candidate(2, 2, 2) == 1.73\n assert candidate(1, 2, 3) == -1\n assert candidate(10, 5, 7) == 16.25\n assert candidate(2, 6, 3) == -1\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(1, 1, 1) == 0.43, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate(2, 2, 10) == -1\n\n"}
{"task_id": "HumanEval/72", "prompt": "\ndef will_it_fly(q,w):\n '''\n Write a function that returns True if the object q will fly, and False otherwise.\n The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.\n\n Example:\n will_it_fly([1, 2], 5) \u279e False \n # 1+2 is less than the maximum possible weight, but it's unbalanced.\n\n will_it_fly([3, 2, 3], 1) \u279e False\n # it's balanced, but 3+2+3 is more than the maximum possible weight.\n\n will_it_fly([3, 2, 3], 9) \u279e True\n # 3+2+3 is less than the maximum possible weight, and it's balanced.\n\n will_it_fly([3], 5) \u279e True\n # 3 is less than the maximum possible weight, and it's balanced.\n '''\n", "entry_point": "will_it_fly", "canonical_solution": " if sum(q) > w:\n return False\n\n i, j = 0, len(q)-1\n while i<j:\n if q[i] != q[j]:\n return False\n i+=1\n j-=1\n return True\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([3, 2, 3], 9) is True\n assert candidate([1, 2], 5) is False\n assert candidate([3], 5) is True\n assert candidate([3, 2, 3], 1) is False\n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([1, 2, 3], 6) is False\n assert candidate([5], 5) is True\n\n"}
{"task_id": "HumanEval/73", "prompt": "\ndef smallest_change(arr):\n \"\"\"\n Given an array arr of integers, find the minimum number of elements that\n need to be changed to make the array palindromic. A palindromic array is an array that\n is read the same backwards and forwards. In one change, you can change one element to any other element.\n\n For example:\n smallest_change([1,2,3,5,4,7,9,6]) == 4\n smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1\n smallest_change([1, 2, 3, 2, 1]) == 0\n \"\"\"\n", "entry_point": "smallest_change", "canonical_solution": " ans = 0\n for i in range(len(arr) // 2):\n if arr[i] != arr[len(arr) - i - 1]:\n ans += 1\n return ans\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([1,2,3,5,4,7,9,6]) == 4\n assert candidate([1, 2, 3, 4, 3, 2, 2]) == 1\n assert candidate([1, 4, 2]) == 1\n assert candidate([1, 4, 4, 2]) == 1\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([1, 2, 3, 2, 1]) == 0\n assert candidate([3, 1, 1, 3]) == 0\n assert candidate([1]) == 0\n assert candidate([0, 1]) == 1\n\n"}
{"task_id": "HumanEval/74", "prompt": "\ndef total_match(lst1, lst2):\n '''\n Write a function that accepts two lists of strings and returns the list that has \n total number of chars in the all strings of the list less than the other list.\n\n if the two lists have the same number of chars, return the first list.\n\n Examples\n total_match([], []) \u279e []\n total_match(['hi', 'admin'], ['hI', 'Hi']) \u279e ['hI', 'Hi']\n total_match(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) \u279e ['hi', 'admin']\n total_match(['hi', 'admin'], ['hI', 'hi', 'hi']) \u279e ['hI', 'hi', 'hi']\n total_match(['4'], ['1', '2', '3', '4', '5']) \u279e ['4']\n '''\n", "entry_point": "total_match", "canonical_solution": " l1 = 0\n for st in lst1:\n l1 += len(st)\n \n l2 = 0\n for st in lst2:\n l2 += len(st)\n \n if l1 <= l2:\n return lst1\n else:\n return lst2\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([], []) == []\n assert candidate(['hi', 'admin'], ['hi', 'hi']) == ['hi', 'hi']\n assert candidate(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) == ['hi', 'admin']\n assert candidate(['4'], ['1', '2', '3', '4', '5']) == ['4']\n assert candidate(['hi', 'admin'], ['hI', 'Hi']) == ['hI', 'Hi']\n assert candidate(['hi', 'admin'], ['hI', 'hi', 'hi']) == ['hI', 'hi', 'hi']\n assert candidate(['hi', 'admin'], ['hI', 'hi', 'hii']) == ['hi', 'admin']\n\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate([], ['this']) == []\n assert candidate(['this'], []) == []\n\n"}
{"task_id": "HumanEval/75", "prompt": "\ndef is_multiply_prime(a):\n \"\"\"Write a function that returns true if the given number is the multiplication of 3 prime numbers\n and false otherwise.\n Knowing that (a) is less then 100. \n Example:\n is_multiply_prime(30) == True\n 30 = 2 * 3 * 5\n \"\"\"\n", "entry_point": "is_multiply_prime", "canonical_solution": " def is_prime(n):\n for j in range(2,n):\n if n%j == 0:\n return False\n return True\n\n for i in range(2,101):\n if not is_prime(i): continue\n for j in range(2,101):\n if not is_prime(j): continue\n for k in range(2,101):\n if not is_prime(k): continue\n if i*j*k == a: return True\n return False\n", "test": "def check(candidate):\n\n assert candidate(5) == False\n assert candidate(30) == True\n assert candidate(8) == True\n assert candidate(10) == False\n assert candidate(125) == True\n assert candidate(3 * 5 * 7) == True\n assert candidate(3 * 6 * 7) == False\n assert candidate(9 * 9 * 9) == False\n assert candidate(11 * 9 * 9) == False\n assert candidate(11 * 13 * 7) == True\n\n"}
{"task_id": "HumanEval/76", "prompt": "\ndef is_simple_power(x, n):\n \"\"\"Your task is to write a function that returns true if a number x is a simple\n power of n and false in other cases.\n x is a simple power of n if n**int=x\n For example:\n is_simple_power(1, 4) => true\n is_simple_power(2, 2) => true\n is_simple_power(8, 2) => true\n is_simple_power(3, 2) => false\n is_simple_power(3, 1) => false\n is_simple_power(5, 3) => false\n \"\"\"\n", "entry_point": "is_simple_power", "canonical_solution": " if (n == 1): \n return (x == 1) \n power = 1\n while (power < x): \n power = power * n \n return (power == x) \n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(16, 2)== True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(143214, 16)== False, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(4, 2)==True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(9, 3)==True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(16, 4)==True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(24, 2)==False, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(128, 4)==False, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(12, 6)==False, \"This prints if this assert fails 1 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(1, 1)==True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate(1, 12)==True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/77", "prompt": "\ndef iscube(a):\n '''\n Write a function that takes an integer a and returns True \n if this ingeger is a cube of some integer number.\n Note: you may assume the input is always valid.\n Examples:\n iscube(1) ==> True\n iscube(2) ==> False\n iscube(-1) ==> True\n iscube(64) ==> True\n iscube(0) ==> True\n iscube(180) ==> False\n '''\n", "entry_point": "iscube", "canonical_solution": " a = abs(a)\n return int(round(a ** (1. / 3))) ** 3 == a\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(1) == True, \"First test error: \" + str(candidate(1))\n assert candidate(2) == False, \"Second test error: \" + str(candidate(2))\n assert candidate(-1) == True, \"Third test error: \" + str(candidate(-1))\n assert candidate(64) == True, \"Fourth test error: \" + str(candidate(64))\n assert candidate(180) == False, \"Fifth test error: \" + str(candidate(180))\n assert candidate(1000) == True, \"Sixth test error: \" + str(candidate(1000))\n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(0) == True, \"1st edge test error: \" + str(candidate(0))\n assert candidate(1729) == False, \"2nd edge test error: \" + str(candidate(1728))\n\n"}
{"task_id": "HumanEval/78", "prompt": "\ndef hex_key(num):\n \"\"\"You have been tasked to write a function that receives \n a hexadecimal number as a string and counts the number of hexadecimal \n digits that are primes (prime number, or a prime, is a natural number \n greater than 1 that is not a product of two smaller natural numbers).\n Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n So you have to determine a number of the following digits: 2, 3, 5, 7, \n B (=decimal 11), D (=decimal 13).\n Note: you may assume the input is always correct or empty string, \n and symbols A,B,C,D,E,F are always uppercase.\n Examples:\n For num = \"AB\" the output should be 1.\n For num = \"1077E\" the output should be 2.\n For num = \"ABED1A33\" the output should be 4.\n For num = \"123456789ABCDEF0\" the output should be 6.\n For num = \"2020\" the output should be 2.\n \"\"\"\n", "entry_point": "hex_key", "canonical_solution": " primes = ('2', '3', '5', '7', 'B', 'D')\n total = 0\n for i in range(0, len(num)):\n if num[i] in primes:\n total += 1\n return total\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"AB\") == 1, \"First test error: \" + str(candidate(\"AB\")) \n assert candidate(\"1077E\") == 2, \"Second test error: \" + str(candidate(\"1077E\")) \n assert candidate(\"ABED1A33\") == 4, \"Third test error: \" + str(candidate(\"ABED1A33\")) \n assert candidate(\"2020\") == 2, \"Fourth test error: \" + str(candidate(\"2020\")) \n assert candidate(\"123456789ABCDEF0\") == 6, \"Fifth test error: \" + str(candidate(\"123456789ABCDEF0\")) \n assert candidate(\"112233445566778899AABBCCDDEEFF00\") == 12, \"Sixth test error: \" + str(candidate(\"112233445566778899AABBCCDDEEFF00\")) \n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([]) == 0\n\n"}
{"task_id": "HumanEval/79", "prompt": "\ndef decimal_to_binary(decimal):\n \"\"\"You will be given a number in decimal form and your task is to convert it to\n binary format. The function should return a string, with each character representing a binary\n number. Each character in the string will be '0' or '1'.\n\n There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n The extra characters are there to help with the format.\n\n Examples:\n decimal_to_binary(15) # returns \"db1111db\"\n decimal_to_binary(32) # returns \"db100000db\"\n \"\"\"\n", "entry_point": "decimal_to_binary", "canonical_solution": " return \"db\" + bin(decimal)[2:] + \"db\"\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(0) == \"db0db\"\n assert candidate(32) == \"db100000db\"\n assert candidate(103) == \"db1100111db\"\n assert candidate(15) == \"db1111db\", \"This prints if this assert fails 1 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/80", "prompt": "\ndef is_happy(s):\n \"\"\"You are given a string s.\n Your task is to check if the string is happy or not.\n A string is happy if its length is at least 3 and every 3 consecutive letters are distinct\n For example:\n is_happy(a) => False\n is_happy(aa) => False\n is_happy(abcd) => True\n is_happy(aabb) => False\n is_happy(adb) => True\n is_happy(xyy) => False\n \"\"\"\n", "entry_point": "is_happy", "canonical_solution": " if len(s) < 3:\n return False\n\n for i in range(len(s) - 2):\n \n if s[i] == s[i+1] or s[i+1] == s[i+2] or s[i] == s[i+2]:\n return False\n return True\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"a\") == False , \"a\"\n assert candidate(\"aa\") == False , \"aa\"\n assert candidate(\"abcd\") == True , \"abcd\"\n assert candidate(\"aabb\") == False , \"aabb\"\n assert candidate(\"adb\") == True , \"adb\"\n assert candidate(\"xyy\") == False , \"xyy\"\n assert candidate(\"iopaxpoi\") == True , \"iopaxpoi\"\n assert candidate(\"iopaxioi\") == False , \"iopaxioi\"\n"}
{"task_id": "HumanEval/81", "prompt": "\ndef numerical_letter_grade(grades):\n \"\"\"It is the last week of the semester and the teacher has to give the grades\n to students. The teacher has been making her own algorithm for grading.\n The only problem is, she has lost the code she used for grading.\n She has given you a list of GPAs for some students and you have to write \n a function that can output a list of letter grades using the following table:\n GPA | Letter grade\n 4.0 A+\n > 3.7 A \n > 3.3 A- \n > 3.0 B+\n > 2.7 B \n > 2.3 B-\n > 2.0 C+\n > 1.7 C\n > 1.3 C-\n > 1.0 D+ \n > 0.7 D \n > 0.0 D-\n 0.0 E\n \n\n Example:\n grade_equation([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-']\n \"\"\"\n", "entry_point": "numerical_letter_grade", "canonical_solution": "\n \n letter_grade = []\n for gpa in grades:\n if gpa == 4.0:\n letter_grade.append(\"A+\")\n elif gpa > 3.7:\n letter_grade.append(\"A\")\n elif gpa > 3.3:\n letter_grade.append(\"A-\")\n elif gpa > 3.0:\n letter_grade.append(\"B+\")\n elif gpa > 2.7:\n letter_grade.append(\"B\")\n elif gpa > 2.3:\n letter_grade.append(\"B-\")\n elif gpa > 2.0:\n letter_grade.append(\"C+\")\n elif gpa > 1.7:\n letter_grade.append(\"C\")\n elif gpa > 1.3:\n letter_grade.append(\"C-\")\n elif gpa > 1.0:\n letter_grade.append(\"D+\")\n elif gpa > 0.7:\n letter_grade.append(\"D\")\n elif gpa > 0.0:\n letter_grade.append(\"D-\")\n else:\n letter_grade.append(\"E\")\n return letter_grade\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([4.0, 3, 1.7, 2, 3.5]) == ['A+', 'B', 'C-', 'C', 'A-']\n assert candidate([1.2]) == ['D+']\n assert candidate([0.5]) == ['D-']\n assert candidate([0.0]) == ['E']\n assert candidate([1, 0.3, 1.5, 2.8, 3.3]) == ['D', 'D-', 'C-', 'B', 'B+']\n assert candidate([0, 0.7]) == ['E', 'D-']\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/82", "prompt": "\ndef prime_length(string):\n \"\"\"Write a function that takes a string and returns True if the string\n length is a prime number or False otherwise\n Examples\n prime_length('Hello') == True\n prime_length('abcdcba') == True\n prime_length('kittens') == True\n prime_length('orange') == False\n \"\"\"\n", "entry_point": "prime_length", "canonical_solution": " l = len(string)\n if l == 0 or l == 1:\n return False\n for i in range(2, l):\n if l % i == 0:\n return False\n return True\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate('Hello') == True\n assert candidate('abcdcba') == True\n assert candidate('kittens') == True\n assert candidate('orange') == False\n assert candidate('wow') == True\n assert candidate('world') == True\n assert candidate('MadaM') == True\n assert candidate('Wow') == True\n assert candidate('') == False\n assert candidate('HI') == True\n assert candidate('go') == True\n assert candidate('gogo') == False\n assert candidate('aaaaaaaaaaaaaaa') == False\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate('Madam') == True\n assert candidate('M') == False\n assert candidate('0') == False\n\n"}
{"task_id": "HumanEval/83", "prompt": "\ndef starts_one_ends(n):\n \"\"\"\n Given a positive integer n, return the count of the numbers of n-digit\n positive integers that start or end with 1.\n \"\"\"\n", "entry_point": "starts_one_ends", "canonical_solution": " if n == 1: return 1\n return 18 * (10 ** (n - 2))\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(1) == 1\n assert candidate(2) == 18\n assert candidate(3) == 180\n assert candidate(4) == 1800\n assert candidate(5) == 18000\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/84", "prompt": "\ndef solve(N):\n \"\"\"Given a positive integer N, return the total sum of its digits in binary.\n \n Example\n For N = 1000, the sum of digits will be 1 the output should be \"1\".\n For N = 150, the sum of digits will be 6 the output should be \"110\".\n For N = 147, the sum of digits will be 12 the output should be \"1100\".\n \n Variables:\n @N integer\n Constraints: 0 \u2264 N \u2264 10000.\n Output:\n a string of binary number\n \"\"\"\n", "entry_point": "solve", "canonical_solution": " return bin(sum(int(i) for i in str(N)))[2:]\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(1000) == \"1\", \"Error\"\n assert candidate(150) == \"110\", \"Error\"\n assert candidate(147) == \"1100\", \"Error\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate(333) == \"1001\", \"Error\"\n assert candidate(963) == \"10010\", \"Error\"\n\n"}
{"task_id": "HumanEval/85", "prompt": "\ndef add(lst):\n \"\"\"Given a non-empty list of integers lst. add the even elements that are at odd indices..\n\n\n Examples:\n add([4, 2, 6, 7]) ==> 2 \n \"\"\"\n", "entry_point": "add", "canonical_solution": " return sum([lst[i] for i in range(1, len(lst), 2) if lst[i]%2 == 0])\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([4, 88]) == 88\n assert candidate([4, 5, 6, 7, 2, 122]) == 122\n assert candidate([4, 0, 6, 7]) == 0\n assert candidate([4, 4, 6, 8]) == 12\n\n # Check some edge cases that are easy to work out by hand.\n \n"}
{"task_id": "HumanEval/86", "prompt": "\ndef anti_shuffle(s):\n \"\"\"\n Write a function that takes a string and returns an ordered version of it.\n Ordered version of string, is a string where all words (separated by space)\n are replaced by a new word where all the characters arranged in\n ascending order based on ascii value.\n Note: You should keep the order of words and blank spaces in the sentence.\n\n For example:\n anti_shuffle('Hi') returns 'Hi'\n anti_shuffle('hello') returns 'ehllo'\n anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor'\n \"\"\"\n", "entry_point": "anti_shuffle", "canonical_solution": " return ' '.join([''.join(sorted(list(i))) for i in s.split(' ')])\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate('Hi') == 'Hi'\n assert candidate('hello') == 'ehllo'\n assert candidate('number') == 'bemnru'\n assert candidate('abcd') == 'abcd'\n assert candidate('Hello World!!!') == 'Hello !!!Wdlor'\n assert candidate('') == ''\n assert candidate('Hi. My name is Mister Robot. How are you?') == '.Hi My aemn is Meirst .Rboot How aer ?ouy'\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/87", "prompt": "\ndef get_row(lst, x):\n \"\"\"\n You are given a 2 dimensional data, as a nested lists,\n which is similar to matrix, however, unlike matrices,\n each row may contain a different number of columns.\n Given lst, and integer x, find integers x in the list,\n and return list of tuples, [(x1, y1), (x2, y2) ...] such that\n each tuple is a coordinate - (row, columns), starting with 0.\n Sort coordinates initially by rows in ascending order.\n Also, sort coordinates of the row by columns in descending order.\n \n Examples:\n get_row([\n [1,2,3,4,5,6],\n [1,2,3,4,1,6],\n [1,2,3,4,5,1]\n ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]\n get_row([], 1) == []\n get_row([[], [1], [1, 2, 3]], 3) == [(2, 2)]\n \"\"\"\n", "entry_point": "get_row", "canonical_solution": " coords = [(i, j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j] == x]\n return sorted(sorted(coords, key=lambda x: x[1], reverse=True), key=lambda x: x[0])\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([\n [1,2,3,4,5,6],\n [1,2,3,4,1,6],\n [1,2,3,4,5,1]\n ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]\n assert candidate([\n [1,2,3,4,5,6],\n [1,2,3,4,5,6],\n [1,2,3,4,5,6],\n [1,2,3,4,5,6],\n [1,2,3,4,5,6],\n [1,2,3,4,5,6]\n ], 2) == [(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]\n assert candidate([\n [1,2,3,4,5,6],\n [1,2,3,4,5,6],\n [1,1,3,4,5,6],\n [1,2,1,4,5,6],\n [1,2,3,1,5,6],\n [1,2,3,4,1,6],\n [1,2,3,4,5,1]\n ], 1) == [(0, 0), (1, 0), (2, 1), (2, 0), (3, 2), (3, 0), (4, 3), (4, 0), (5, 4), (5, 0), (6, 5), (6, 0)]\n assert candidate([], 1) == []\n assert candidate([[1]], 2) == []\n assert candidate([[], [1], [1, 2, 3]], 3) == [(2, 2)]\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/88", "prompt": "\ndef sort_array(array):\n \"\"\"\n Given an array of non-negative integers, return a copy of the given array after sorting,\n you will sort the given array in ascending order if the sum( first index value, last index value) is odd,\n or sort it in descending order if the sum( first index value, last index value) is even.\n\n Note:\n * don't change the given array.\n\n Examples:\n * sort_array([]) => []\n * sort_array([5]) => [5]\n * sort_array([2, 4, 3, 0, 1, 5]) => [0, 1, 2, 3, 4, 5]\n * sort_array([2, 4, 3, 0, 1, 5, 6]) => [6, 5, 4, 3, 2, 1, 0]\n \"\"\"\n", "entry_point": "sort_array", "canonical_solution": " return [] if len(array) == 0 else sorted(array, reverse= (array[0]+array[-1]) % 2 == 0) \n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([]) == [], \"Error\"\n assert candidate([5]) == [5], \"Error\"\n assert candidate([2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5], \"Error\"\n assert candidate([2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0], \"Error\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate([2, 1]) == [1, 2], \"Error\"\n assert candidate([15, 42, 87, 32 ,11, 0]) == [0, 11, 15, 32, 42, 87], \"Error\"\n assert candidate([21, 14, 23, 11]) == [23, 21, 14, 11], \"Error\"\n\n"}
{"task_id": "HumanEval/89", "prompt": "\ndef encrypt(s):\n \"\"\"Create a function encrypt that takes a string as an argument and\n returns a string encrypted with the alphabet being rotated. \n The alphabet should be rotated in a manner such that the letters \n shift down by two multiplied to two places.\n For example:\n encrypt('hi') returns 'lm'\n encrypt('asdfghjkl') returns 'ewhjklnop'\n encrypt('gf') returns 'kj'\n encrypt('et') returns 'ix'\n \"\"\"\n", "entry_point": "encrypt", "canonical_solution": " d = 'abcdefghijklmnopqrstuvwxyz'\n out = ''\n for c in s:\n if c in d:\n out += d[(d.index(c)+2*2) % 26]\n else:\n out += c\n return out\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate('hi') == 'lm', \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate('asdfghjkl') == 'ewhjklnop', \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate('gf') == 'kj', \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate('et') == 'ix', \"This prints if this assert fails 1 (good for debugging!)\"\n\n assert candidate('faewfawefaewg')=='jeiajeaijeiak', \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate('hellomyfriend')=='lippsqcjvmirh', \"This prints if this assert fails 2 (good for debugging!)\"\n assert candidate('dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh')=='hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl', \"This prints if this assert fails 3 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate('a')=='e', \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/90", "prompt": "\ndef next_smallest(lst):\n \"\"\"\n You are given a list of integers.\n Write a function next_smallest() that returns the 2nd smallest element of the list.\n Return None if there is no such element.\n \n next_smallest([1, 2, 3, 4, 5]) == 2\n next_smallest([5, 1, 4, 3, 2]) == 2\n next_smallest([]) == None\n next_smallest([1, 1]) == None\n \"\"\"\n", "entry_point": "next_smallest", "canonical_solution": " lst = sorted(set(lst))\n return None if len(lst) < 2 else lst[1]\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([1, 2, 3, 4, 5]) == 2\n assert candidate([5, 1, 4, 3, 2]) == 2\n assert candidate([]) == None\n assert candidate([1, 1]) == None\n assert candidate([1,1,1,1,0]) == 1\n assert candidate([1, 0**0]) == None\n assert candidate([-35, 34, 12, -45]) == -35\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/91", "prompt": "\ndef is_bored(S):\n \"\"\"\n You'll be given a string of words, and your task is to count the number\n of boredoms. A boredom is a sentence that starts with the word \"I\".\n Sentences are delimited by '.', '?' or '!'.\n \n For example:\n >>> is_bored(\"Hello world\")\n 0\n >>> is_bored(\"The sky is blue. The sun is shining. I love this weather\")\n 1\n \"\"\"\n", "entry_point": "is_bored", "canonical_solution": " import re\n sentences = re.split(r'[.?!]\\s*', S)\n return sum(sentence[0:2] == 'I ' for sentence in sentences)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"Hello world\") == 0, \"Test 1\"\n assert candidate(\"Is the sky blue?\") == 0, \"Test 2\"\n assert candidate(\"I love It !\") == 1, \"Test 3\"\n assert candidate(\"bIt\") == 0, \"Test 4\"\n assert candidate(\"I feel good today. I will be productive. will kill It\") == 2, \"Test 5\"\n assert candidate(\"You and I are going for a walk\") == 0, \"Test 6\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/92", "prompt": "\ndef any_int(x, y, z):\n '''\n Create a function that takes 3 numbers.\n Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n Returns false in any other cases.\n \n Examples\n any_int(5, 2, 7) \u279e True\n \n any_int(3, 2, 2) \u279e False\n\n any_int(3, -2, 1) \u279e True\n \n any_int(3.6, -2.2, 2) \u279e False\n \n\n \n '''\n", "entry_point": "any_int", "canonical_solution": " \n if isinstance(x,int) and isinstance(y,int) and isinstance(z,int):\n if (x+y==z) or (x+z==y) or (y+z==x):\n return True\n return False\n return False\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(2, 3, 1)==True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(2.5, 2, 3)==False, \"This prints if this assert fails 2 (good for debugging!)\"\n assert candidate(1.5, 5, 3.5)==False, \"This prints if this assert fails 3 (good for debugging!)\"\n assert candidate(2, 6, 2)==False, \"This prints if this assert fails 4 (good for debugging!)\"\n assert candidate(4, 2, 2)==True, \"This prints if this assert fails 5 (good for debugging!)\"\n assert candidate(2.2, 2.2, 2.2)==False, \"This prints if this assert fails 6 (good for debugging!)\"\n assert candidate(-4, 6, 2)==True, \"This prints if this assert fails 7 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(2,1,1)==True, \"This prints if this assert fails 8 (also good for debugging!)\"\n assert candidate(3,4,7)==True, \"This prints if this assert fails 9 (also good for debugging!)\"\n assert candidate(3.0,4,7)==False, \"This prints if this assert fails 10 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/93", "prompt": "\ndef encode(message):\n \"\"\"\n Write a function that takes a message, and encodes in such a \n way that it swaps case of all letters, replaces all vowels in \n the message with the letter that appears 2 places ahead of that \n vowel in the english alphabet. \n Assume only letters. \n \n Examples:\n >>> encode('test')\n 'TGST'\n >>> encode('This is a message')\n 'tHKS KS C MGSSCGG'\n \"\"\"\n", "entry_point": "encode", "canonical_solution": " vowels = \"aeiouAEIOU\"\n vowels_replace = dict([(i, chr(ord(i) + 2)) for i in vowels])\n message = message.swapcase()\n return ''.join([vowels_replace[i] if i in vowels else i for i in message])\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate('TEST') == 'tgst', \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate('Mudasir') == 'mWDCSKR', \"This prints if this assert fails 2 (good for debugging!)\"\n assert candidate('YES') == 'ygs', \"This prints if this assert fails 3 (good for debugging!)\"\n \n # Check some edge cases that are easy to work out by hand.\n assert candidate('This is a message') == 'tHKS KS C MGSSCGG', \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate(\"I DoNt KnOw WhAt tO WrItE\") == 'k dQnT kNqW wHcT Tq wRkTg', \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/94", "prompt": "\n\ndef skjkasdkd(lst):\n \"\"\"You are given a list of integers.\n You need to find the largest prime value and return the sum of its digits.\n\n Examples:\n For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10\n For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25\n For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13\n For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11\n For lst = [0,81,12,3,1,21] the output should be 3\n For lst = [0,8,1,2,1,7] the output should be 7\n \"\"\"\n", "entry_point": "skjkasdkd", "canonical_solution": " def isPrime(n):\n for i in range(2,int(n**0.5)+1):\n if n%i==0:\n return False\n\n return True\n maxx = 0\n i = 0\n while i < len(lst):\n if(lst[i] > maxx and isPrime(lst[i])):\n maxx = lst[i]\n i+=1\n result = sum(int(digit) for digit in str(maxx))\n return result\n\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3]) == 10, \"This prints if this assert fails 1 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1]) == 25, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3]) == 13, \"This prints if this assert fails 3 (also good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([0,724,32,71,99,32,6,0,5,91,83,0,5,6]) == 11, \"This prints if this assert fails 4 (also good for debugging!)\"\n \n # Check some edge cases that are easy to work out by hand.\n assert candidate([0,81,12,3,1,21]) == 3, \"This prints if this assert fails 5 (also good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([0,8,1,2,1,7]) == 7, \"This prints if this assert fails 6 (also good for debugging!)\"\n\n assert candidate([8191]) == 19, \"This prints if this assert fails 7 (also good for debugging!)\"\n assert candidate([8191, 123456, 127, 7]) == 19, \"This prints if this assert fails 8 (also good for debugging!)\"\n assert candidate([127, 97, 8192]) == 10, \"This prints if this assert fails 9 (also good for debugging!)\"\n"}
{"task_id": "HumanEval/95", "prompt": "\ndef check_dict_case(dict):\n \"\"\"\n Given a dictionary, return True if all keys are strings in lower \n case or all keys are strings in upper case, else return False.\n The function should return False is the given dictionary is empty.\n Examples:\n check_dict_case({\"a\":\"apple\", \"b\":\"banana\"}) should return True.\n check_dict_case({\"a\":\"apple\", \"A\":\"banana\", \"B\":\"banana\"}) should return False.\n check_dict_case({\"a\":\"apple\", 8:\"banana\", \"a\":\"apple\"}) should return False.\n check_dict_case({\"Name\":\"John\", \"Age\":\"36\", \"City\":\"Houston\"}) should return False.\n check_dict_case({\"STATE\":\"NC\", \"ZIP\":\"12345\" }) should return True.\n \"\"\"\n", "entry_point": "check_dict_case", "canonical_solution": " if len(dict.keys()) == 0:\n return False\n else:\n state = \"start\"\n for key in dict.keys():\n\n if isinstance(key, str) == False:\n state = \"mixed\"\n break\n if state == \"start\":\n if key.isupper():\n state = \"upper\"\n elif key.islower():\n state = \"lower\"\n else:\n break\n elif (state == \"upper\" and not key.isupper()) or (state == \"lower\" and not key.islower()):\n state = \"mixed\"\n break\n else:\n break\n return state == \"upper\" or state == \"lower\" \n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate({\"p\":\"pineapple\", \"b\":\"banana\"}) == True, \"First test error: \" + str(candidate({\"p\":\"pineapple\", \"b\":\"banana\"}))\n assert candidate({\"p\":\"pineapple\", \"A\":\"banana\", \"B\":\"banana\"}) == False, \"Second test error: \" + str(candidate({\"p\":\"pineapple\", \"A\":\"banana\", \"B\":\"banana\"}))\n assert candidate({\"p\":\"pineapple\", 5:\"banana\", \"a\":\"apple\"}) == False, \"Third test error: \" + str(candidate({\"p\":\"pineapple\", 5:\"banana\", \"a\":\"apple\"}))\n assert candidate({\"Name\":\"John\", \"Age\":\"36\", \"City\":\"Houston\"}) == False, \"Fourth test error: \" + str(candidate({\"Name\":\"John\", \"Age\":\"36\", \"City\":\"Houston\"}))\n assert candidate({\"STATE\":\"NC\", \"ZIP\":\"12345\" }) == True, \"Fifth test error: \" + str(candidate({\"STATE\":\"NC\", \"ZIP\":\"12345\" })) \n assert candidate({\"fruit\":\"Orange\", \"taste\":\"Sweet\" }) == True, \"Fourth test error: \" + str(candidate({\"fruit\":\"Orange\", \"taste\":\"Sweet\" })) \n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate({}) == False, \"1st edge test error: \" + str(candidate({}))\n\n"}
{"task_id": "HumanEval/96", "prompt": "\ndef count_up_to(n):\n \"\"\"Implement a function that takes an non-negative integer and returns an array of the first n\n integers that are prime numbers and less than n.\n for example:\n count_up_to(5) => [2,3]\n count_up_to(11) => [2,3,5,7]\n count_up_to(0) => []\n count_up_to(20) => [2,3,5,7,11,13,17,19]\n count_up_to(1) => []\n count_up_to(18) => [2,3,5,7,11,13,17]\n \"\"\"\n", "entry_point": "count_up_to", "canonical_solution": " primes = []\n for i in range(2, n):\n is_prime = True\n for j in range(2, i):\n if i % j == 0:\n is_prime = False\n break\n if is_prime:\n primes.append(i)\n return primes\n\n", "test": "def check(candidate):\n\n assert candidate(5) == [2,3]\n assert candidate(6) == [2,3,5]\n assert candidate(7) == [2,3,5]\n assert candidate(10) == [2,3,5,7]\n assert candidate(0) == []\n assert candidate(22) == [2,3,5,7,11,13,17,19]\n assert candidate(1) == []\n assert candidate(18) == [2,3,5,7,11,13,17]\n assert candidate(47) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]\n assert candidate(101) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n\n"}
{"task_id": "HumanEval/97", "prompt": "\ndef multiply(a, b):\n \"\"\"Complete the function that takes two integers and returns \n the product of their unit digits.\n Assume the input is always valid.\n Examples:\n multiply(148, 412) should return 16.\n multiply(19, 28) should return 72.\n multiply(2020, 1851) should return 0.\n multiply(14,-15) should return 20.\n \"\"\"\n", "entry_point": "multiply", "canonical_solution": " return abs(a % 10) * abs(b % 10)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(148, 412) == 16, \"First test error: \" + str(candidate(148, 412)) \n assert candidate(19, 28) == 72, \"Second test error: \" + str(candidate(19, 28)) \n assert candidate(2020, 1851) == 0, \"Third test error: \" + str(candidate(2020, 1851))\n assert candidate(14,-15) == 20, \"Fourth test error: \" + str(candidate(14,-15)) \n assert candidate(76, 67) == 42, \"Fifth test error: \" + str(candidate(76, 67)) \n assert candidate(17, 27) == 49, \"Sixth test error: \" + str(candidate(17, 27)) \n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(0, 1) == 0, \"1st edge test error: \" + str(candidate(0, 1))\n assert candidate(0, 0) == 0, \"2nd edge test error: \" + str(candidate(0, 0))\n\n"}
{"task_id": "HumanEval/98", "prompt": "\ndef count_upper(s):\n \"\"\"\n Given a string s, count the number of uppercase vowels in even indices.\n \n For example:\n count_upper('aBCdEf') returns 1\n count_upper('abcdefg') returns 0\n count_upper('dBBE') returns 0\n \"\"\"\n", "entry_point": "count_upper", "canonical_solution": " count = 0\n for i in range(0,len(s),2):\n if s[i] in \"AEIOU\":\n count += 1\n return count\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate('aBCdEf') == 1\n assert candidate('abcdefg') == 0\n assert candidate('dBBE') == 0\n assert candidate('B') == 0\n assert candidate('U') == 1\n assert candidate('') == 0\n assert candidate('EEEE') == 2\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/99", "prompt": "\ndef closest_integer(value):\n '''\n Create a function that takes a value (string) representing a number\n and returns the closest integer to it. If the number is equidistant\n from two integers, round it away from zero.\n\n Examples\n >>> closest_integer(\"10\")\n 10\n >>> closest_integer(\"15.3\")\n 15\n\n Note:\n Rounding away from zero means that if the given number is equidistant\n from two integers, the one you should return is the one that is the\n farthest from zero. For example closest_integer(\"14.5\") should\n return 15 and closest_integer(\"-14.5\") should return -15.\n '''\n", "entry_point": "closest_integer", "canonical_solution": " from math import floor, ceil\n\n if value.count('.') == 1:\n # remove trailing zeros\n while (value[-1] == '0'):\n value = value[:-1]\n\n num = float(value)\n if value[-2:] == '.5':\n if num > 0:\n res = ceil(num)\n else:\n res = floor(num)\n elif len(value) > 0:\n res = int(round(num))\n else:\n res = 0\n\n return res\n\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"10\") == 10, \"Test 1\"\n assert candidate(\"14.5\") == 15, \"Test 2\"\n assert candidate(\"-15.5\") == -16, \"Test 3\"\n assert candidate(\"15.3\") == 15, \"Test 3\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(\"0\") == 0, \"Test 0\"\n\n"}
{"task_id": "HumanEval/100", "prompt": "\ndef make_a_pile(n):\n \"\"\"\n Given a positive integer n, you have to make a pile of n levels of stones.\n The first level has n stones.\n The number of stones in the next level is:\n - the next odd number if n is odd.\n - the next even number if n is even.\n Return the number of stones in each level in a list, where element at index\n i represents the number of stones in the level (i+1).\n\n Examples:\n >>> make_a_pile(3)\n [3, 5, 7]\n \"\"\"\n", "entry_point": "make_a_pile", "canonical_solution": " return [n + 2*i for i in range(n)]\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(3) == [3, 5, 7], \"Test 3\"\n assert candidate(4) == [4,6,8,10], \"Test 4\"\n assert candidate(5) == [5, 7, 9, 11, 13]\n assert candidate(6) == [6, 8, 10, 12, 14, 16]\n assert candidate(8) == [8, 10, 12, 14, 16, 18, 20, 22]\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/101", "prompt": "\ndef words_string(s):\n \"\"\"\n You will be given a string of words separated by commas or spaces. Your task is\n to split the string into words and return an array of the words.\n \n For example:\n words_string(\"Hi, my name is John\") == [\"Hi\", \"my\", \"name\", \"is\", \"John\"]\n words_string(\"One, two, three, four, five, six\") == [\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\n \"\"\"\n", "entry_point": "words_string", "canonical_solution": " if not s:\n return []\n\n s_list = []\n\n for letter in s:\n if letter == ',':\n s_list.append(' ')\n else:\n s_list.append(letter)\n\n s_list = \"\".join(s_list)\n return s_list.split()\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(\"Hi, my name is John\") == [\"Hi\", \"my\", \"name\", \"is\", \"John\"]\n assert candidate(\"One, two, three, four, five, six\") == [\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\n assert candidate(\"Hi, my name\") == [\"Hi\", \"my\", \"name\"]\n assert candidate(\"One,, two, three, four, five, six,\") == [\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate(\"\") == []\n assert candidate(\"ahmed , gamal\") == [\"ahmed\", \"gamal\"]\n\n"}
{"task_id": "HumanEval/102", "prompt": "\ndef choose_num(x, y):\n \"\"\"This function takes two positive numbers x and y and returns the\n biggest even integer number that is in the range [x, y] inclusive. If \n there's no such number, then the function should return -1.\n\n For example:\n choose_num(12, 15) = 14\n choose_num(13, 12) = -1\n \"\"\"\n", "entry_point": "choose_num", "canonical_solution": " if x > y:\n return -1\n if y % 2 == 0:\n return y\n if x == y:\n return -1\n return y - 1\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(12, 15) == 14\n assert candidate(13, 12) == -1\n assert candidate(33, 12354) == 12354\n assert candidate(5234, 5233) == -1\n assert candidate(6, 29) == 28\n assert candidate(27, 10) == -1\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(7, 7) == -1\n assert candidate(546, 546) == 546\n\n"}
{"task_id": "HumanEval/103", "prompt": "\ndef rounded_avg(n, m):\n \"\"\"You are given two positive integers n and m, and your task is to compute the\n average of the integers from n through m (including n and m). \n Round the answer to the nearest integer and convert that to binary.\n If n is greater than m, return -1.\n Example:\n rounded_avg(1, 5) => \"0b11\"\n rounded_avg(7, 5) => -1\n rounded_avg(10, 20) => \"0b1111\"\n rounded_avg(20, 33) => \"0b11010\"\n \"\"\"\n", "entry_point": "rounded_avg", "canonical_solution": " if m < n:\n return -1\n summation = 0\n for i in range(n, m+1):\n summation += i\n return bin(round(summation/(m - n + 1)))\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(1, 5) == \"0b11\"\n assert candidate(7, 13) == \"0b1010\"\n assert candidate(964,977) == \"0b1111001010\"\n assert candidate(996,997) == \"0b1111100100\"\n assert candidate(560,851) == \"0b1011000010\"\n assert candidate(185,546) == \"0b101101110\"\n assert candidate(362,496) == \"0b110101101\"\n assert candidate(350,902) == \"0b1001110010\"\n assert candidate(197,233) == \"0b11010111\"\n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(7, 5) == -1\n assert candidate(5, 1) == -1\n assert candidate(5, 5) == \"0b101\"\n\n"}
{"task_id": "HumanEval/104", "prompt": "\ndef unique_digits(x):\n \"\"\"Given a list of positive integers x. return a sorted list of all \n elements that hasn't any even digit.\n\n Note: Returned list should be sorted in increasing order.\n \n For example:\n >>> unique_digits([15, 33, 1422, 1])\n [1, 15, 33]\n >>> unique_digits([152, 323, 1422, 10])\n []\n \"\"\"\n", "entry_point": "unique_digits", "canonical_solution": " odd_digit_elements = []\n for i in x:\n if all (int(c) % 2 == 1 for c in str(i)):\n odd_digit_elements.append(i)\n return sorted(odd_digit_elements)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([15, 33, 1422, 1]) == [1, 15, 33]\n assert candidate([152, 323, 1422, 10]) == []\n assert candidate([12345, 2033, 111, 151]) == [111, 151]\n assert candidate([135, 103, 31]) == [31, 135]\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/105", "prompt": "\ndef by_length(arr):\n \"\"\"\n Given an array of integers, sort the integers that are between 1 and 9 inclusive,\n reverse the resulting array, and then replace each digit by its corresponding name from\n \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n\n For example:\n arr = [2, 1, 1, 4, 5, 8, 2, 3] \n -> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8] \n -> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1]\n return [\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\"]\n \n If the array is empty, return an empty array:\n arr = []\n return []\n \n If the array has any strange number ignore it:\n arr = [1, -1 , 55] \n -> sort arr -> [-1, 1, 55]\n -> reverse arr -> [55, 1, -1]\n return = ['One']\n \"\"\"\n", "entry_point": "by_length", "canonical_solution": " dic = {\n 1: \"One\",\n 2: \"Two\",\n 3: \"Three\",\n 4: \"Four\",\n 5: \"Five\",\n 6: \"Six\",\n 7: \"Seven\",\n 8: \"Eight\",\n 9: \"Nine\",\n }\n sorted_arr = sorted(arr, reverse=True)\n new_arr = []\n for var in sorted_arr:\n try:\n new_arr.append(dic[var])\n except:\n pass\n return new_arr\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([2, 1, 1, 4, 5, 8, 2, 3]) == [\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\"], \"Error\"\n assert candidate([]) == [], \"Error\"\n assert candidate([1, -1 , 55]) == ['One'], \"Error\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate([1, -1, 3, 2]) == [\"Three\", \"Two\", \"One\"]\n assert candidate([9, 4, 8]) == [\"Nine\", \"Eight\", \"Four\"]\n\n"}
{"task_id": "HumanEval/106", "prompt": "\ndef f(n):\n \"\"\" Implement the function f that takes n as a parameter,\n and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even\n or the sum of numbers from 1 to i otherwise.\n i starts from 1.\n the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n Example:\n f(5) == [1, 2, 6, 24, 15]\n \"\"\"\n", "entry_point": "f", "canonical_solution": " ret = []\n for i in range(1,n+1):\n if i%2 == 0:\n x = 1\n for j in range(1,i+1): x *= j\n ret += [x]\n else:\n x = 0\n for j in range(1,i+1): x += j\n ret += [x]\n return ret\n", "test": "def check(candidate):\n\n assert candidate(5) == [1, 2, 6, 24, 15]\n assert candidate(7) == [1, 2, 6, 24, 15, 720, 28]\n assert candidate(1) == [1]\n assert candidate(3) == [1, 2, 6]\n"}
{"task_id": "HumanEval/107", "prompt": "\ndef even_odd_palindrome(n):\n \"\"\"\n Given a positive integer n, return a tuple that has the number of even and odd\n integer palindromes that fall within the range(1, n), inclusive.\n\n Example 1:\n\n Input: 3\n Output: (1, 2)\n Explanation:\n Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n\n Example 2:\n\n Input: 12\n Output: (4, 6)\n Explanation:\n Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n\n Note:\n 1. 1 <= n <= 10^3\n 2. returned tuple has the number of even and odd integer palindromes respectively.\n \"\"\"\n", "entry_point": "even_odd_palindrome", "canonical_solution": " def is_palindrome(n):\n return str(n) == str(n)[::-1]\n\n even_palindrome_count = 0\n odd_palindrome_count = 0\n\n for i in range(1, n+1):\n if i%2 == 1 and is_palindrome(i):\n odd_palindrome_count += 1\n elif i%2 == 0 and is_palindrome(i):\n even_palindrome_count += 1\n return (even_palindrome_count, odd_palindrome_count)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(123) == (8, 13)\n assert candidate(12) == (4, 6)\n assert candidate(3) == (1, 2)\n assert candidate(63) == (6, 8)\n assert candidate(25) == (5, 6)\n assert candidate(19) == (4, 6)\n assert candidate(9) == (4, 5), \"This prints if this assert fails 1 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(1) == (0, 1), \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/108", "prompt": "\ndef count_nums(arr):\n \"\"\"\n Write a function count_nums which takes an array of integers and returns\n the number of elements which has a sum of digits > 0.\n If a number is negative, then its first signed digit will be negative:\n e.g. -123 has signed digits -1, 2, and 3.\n >>> count_nums([]) == 0\n >>> count_nums([-1, 11, -11]) == 1\n >>> count_nums([1, 1, 2]) == 3\n \"\"\"\n", "entry_point": "count_nums", "canonical_solution": " def digits_sum(n):\n neg = 1\n if n < 0: n, neg = -1 * n, -1 \n n = [int(i) for i in str(n)]\n n[0] = n[0] * neg\n return sum(n)\n return len(list(filter(lambda x: x > 0, [digits_sum(i) for i in arr])))\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([]) == 0\n assert candidate([-1, -2, 0]) == 0\n assert candidate([1, 1, 2, -2, 3, 4, 5]) == 6\n assert candidate([1, 6, 9, -6, 0, 1, 5]) == 5\n assert candidate([1, 100, 98, -7, 1, -1]) == 4\n assert candidate([12, 23, 34, -45, -56, 0]) == 5\n assert candidate([-0, 1**0]) == 1\n assert candidate([1]) == 1\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/109", "prompt": "\ndef move_one_ball(arr):\n \"\"\"We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n numbers in the array will be randomly ordered. Your task is to determine if\n it is possible to get an array sorted in non-decreasing order by performing \n the following operation on the given array:\n You are allowed to perform right shift operation any number of times.\n \n One right shift operation means shifting all elements of the array by one\n position in the right direction. The last element of the array will be moved to\n the starting position in the array i.e. 0th index. \n\n If it is possible to obtain the sorted array by performing the above operation\n then return True else return False.\n If the given array is empty then return True.\n\n Note: The given list is guaranteed to have unique elements.\n\n For Example:\n \n move_one_ball([3, 4, 5, 1, 2])==>True\n Explanation: By performin 2 right shift operations, non-decreasing order can\n be achieved for the given array.\n move_one_ball([3, 5, 4, 1, 2])==>False\n Explanation:It is not possible to get non-decreasing order for the given\n array by performing any number of right shift operations.\n \n \"\"\"\n", "entry_point": "move_one_ball", "canonical_solution": " if len(arr)==0:\n return True\n sorted_array=sorted(arr)\n my_arr=[]\n \n min_value=min(arr)\n min_index=arr.index(min_value)\n my_arr=arr[min_index:]+arr[0:min_index]\n for i in range(len(arr)):\n if my_arr[i]!=sorted_array[i]:\n return False\n return True\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([3, 4, 5, 1, 2])==True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([3, 5, 10, 1, 2])==True\n assert candidate([4, 3, 1, 2])==False\n # Check some edge cases that are easy to work out by hand.\n assert candidate([3, 5, 4, 1, 2])==False, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate([])==True\n"}
{"task_id": "HumanEval/110", "prompt": "\ndef exchange(lst1, lst2):\n \"\"\"In this problem, you will implement a function that takes two lists of numbers,\n and determines whether it is possible to perform an exchange of elements\n between them to make lst1 a list of only even numbers.\n There is no limit on the number of exchanged elements between lst1 and lst2.\n If it is possible to exchange elements between the lst1 and lst2 to make\n all the elements of lst1 to be even, return \"YES\".\n Otherwise, return \"NO\".\n For example:\n exchange([1, 2, 3, 4], [1, 2, 3, 4]) => \"YES\"\n exchange([1, 2, 3, 4], [1, 5, 3, 4]) => \"NO\"\n It is assumed that the input lists will be non-empty.\n \"\"\"\n", "entry_point": "exchange", "canonical_solution": " odd = 0\n even = 0\n for i in lst1:\n if i%2 == 1:\n odd += 1\n for i in lst2:\n if i%2 == 0:\n even += 1\n if even >= odd:\n return \"YES\"\n return \"NO\"\n \n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([1, 2, 3, 4], [1, 2, 3, 4]) == \"YES\"\n assert candidate([1, 2, 3, 4], [1, 5, 3, 4]) == \"NO\"\n assert candidate([1, 2, 3, 4], [2, 1, 4, 3]) == \"YES\" \n assert candidate([5, 7, 3], [2, 6, 4]) == \"YES\"\n assert candidate([5, 7, 3], [2, 6, 3]) == \"NO\" \n assert candidate([3, 2, 6, 1, 8, 9], [3, 5, 5, 1, 1, 1]) == \"NO\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([100, 200], [200, 200]) == \"YES\"\n\n"}
{"task_id": "HumanEval/111", "prompt": "\ndef histogram(test):\n \"\"\"Given a string representing a space separated lowercase letters, return a dictionary\n of the letter with the most repetition and containing the corresponding count.\n If several letters have the same occurrence, return all of them.\n \n Example:\n histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}\n histogram('a b b a') == {'a': 2, 'b': 2}\n histogram('a b c a b') == {'a': 2, 'b': 2}\n histogram('b b b b a') == {'b': 4}\n histogram('') == {}\n\n \"\"\"\n", "entry_point": "histogram", "canonical_solution": " dict1={}\n list1=test.split(\" \")\n t=0\n\n for i in list1:\n if(list1.count(i)>t) and i!='':\n t=list1.count(i)\n if t>0:\n for i in list1:\n if(list1.count(i)==t):\n \n dict1[i]=t\n return dict1\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate('a b b a') == {'a':2,'b': 2}, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate('a b c a b') == {'a': 2, 'b': 2}, \"This prints if this assert fails 2 (good for debugging!)\"\n assert candidate('a b c d g') == {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'g': 1}, \"This prints if this assert fails 3 (good for debugging!)\"\n assert candidate('r t g') == {'r': 1,'t': 1,'g': 1}, \"This prints if this assert fails 4 (good for debugging!)\"\n assert candidate('b b b b a') == {'b': 4}, \"This prints if this assert fails 5 (good for debugging!)\"\n assert candidate('r t g') == {'r': 1,'t': 1,'g': 1}, \"This prints if this assert fails 6 (good for debugging!)\"\n \n \n # Check some edge cases that are easy to work out by hand.\n assert candidate('') == {}, \"This prints if this assert fails 7 (also good for debugging!)\"\n assert candidate('a') == {'a': 1}, \"This prints if this assert fails 8 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/112", "prompt": "\ndef reverse_delete(s,c):\n \"\"\"Task\n We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n then check if the result string is palindrome.\n A string is called palindrome if it reads the same backward as forward.\n You should return a tuple containing the result string and True/False for the check.\n Example\n For s = \"abcde\", c = \"ae\", the result should be ('bcd',False)\n For s = \"abcdef\", c = \"b\" the result should be ('acdef',False)\n For s = \"abcdedcba\", c = \"ab\", the result should be ('cdedc',True)\n \"\"\"\n", "entry_point": "reverse_delete", "canonical_solution": " s = ''.join([char for char in s if char not in c])\n return (s,s[::-1] == s)\n", "test": "def check(candidate):\n\n assert candidate(\"abcde\",\"ae\") == ('bcd',False)\n assert candidate(\"abcdef\", \"b\") == ('acdef',False)\n assert candidate(\"abcdedcba\",\"ab\") == ('cdedc',True)\n assert candidate(\"dwik\",\"w\") == ('dik',False)\n assert candidate(\"a\",\"a\") == ('',True)\n assert candidate(\"abcdedcba\",\"\") == ('abcdedcba',True)\n assert candidate(\"abcdedcba\",\"v\") == ('abcdedcba',True)\n assert candidate(\"vabba\",\"v\") == ('abba',True)\n assert candidate(\"mamma\", \"mia\") == (\"\", True)\n"}
{"task_id": "HumanEval/113", "prompt": "\ndef odd_count(lst):\n \"\"\"Given a list of strings, where each string consists of only digits, return a list.\n Each element i of the output should be \"the number of odd elements in the\n string i of the input.\" where all the i's should be replaced by the number\n of odd digits in the i'th string of the input.\n\n >>> odd_count(['1234567'])\n [\"the number of odd elements 4n the str4ng 4 of the 4nput.\"]\n >>> odd_count(['3',\"11111111\"])\n [\"the number of odd elements 1n the str1ng 1 of the 1nput.\",\n \"the number of odd elements 8n the str8ng 8 of the 8nput.\"]\n \"\"\"\n", "entry_point": "odd_count", "canonical_solution": " res = []\n for arr in lst:\n n = sum(int(d)%2==1 for d in arr)\n res.append(\"the number of odd elements \" + str(n) + \"n the str\"+ str(n) +\"ng \"+ str(n) +\" of the \"+ str(n) +\"nput.\")\n return res\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(['1234567']) == [\"the number of odd elements 4n the str4ng 4 of the 4nput.\"], \"Test 1\"\n assert candidate(['3',\"11111111\"]) == [\"the number of odd elements 1n the str1ng 1 of the 1nput.\", \"the number of odd elements 8n the str8ng 8 of the 8nput.\"], \"Test 2\"\n assert candidate(['271', '137', '314']) == [\n 'the number of odd elements 2n the str2ng 2 of the 2nput.',\n 'the number of odd elements 3n the str3ng 3 of the 3nput.',\n 'the number of odd elements 2n the str2ng 2 of the 2nput.'\n ]\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/114", "prompt": "\ndef minSubArraySum(nums):\n \"\"\"\n Given an array of integers nums, find the minimum sum of any non-empty sub-array\n of nums.\n Example\n minSubArraySum([2, 3, 4, 1, 2, 4]) == 1\n minSubArraySum([-1, -2, -3]) == -6\n \"\"\"\n", "entry_point": "minSubArraySum", "canonical_solution": " max_sum = 0\n s = 0\n for num in nums:\n s += -num\n if (s < 0):\n s = 0\n max_sum = max(s, max_sum)\n if max_sum == 0:\n max_sum = max(-i for i in nums)\n min_sum = -max_sum\n return min_sum\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([2, 3, 4, 1, 2, 4]) == 1, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([-1, -2, -3]) == -6\n assert candidate([-1, -2, -3, 2, -10]) == -14\n assert candidate([-9999999999999999]) == -9999999999999999\n assert candidate([0, 10, 20, 1000000]) == 0\n assert candidate([-1, -2, -3, 10, -5]) == -6\n assert candidate([100, -1, -2, -3, 10, -5]) == -6\n assert candidate([10, 11, 13, 8, 3, 4]) == 3\n assert candidate([100, -33, 32, -1, 0, -2]) == -33\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([-10]) == -10, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate([7]) == 7\n assert candidate([1, -1]) == -1\n"}
{"task_id": "HumanEval/115", "prompt": "\ndef max_fill(grid, capacity):\n import math\n \"\"\"\n You are given a rectangular grid of wells. Each row represents a single well,\n and each 1 in a row represents a single unit of water.\n Each well has a corresponding bucket that can be used to extract water from it, \n and all buckets have the same capacity.\n Your task is to use the buckets to empty the wells.\n Output the number of times you need to lower the buckets.\n\n Example 1:\n Input: \n grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]\n bucket_capacity : 1\n Output: 6\n\n Example 2:\n Input: \n grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]\n bucket_capacity : 2\n Output: 5\n \n Example 3:\n Input: \n grid : [[0,0,0], [0,0,0]]\n bucket_capacity : 5\n Output: 0\n\n Constraints:\n * all wells have the same length\n * 1 <= grid.length <= 10^2\n * 1 <= grid[:,1].length <= 10^2\n * grid[i][j] -> 0 | 1\n * 1 <= capacity <= 10\n \"\"\"\n", "entry_point": "max_fill", "canonical_solution": " return sum([math.ceil(sum(arr)/capacity) for arr in grid])\n", "test": "def check(candidate):\n\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([[0,0,1,0], [0,1,0,0], [1,1,1,1]], 1) == 6, \"Error\"\n assert candidate([[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]], 2) == 5, \"Error\"\n assert candidate([[0,0,0], [0,0,0]], 5) == 0, \"Error\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate([[1,1,1,1], [1,1,1,1]], 2) == 4, \"Error\"\n assert candidate([[1,1,1,1], [1,1,1,1]], 9) == 2, \"Error\"\n\n"}
{"task_id": "HumanEval/116", "prompt": "\ndef sort_array(arr):\n \"\"\"\n In this Kata, you have to sort an array of non-negative integers according to\n number of ones in their binary representation in ascending order.\n For similar number of ones, sort based on decimal value.\n\n It must be implemented like this:\n >>> sort_array([1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]\n >>> sort_array([-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]\n >>> sort_array([1, 0, 2, 3, 4]) [0, 1, 2, 3, 4]\n \"\"\"\n", "entry_point": "sort_array", "canonical_solution": " return sorted(sorted(arr), key=lambda x: bin(x)[2:].count('1'))\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([1,5,2,3,4]) == [1, 2, 4, 3, 5]\n assert candidate([-2,-3,-4,-5,-6]) == [-4, -2, -6, -5, -3]\n assert candidate([1,0,2,3,4]) == [0, 1, 2, 4, 3]\n assert candidate([]) == []\n assert candidate([2,5,77,4,5,3,5,7,2,3,4]) == [2, 2, 4, 4, 3, 3, 5, 5, 5, 7, 77]\n assert candidate([3,6,44,12,32,5]) == [32, 3, 5, 6, 12, 44]\n assert candidate([2,4,8,16,32]) == [2, 4, 8, 16, 32]\n assert candidate([2,4,8,16,32]) == [2, 4, 8, 16, 32]\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/117", "prompt": "\ndef select_words(s, n):\n \"\"\"Given a string s and a natural number n, you have been tasked to implement \n a function that returns a list of all words from string s that contain exactly \n n consonants, in order these words appear in the string s.\n If the string s is empty then the function should return an empty list.\n Note: you may assume the input string contains only letters and spaces.\n Examples:\n select_words(\"Mary had a little lamb\", 4) ==> [\"little\"]\n select_words(\"Mary had a little lamb\", 3) ==> [\"Mary\", \"lamb\"]\n select_words(\"simple white space\", 2) ==> []\n select_words(\"Hello world\", 4) ==> [\"world\"]\n select_words(\"Uncle sam\", 3) ==> [\"Uncle\"]\n \"\"\"\n", "entry_point": "select_words", "canonical_solution": " result = []\n for word in s.split():\n n_consonants = 0\n for i in range(0, len(word)):\n if word[i].lower() not in [\"a\",\"e\",\"i\",\"o\",\"u\"]:\n n_consonants += 1 \n if n_consonants == n:\n result.append(word)\n return result\n\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"Mary had a little lamb\", 4) == [\"little\"], \"First test error: \" + str(candidate(\"Mary had a little lamb\", 4)) \n assert candidate(\"Mary had a little lamb\", 3) == [\"Mary\", \"lamb\"], \"Second test error: \" + str(candidate(\"Mary had a little lamb\", 3)) \n assert candidate(\"simple white space\", 2) == [], \"Third test error: \" + str(candidate(\"simple white space\", 2)) \n assert candidate(\"Hello world\", 4) == [\"world\"], \"Fourth test error: \" + str(candidate(\"Hello world\", 4)) \n assert candidate(\"Uncle sam\", 3) == [\"Uncle\"], \"Fifth test error: \" + str(candidate(\"Uncle sam\", 3))\n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(\"\", 4) == [], \"1st edge test error: \" + str(candidate(\"\", 4))\n assert candidate(\"a b c d e f\", 1) == [\"b\", \"c\", \"d\", \"f\"], \"2nd edge test error: \" + str(candidate(\"a b c d e f\", 1))\n\n"}
{"task_id": "HumanEval/118", "prompt": "\ndef get_closest_vowel(word):\n \"\"\"You are given a word. Your task is to find the closest vowel that stands between \n two consonants from the right side of the word (case sensitive).\n \n Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n find any vowel met the above condition. \n\n You may assume that the given string contains English letter only.\n\n Example:\n get_closest_vowel(\"yogurt\") ==> \"u\"\n get_closest_vowel(\"FULL\") ==> \"U\"\n get_closest_vowel(\"quick\") ==> \"\"\n get_closest_vowel(\"ab\") ==> \"\"\n \"\"\"\n", "entry_point": "get_closest_vowel", "canonical_solution": " if len(word) < 3:\n return \"\"\n\n vowels = {\"a\", \"e\", \"i\", \"o\", \"u\", \"A\", \"E\", 'O', 'U', 'I'}\n for i in range(len(word)-2, 0, -1):\n if word[i] in vowels:\n if (word[i+1] not in vowels) and (word[i-1] not in vowels):\n return word[i]\n return \"\"\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"yogurt\") == \"u\"\n assert candidate(\"full\") == \"u\"\n assert candidate(\"easy\") == \"\"\n assert candidate(\"eAsy\") == \"\"\n assert candidate(\"ali\") == \"\"\n assert candidate(\"bad\") == \"a\"\n assert candidate(\"most\") == \"o\"\n assert candidate(\"ab\") == \"\"\n assert candidate(\"ba\") == \"\"\n assert candidate(\"quick\") == \"\"\n assert candidate(\"anime\") == \"i\"\n assert candidate(\"Asia\") == \"\"\n assert candidate(\"Above\") == \"o\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/119", "prompt": "\ndef match_parens(lst):\n '''\n You are given a list of two strings, both strings consist of open\n parentheses '(' or close parentheses ')' only.\n Your job is to check if it is possible to concatenate the two strings in\n some order, that the resulting string will be good.\n A string S is considered to be good if and only if all parentheses in S\n are balanced. For example: the string '(())()' is good, while the string\n '())' is not.\n Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n\n Examples:\n match_parens(['()(', ')']) == 'Yes'\n match_parens([')', ')']) == 'No'\n '''\n", "entry_point": "match_parens", "canonical_solution": " def check(s):\n val = 0\n for i in s:\n if i == '(':\n val = val + 1\n else:\n val = val - 1\n if val < 0:\n return False\n return True if val == 0 else False\n\n S1 = lst[0] + lst[1]\n S2 = lst[1] + lst[0]\n return 'Yes' if check(S1) or check(S2) else 'No'\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(['()(', ')']) == 'Yes'\n assert candidate([')', ')']) == 'No'\n assert candidate(['(()(())', '())())']) == 'No'\n assert candidate([')())', '(()()(']) == 'Yes'\n assert candidate(['(())))', '(()())((']) == 'Yes'\n assert candidate(['()', '())']) == 'No'\n assert candidate(['(()(', '()))()']) == 'Yes'\n assert candidate(['((((', '((())']) == 'No'\n assert candidate([')(()', '(()(']) == 'No'\n assert candidate([')(', ')(']) == 'No'\n \n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(['(', ')']) == 'Yes'\n assert candidate([')', '(']) == 'Yes' \n\n"}
{"task_id": "HumanEval/120", "prompt": "\ndef maximum(arr, k):\n \"\"\"\n Given an array arr of integers and a positive integer k, return a sorted list \n of length k with the maximum k numbers in arr.\n\n Example 1:\n\n Input: arr = [-3, -4, 5], k = 3\n Output: [-4, -3, 5]\n\n Example 2:\n\n Input: arr = [4, -4, 4], k = 2\n Output: [4, 4]\n\n Example 3:\n\n Input: arr = [-3, 2, 1, 2, -1, -2, 1], k = 1\n Output: [2]\n\n Note:\n 1. The length of the array will be in the range of [1, 1000].\n 2. The elements in the array will be in the range of [-1000, 1000].\n 3. 0 <= k <= len(arr)\n \"\"\"\n", "entry_point": "maximum", "canonical_solution": " if k == 0:\n return []\n arr.sort()\n ans = arr[-k:]\n return ans\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([-3, -4, 5], 3) == [-4, -3, 5]\n assert candidate([4, -4, 4], 2) == [4, 4]\n assert candidate([-3, 2, 1, 2, -1, -2, 1], 1) == [2]\n assert candidate([123, -123, 20, 0 , 1, 2, -3], 3) == [2, 20, 123]\n assert candidate([-123, 20, 0 , 1, 2, -3], 4) == [0, 1, 2, 20]\n assert candidate([5, 15, 0, 3, -13, -8, 0], 7) == [-13, -8, 0, 0, 3, 5, 15]\n assert candidate([-1, 0, 2, 5, 3, -10], 2) == [3, 5]\n assert candidate([1, 0, 5, -7], 1) == [5]\n assert candidate([4, -4], 2) == [-4, 4]\n assert candidate([-10, 10], 2) == [-10, 10]\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([1, 2, 3, -23, 243, -400, 0], 0) == []\n\n"}
{"task_id": "HumanEval/121", "prompt": "\ndef solution(lst):\n \"\"\"Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.\n \n\n Examples\n solution([5, 8, 7, 1]) ==> 12\n solution([3, 3, 3, 3, 3]) ==> 9\n solution([30, 13, 24, 321]) ==>0\n \"\"\"\n", "entry_point": "solution", "canonical_solution": " return sum([x for idx, x in enumerate(lst) if idx%2==0 and x%2==1])\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([5, 8, 7, 1]) == 12\n assert candidate([3, 3, 3, 3, 3]) == 9\n assert candidate([30, 13, 24, 321]) == 0\n assert candidate([5, 9]) == 5\n assert candidate([2, 4, 8]) == 0\n assert candidate([30, 13, 23, 32]) == 23\n assert candidate([3, 13, 2, 9]) == 3\n\n # Check some edge cases that are easy to work out by hand.\n\n"}
{"task_id": "HumanEval/122", "prompt": "\ndef add_elements(arr, k):\n \"\"\"\n Given a non-empty array of integers arr and an integer k, return\n the sum of the elements with at most two digits from the first k elements of arr.\n\n Example:\n\n Input: arr = [111,21,3,4000,5,6,7,8,9], k = 4\n Output: 24 # sum of 21 + 3\n\n Constraints:\n 1. 1 <= len(arr) <= 100\n 2. 1 <= k <= len(arr)\n \"\"\"\n", "entry_point": "add_elements", "canonical_solution": " return sum(elem for elem in arr[:k] if len(str(elem)) <= 2)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([1,-2,-3,41,57,76,87,88,99], 3) == -4\n assert candidate([111,121,3,4000,5,6], 2) == 0\n assert candidate([11,21,3,90,5,6,7,8,9], 4) == 125\n assert candidate([111,21,3,4000,5,6,7,8,9], 4) == 24, \"This prints if this assert fails 1 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([1], 1) == 1, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/123", "prompt": "\ndef get_odd_collatz(n):\n \"\"\"\n Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.\n\n The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\n as follows: start with any positive integer n. Then each term is obtained from the \n previous term as follows: if the previous term is even, the next term is one half of \n the previous term. If the previous term is odd, the next term is 3 times the previous\n term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\n\n Note: \n 1. Collatz(1) is [1].\n 2. returned list sorted in increasing order.\n\n For example:\n get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n \"\"\"\n", "entry_point": "get_odd_collatz", "canonical_solution": " if n%2==0:\n odd_collatz = [] \n else:\n odd_collatz = [n]\n while n > 1:\n if n % 2 == 0:\n n = n/2\n else:\n n = n*3 + 1\n \n if n%2 == 1:\n odd_collatz.append(int(n))\n\n return sorted(odd_collatz)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(14) == [1, 5, 7, 11, 13, 17]\n assert candidate(5) == [1, 5]\n assert candidate(12) == [1, 3, 5], \"This prints if this assert fails 1 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(1) == [1], \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/124", "prompt": "\ndef valid_date(date):\n \"\"\"You have to write a function which validates a given date string and\n returns True if the date is valid otherwise False.\n The date is valid if all of the following rules are satisfied:\n 1. The date string is not empty.\n 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.\n 3. The months should not be less than 1 or higher than 12.\n 4. The date should be in the format: mm-dd-yyyy\n\n for example: \n valid_date('03-11-2000') => True\n\n valid_date('15-01-2012') => False\n\n valid_date('04-0-2040') => False\n\n valid_date('06-04-2020') => True\n\n valid_date('06/04/2020') => False\n \"\"\"\n", "entry_point": "valid_date", "canonical_solution": " try:\n date = date.strip()\n month, day, year = date.split('-')\n month, day, year = int(month), int(day), int(year)\n if month < 1 or month > 12:\n return False\n if month in [1,3,5,7,8,10,12] and day < 1 or day > 31:\n return False\n if month in [4,6,9,11] and day < 1 or day > 30:\n return False\n if month == 2 and day < 1 or day > 29:\n return False\n except:\n return False\n\n return True\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate('03-11-2000') == True\n\n assert candidate('15-01-2012') == False\n\n assert candidate('04-0-2040') == False\n\n assert candidate('06-04-2020') == True\n\n assert candidate('01-01-2007') == True\n\n assert candidate('03-32-2011') == False\n\n assert candidate('') == False\n\n assert candidate('04-31-3000') == False\n\n assert candidate('06-06-2005') == True\n\n assert candidate('21-31-2000') == False\n\n assert candidate('04-12-2003') == True\n\n assert candidate('04122003') == False\n\n assert candidate('20030412') == False\n\n assert candidate('2003-04') == False\n\n assert candidate('2003-04-12') == False\n\n assert candidate('04-2003') == False\n"}
{"task_id": "HumanEval/125", "prompt": "\ndef split_words(txt):\n '''\n Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you\n should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\n alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\n Examples\n split_words(\"Hello world!\") \u279e [\"Hello\", \"world!\"]\n split_words(\"Hello,world!\") \u279e [\"Hello\", \"world!\"]\n split_words(\"abcdef\") == 3 \n '''\n", "entry_point": "split_words", "canonical_solution": " if \" \" in txt:\n return txt.split()\n elif \",\" in txt:\n return txt.replace(',',' ').split()\n else:\n return len([i for i in txt if i.islower() and ord(i)%2 == 0])\n", "test": "def check(candidate):\n\n assert candidate(\"Hello world!\") == [\"Hello\",\"world!\"]\n assert candidate(\"Hello,world!\") == [\"Hello\",\"world!\"]\n assert candidate(\"Hello world,!\") == [\"Hello\",\"world,!\"]\n assert candidate(\"Hello,Hello,world !\") == [\"Hello,Hello,world\",\"!\"]\n assert candidate(\"abcdef\") == 3\n assert candidate(\"aaabb\") == 2\n assert candidate(\"aaaBb\") == 1\n assert candidate(\"\") == 0\n"}
{"task_id": "HumanEval/126", "prompt": "\ndef is_sorted(lst):\n '''\n Given a list of numbers, return whether or not they are sorted\n in ascending order. If list has more than 1 duplicate of the same\n number, return False. Assume no negative numbers and only integers.\n\n Examples\n is_sorted([5]) \u279e True\n is_sorted([1, 2, 3, 4, 5]) \u279e True\n is_sorted([1, 3, 2, 4, 5]) \u279e False\n is_sorted([1, 2, 3, 4, 5, 6]) \u279e True\n is_sorted([1, 2, 3, 4, 5, 6, 7]) \u279e True\n is_sorted([1, 3, 2, 4, 5, 6, 7]) \u279e False\n is_sorted([1, 2, 2, 3, 3, 4]) \u279e True\n is_sorted([1, 2, 2, 2, 3, 4]) \u279e False\n '''\n", "entry_point": "is_sorted", "canonical_solution": " count_digit = dict([(i, 0) for i in lst])\n for i in lst:\n count_digit[i]+=1 \n if any(count_digit[i] > 2 for i in lst):\n return False\n if all(lst[i-1] <= lst[i] for i in range(1, len(lst))):\n return True\n else:\n return False\n \n \n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([5]) == True\n assert candidate([1, 2, 3, 4, 5]) == True\n assert candidate([1, 3, 2, 4, 5]) == False\n assert candidate([1, 2, 3, 4, 5, 6]) == True\n assert candidate([1, 2, 3, 4, 5, 6, 7]) == True\n assert candidate([1, 3, 2, 4, 5, 6, 7]) == False, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([]) == True, \"This prints if this assert fails 2 (good for debugging!)\"\n assert candidate([1]) == True, \"This prints if this assert fails 3 (good for debugging!)\"\n assert candidate([3, 2, 1]) == False, \"This prints if this assert fails 4 (good for debugging!)\"\n \n # Check some edge cases that are easy to work out by hand.\n assert candidate([1, 2, 2, 2, 3, 4]) == False, \"This prints if this assert fails 5 (good for debugging!)\"\n assert candidate([1, 2, 3, 3, 3, 4]) == False, \"This prints if this assert fails 6 (good for debugging!)\"\n assert candidate([1, 2, 2, 3, 3, 4]) == True, \"This prints if this assert fails 7 (good for debugging!)\"\n assert candidate([1, 2, 3, 4]) == True, \"This prints if this assert fails 8 (good for debugging!)\"\n\n"}
{"task_id": "HumanEval/127", "prompt": "\ndef intersection(interval1, interval2):\n \"\"\"You are given two intervals,\n where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n The given intervals are closed which means that the interval (start, end)\n includes both start and end.\n For each given interval, it is assumed that its start is less or equal its end.\n Your task is to determine whether the length of intersection of these two \n intervals is a prime number.\n Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n which its length is 1, which not a prime number.\n If the length of the intersection is a prime number, return \"YES\",\n otherwise, return \"NO\".\n If the two intervals don't intersect, return \"NO\".\n\n\n [input/output] samples:\n intersection((1, 2), (2, 3)) ==> \"NO\"\n intersection((-1, 1), (0, 4)) ==> \"NO\"\n intersection((-3, -1), (-5, 5)) ==> \"YES\"\n \"\"\"\n", "entry_point": "intersection", "canonical_solution": " def is_prime(num):\n if num == 1 or num == 0:\n return False\n if num == 2:\n return True\n for i in range(2, num):\n if num%i == 0:\n return False\n return True\n\n l = max(interval1[0], interval2[0])\n r = min(interval1[1], interval2[1])\n length = r - l\n if length > 0 and is_prime(length):\n return \"YES\"\n return \"NO\"\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate((1, 2), (2, 3)) == \"NO\"\n assert candidate((-1, 1), (0, 4)) == \"NO\"\n assert candidate((-3, -1), (-5, 5)) == \"YES\"\n assert candidate((-2, 2), (-4, 0)) == \"YES\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate((-11, 2), (-1, -1)) == \"NO\"\n assert candidate((1, 2), (3, 5)) == \"NO\"\n assert candidate((1, 2), (1, 2)) == \"NO\"\n assert candidate((-2, -2), (-3, -2)) == \"NO\"\n\n"}
{"task_id": "HumanEval/128", "prompt": "\ndef prod_signs(arr):\n \"\"\"\n You are given an array arr of integers and you need to return\n sum of magnitudes of integers multiplied by product of all signs\n of each number in the array, represented by 1, -1 or 0.\n Note: return None for empty arr.\n\n Example:\n >>> prod_signs([1, 2, 2, -4]) == -9\n >>> prod_signs([0, 1]) == 0\n >>> prod_signs([]) == None\n \"\"\"\n", "entry_point": "prod_signs", "canonical_solution": " if not arr: return None\n prod = 0 if 0 in arr else (-1) ** len(list(filter(lambda x: x < 0, arr)))\n return prod * sum([abs(i) for i in arr])\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([1, 2, 2, -4]) == -9\n assert candidate([0, 1]) == 0\n assert candidate([1, 1, 1, 2, 3, -1, 1]) == -10\n assert candidate([]) == None\n assert candidate([2, 4,1, 2, -1, -1, 9]) == 20\n assert candidate([-1, 1, -1, 1]) == 4\n assert candidate([-1, 1, 1, 1]) == -4\n assert candidate([-1, 1, 1, 0]) == 0\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/129", "prompt": "\ndef minPath(grid, k):\n \"\"\"\n Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n each cell of the grid contains a value. Every integer in the range [1, N * N]\n inclusive appears exactly once on the cells of the grid.\n\n You have to find the minimum path of length k in the grid. You can start\n from any cell, and in each step you can move to any of the neighbor cells,\n in other words, you can go to cells which share an edge with you current\n cell.\n Please note that a path of length k means visiting exactly k cells (not\n necessarily distinct).\n You CANNOT go off the grid.\n A path A (of length k) is considered less than a path B (of length k) if\n after making the ordered lists of the values on the cells that A and B go\n through (let's call them lst_A and lst_B), lst_A is lexicographically less\n than lst_B, in other words, there exist an integer index i (1 <= i <= k)\n such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have\n lst_A[j] = lst_B[j].\n It is guaranteed that the answer is unique.\n Return an ordered list of the values on the cells that the minimum path go through.\n\n Examples:\n\n Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3\n Output: [1, 2, 1]\n\n Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1\n Output: [1]\n \"\"\"\n", "entry_point": "minPath", "canonical_solution": " n = len(grid)\n val = n * n + 1\n for i in range(n):\n for j in range(n):\n if grid[i][j] == 1:\n temp = []\n if i != 0:\n temp.append(grid[i - 1][j])\n\n if j != 0:\n temp.append(grid[i][j - 1])\n\n if i != n - 1:\n temp.append(grid[i + 1][j])\n\n if j != n - 1:\n temp.append(grid[i][j + 1])\n\n val = min(temp)\n\n ans = []\n for i in range(k):\n if i % 2 == 0:\n ans.append(1)\n else:\n ans.append(val)\n return ans\n", "test": "def check(candidate):\n\n # Check some simple cases\n print\n assert candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) == [1, 2, 1]\n assert candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) == [1]\n assert candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4) == [1, 2, 1, 2]\n assert candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7) == [1, 10, 1, 10, 1, 10, 1]\n assert candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5) == [1, 7, 1, 7, 1]\n assert candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9) == [1, 6, 1, 6, 1, 6, 1, 6, 1]\n assert candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12) == [1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]\n assert candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8) == [1, 3, 1, 3, 1, 3, 1, 3]\n assert candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8) == [1, 5, 1, 5, 1, 5, 1, 5]\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([[1, 2], [3, 4]], 10) == [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]\n assert candidate([[1, 3], [3, 2]], 10) == [1, 3, 1, 3, 1, 3, 1, 3, 1, 3]\n\n"}
{"task_id": "HumanEval/130", "prompt": "\ndef tri(n):\n \"\"\"Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n the last couple centuries. However, what people don't know is Tribonacci sequence.\n Tribonacci sequence is defined by the recurrence:\n tri(1) = 3\n tri(n) = 1 + n / 2, if n is even.\n tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n For example:\n tri(2) = 1 + (2 / 2) = 2\n tri(4) = 3\n tri(3) = tri(2) + tri(1) + tri(4)\n = 2 + 3 + 3 = 8 \n You are given a non-negative integer number n, you have to a return a list of the \n first n + 1 numbers of the Tribonacci sequence.\n Examples:\n tri(3) = [1, 3, 2, 8]\n \"\"\"\n", "entry_point": "tri", "canonical_solution": " if n == 0:\n return [1]\n my_tri = [1, 3]\n for i in range(2, n + 1):\n if i % 2 == 0:\n my_tri.append(i / 2 + 1)\n else:\n my_tri.append(my_tri[i - 1] + my_tri[i - 2] + (i + 3) / 2)\n return my_tri\n", "test": "def check(candidate):\n\n # Check some simple cases\n \n assert candidate(3) == [1, 3, 2.0, 8.0]\n assert candidate(4) == [1, 3, 2.0, 8.0, 3.0]\n assert candidate(5) == [1, 3, 2.0, 8.0, 3.0, 15.0]\n assert candidate(6) == [1, 3, 2.0, 8.0, 3.0, 15.0, 4.0]\n assert candidate(7) == [1, 3, 2.0, 8.0, 3.0, 15.0, 4.0, 24.0]\n assert candidate(8) == [1, 3, 2.0, 8.0, 3.0, 15.0, 4.0, 24.0, 5.0]\n assert candidate(9) == [1, 3, 2.0, 8.0, 3.0, 15.0, 4.0, 24.0, 5.0, 35.0]\n assert candidate(20) == [1, 3, 2.0, 8.0, 3.0, 15.0, 4.0, 24.0, 5.0, 35.0, 6.0, 48.0, 7.0, 63.0, 8.0, 80.0, 9.0, 99.0, 10.0, 120.0, 11.0]\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(0) == [1]\n assert candidate(1) == [1, 3]\n"}
{"task_id": "HumanEval/131", "prompt": "\ndef digits(n):\n \"\"\"Given a positive integer n, return the product of the odd digits.\n Return 0 if all digits are even.\n For example:\n digits(1) == 1\n digits(4) == 0\n digits(235) == 15\n \"\"\"\n", "entry_point": "digits", "canonical_solution": " product = 1\n odd_count = 0\n for digit in str(n):\n int_digit = int(digit)\n if int_digit%2 == 1:\n product= product*int_digit\n odd_count+=1\n if odd_count ==0:\n return 0\n else:\n return product\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(5) == 5\n assert candidate(54) == 5\n assert candidate(120) ==1\n assert candidate(5014) == 5\n assert candidate(98765) == 315\n assert candidate(5576543) == 2625\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(2468) == 0\n\n"}
{"task_id": "HumanEval/132", "prompt": "\ndef is_nested(string):\n '''\n Create a function that takes a string as input which contains only square brackets.\n The function should return True if and only if there is a valid subsequence of brackets \n where at least one bracket in the subsequence is nested.\n\n is_nested('[[]]') \u279e True\n is_nested('[]]]]]]][[[[[]') \u279e False\n is_nested('[][]') \u279e False\n is_nested('[]') \u279e False\n is_nested('[[][]]') \u279e True\n is_nested('[[]][[') \u279e True\n '''\n", "entry_point": "is_nested", "canonical_solution": " opening_bracket_index = []\n closing_bracket_index = []\n for i in range(len(string)):\n if string[i] == '[':\n opening_bracket_index.append(i)\n else:\n closing_bracket_index.append(i)\n closing_bracket_index.reverse()\n cnt = 0\n i = 0\n l = len(closing_bracket_index)\n for idx in opening_bracket_index:\n if i < l and idx < closing_bracket_index[i]:\n cnt += 1\n i += 1\n return cnt >= 2\n\n \n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate('[[]]') == True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate('[]]]]]]][[[[[]') == False\n assert candidate('[][]') == False\n assert candidate(('[]')) == False\n assert candidate('[[[[]]]]') == True\n assert candidate('[]]]]]]]]]]') == False\n assert candidate('[][][[]]') == True\n assert candidate('[[]') == False\n assert candidate('[]]') == False\n assert candidate('[[]][[') == True\n assert candidate('[[][]]') == True\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate('') == False, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate('[[[[[[[[') == False\n assert candidate(']]]]]]]]') == False\n\n"}
{"task_id": "HumanEval/133", "prompt": "\n\ndef sum_squares(lst):\n \"\"\"You are given a list of numbers.\n You need to return the sum of squared numbers in the given list,\n round each element in the list to the upper int(Ceiling) first.\n Examples:\n For lst = [1,2,3] the output should be 14\n For lst = [1,4,9] the output should be 98\n For lst = [1,3,5,7] the output should be 84\n For lst = [1.4,4.2,0] the output should be 29\n For lst = [-2.4,1,1] the output should be 6\n \n\n \"\"\"\n", "entry_point": "sum_squares", "canonical_solution": " import math\n squared = 0\n for i in lst:\n squared += math.ceil(i)**2\n return squared\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([1,2,3])==14, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([1.0,2,3])==14, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([1,3,5,7])==84, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([1.4,4.2,0])==29, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([-2.4,1,1])==6, \"This prints if this assert fails 1 (good for debugging!)\"\n\n assert candidate([100,1,15,2])==10230, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([10000,10000])==200000000, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([-1.4,4.6,6.3])==75, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([-1.4,17.9,18.9,19.9])==1086, \"This prints if this assert fails 1 (good for debugging!)\"\n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([0])==0, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate([-1])==1, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate([-1,1,0])==2, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/134", "prompt": "\ndef check_if_last_char_is_a_letter(txt):\n '''\n Create a function that returns True if the last character\n of a given string is an alphabetical character and is not\n a part of a word, and False otherwise.\n Note: \"word\" is a group of characters separated by space.\n\n Examples:\n check_if_last_char_is_a_letter(\"apple pie\") \u279e False\n check_if_last_char_is_a_letter(\"apple pi e\") \u279e True\n check_if_last_char_is_a_letter(\"apple pi e \") \u279e False\n check_if_last_char_is_a_letter(\"\") \u279e False \n '''\n", "entry_point": "check_if_last_char_is_a_letter", "canonical_solution": " \n check = txt.split(' ')[-1]\n return True if len(check) == 1 and (97 <= ord(check.lower()) <= 122) else False\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"apple\") == False\n assert candidate(\"apple pi e\") == True\n assert candidate(\"eeeee\") == False\n assert candidate(\"A\") == True\n assert candidate(\"Pumpkin pie \") == False\n assert candidate(\"Pumpkin pie 1\") == False\n assert candidate(\"\") == False\n assert candidate(\"eeeee e \") == False\n assert candidate(\"apple pie\") == False\n assert candidate(\"apple pi e \") == False\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/135", "prompt": "\ndef can_arrange(arr):\n \"\"\"Create a function which returns the largest index of an element which\n is not greater than or equal to the element immediately preceding it. If\n no such element exists then return -1. The given array will not contain\n duplicate values.\n\n Examples:\n can_arrange([1,2,4,3,5]) = 3\n can_arrange([1,2,3]) = -1\n \"\"\"\n", "entry_point": "can_arrange", "canonical_solution": " ind=-1\n i=1\n while i<len(arr):\n if arr[i]<arr[i-1]:\n ind=i\n i+=1\n return ind\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([1,2,4,3,5])==3\n assert candidate([1,2,4,5])==-1\n assert candidate([1,4,2,5,6,7,8,9,10])==2\n assert candidate([4,8,5,7,3])==4\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([])==-1\n\n"}
{"task_id": "HumanEval/136", "prompt": "\ndef largest_smallest_integers(lst):\n '''\n Create a function that returns a tuple (a, b), where 'a' is\n the largest of negative integers, and 'b' is the smallest\n of positive integers in a list.\n If there is no negative or positive integers, return them as None.\n\n Examples:\n largest_smallest_integers([2, 4, 1, 3, 5, 7]) == (None, 1)\n largest_smallest_integers([]) == (None, None)\n largest_smallest_integers([0]) == (None, None)\n '''\n", "entry_point": "largest_smallest_integers", "canonical_solution": " smallest = list(filter(lambda x: x < 0, lst))\n largest = list(filter(lambda x: x > 0, lst))\n return (max(smallest) if smallest else None, min(largest) if largest else None)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([2, 4, 1, 3, 5, 7]) == (None, 1)\n assert candidate([2, 4, 1, 3, 5, 7, 0]) == (None, 1)\n assert candidate([1, 3, 2, 4, 5, 6, -2]) == (-2, 1)\n assert candidate([4, 5, 3, 6, 2, 7, -7]) == (-7, 2)\n assert candidate([7, 3, 8, 4, 9, 2, 5, -9]) == (-9, 2)\n assert candidate([]) == (None, None)\n assert candidate([0]) == (None, None)\n assert candidate([-1, -3, -5, -6]) == (-1, None)\n assert candidate([-1, -3, -5, -6, 0]) == (-1, None)\n assert candidate([-6, -4, -4, -3, 1]) == (-3, 1)\n assert candidate([-6, -4, -4, -3, -100, 1]) == (-3, 1)\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n"}
{"task_id": "HumanEval/137", "prompt": "\ndef compare_one(a, b):\n \"\"\"\n Create a function that takes integers, floats, or strings representing\n real numbers, and returns the larger variable in its given variable type.\n Return None if the values are equal.\n Note: If a real number is represented as a string, the floating point might be . or ,\n\n compare_one(1, 2.5) \u279e 2.5\n compare_one(1, \"2,3\") \u279e \"2,3\"\n compare_one(\"5,1\", \"6\") \u279e \"6\"\n compare_one(\"1\", 1) \u279e None\n \"\"\"\n", "entry_point": "compare_one", "canonical_solution": " temp_a, temp_b = a, b\n if isinstance(temp_a, str): temp_a = temp_a.replace(',','.')\n if isinstance(temp_b, str): temp_b = temp_b.replace(',','.')\n if float(temp_a) == float(temp_b): return None\n return a if float(temp_a) > float(temp_b) else b \n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(1, 2) == 2\n assert candidate(1, 2.5) == 2.5\n assert candidate(2, 3) == 3\n assert candidate(5, 6) == 6\n assert candidate(1, \"2,3\") == \"2,3\"\n assert candidate(\"5,1\", \"6\") == \"6\"\n assert candidate(\"1\", \"2\") == \"2\"\n assert candidate(\"1\", 1) == None\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/138", "prompt": "\ndef is_equal_to_sum_even(n):\n \"\"\"Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n Example\n is_equal_to_sum_even(4) == False\n is_equal_to_sum_even(6) == False\n is_equal_to_sum_even(8) == True\n \"\"\"\n", "entry_point": "is_equal_to_sum_even", "canonical_solution": " return n%2 == 0 and n >= 8\n", "test": "def check(candidate):\n assert candidate(4) == False\n assert candidate(6) == False\n assert candidate(8) == True\n assert candidate(10) == True\n assert candidate(11) == False\n assert candidate(12) == True\n assert candidate(13) == False\n assert candidate(16) == True\n"}
{"task_id": "HumanEval/139", "prompt": "\ndef special_factorial(n):\n \"\"\"The Brazilian factorial is defined as:\n brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n where n > 0\n\n For example:\n >>> special_factorial(4)\n 288\n\n The function will receive an integer as input and should return the special\n factorial of this integer.\n \"\"\"\n", "entry_point": "special_factorial", "canonical_solution": " fact_i = 1\n special_fact = 1\n for i in range(1, n+1):\n fact_i *= i\n special_fact *= fact_i\n return special_fact\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(4) == 288, \"Test 4\"\n assert candidate(5) == 34560, \"Test 5\"\n assert candidate(7) == 125411328000, \"Test 7\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(1) == 1, \"Test 1\"\n\n"}
{"task_id": "HumanEval/140", "prompt": "\ndef fix_spaces(text):\n \"\"\"\n Given a string text, replace all spaces in it with underscores, \n and if a string has more than 2 consecutive spaces, \n then replace all consecutive spaces with - \n \n fix_spaces(\"Example\") == \"Example\"\n fix_spaces(\"Example 1\") == \"Example_1\"\n fix_spaces(\" Example 2\") == \"_Example_2\"\n fix_spaces(\" Example 3\") == \"_Example-3\"\n \"\"\"\n", "entry_point": "fix_spaces", "canonical_solution": " new_text = \"\"\n i = 0\n start, end = 0, 0\n while i < len(text):\n if text[i] == \" \":\n end += 1\n else:\n if end - start > 2:\n new_text += \"-\"+text[i]\n elif end - start > 0:\n new_text += \"_\"*(end - start)+text[i]\n else:\n new_text += text[i]\n start, end = i+1, i+1\n i+=1\n if end - start > 2:\n new_text += \"-\"\n elif end - start > 0:\n new_text += \"_\"\n return new_text\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"Example\") == \"Example\", \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(\"Mudasir Hanif \") == \"Mudasir_Hanif_\", \"This prints if this assert fails 2 (good for debugging!)\"\n assert candidate(\"Yellow Yellow Dirty Fellow\") == \"Yellow_Yellow__Dirty__Fellow\", \"This prints if this assert fails 3 (good for debugging!)\"\n \n # Check some edge cases that are easy to work out by hand.\n assert candidate(\"Exa mple\") == \"Exa-mple\", \"This prints if this assert fails 4 (good for debugging!)\"\n assert candidate(\" Exa 1 2 2 mple\") == \"-Exa_1_2_2_mple\", \"This prints if this assert fails 4 (good for debugging!)\"\n\n"}
{"task_id": "HumanEval/141", "prompt": "\ndef file_name_check(file_name):\n \"\"\"Create a function which takes a string representing a file's name, and returns\n 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n A file's name is considered to be valid if and only if all the following conditions \n are met:\n - There should not be more than three digits ('0'-'9') in the file's name.\n - The file's name contains exactly one dot '.'\n - The substring before the dot should not be empty, and it starts with a letter from \n the latin alphapet ('a'-'z' and 'A'-'Z').\n - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n Examples:\n file_name_check(\"example.txt\") # => 'Yes'\n file_name_check(\"1example.dll\") # => 'No' (the name should start with a latin alphapet letter)\n \"\"\"\n", "entry_point": "file_name_check", "canonical_solution": " suf = ['txt', 'exe', 'dll']\n lst = file_name.split(sep='.')\n if len(lst) != 2:\n return 'No'\n if not lst[1] in suf:\n return 'No'\n if len(lst[0]) == 0:\n return 'No'\n if not lst[0][0].isalpha():\n return 'No'\n t = len([x for x in lst[0] if x.isdigit()])\n if t > 3:\n return 'No'\n return 'Yes'\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"example.txt\") == 'Yes'\n assert candidate(\"1example.dll\") == 'No'\n assert candidate('s1sdf3.asd') == 'No'\n assert candidate('K.dll') == 'Yes'\n assert candidate('MY16FILE3.exe') == 'Yes'\n assert candidate('His12FILE94.exe') == 'No'\n assert candidate('_Y.txt') == 'No'\n assert candidate('?aREYA.exe') == 'No'\n assert candidate('/this_is_valid.dll') == 'No'\n assert candidate('this_is_valid.wow') == 'No'\n assert candidate('this_is_valid.txt') == 'Yes'\n assert candidate('this_is_valid.txtexe') == 'No'\n assert candidate('#this2_i4s_5valid.ten') == 'No'\n assert candidate('@this1_is6_valid.exe') == 'No'\n assert candidate('this_is_12valid.6exe4.txt') == 'No'\n assert candidate('all.exe.txt') == 'No'\n assert candidate('I563_No.exe') == 'Yes'\n assert candidate('Is3youfault.txt') == 'Yes'\n assert candidate('no_one#knows.dll') == 'Yes'\n assert candidate('1I563_Yes3.exe') == 'No'\n assert candidate('I563_Yes3.txtt') == 'No'\n assert candidate('final..txt') == 'No'\n assert candidate('final132') == 'No'\n assert candidate('_f4indsartal132.') == 'No'\n \n \n\n # Check some edge cases that are easy to work out by hand.\n assert candidate('.txt') == 'No'\n assert candidate('s.') == 'No'\n\n"}
{"task_id": "HumanEval/142", "prompt": "\n\n\ndef sum_squares(lst):\n \"\"\"\"\n This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a \n multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n \n Examples:\n For lst = [1,2,3] the output should be 6\n For lst = [] the output should be 0\n For lst = [-1,-5,2,-1,-5] the output should be -126\n \"\"\"\n", "entry_point": "sum_squares", "canonical_solution": " result =[]\n for i in range(len(lst)):\n if i %3 == 0:\n result.append(lst[i]**2)\n elif i % 4 == 0 and i%3 != 0:\n result.append(lst[i]**3)\n else:\n result.append(lst[i])\n return sum(result)\n", "test": "def check(candidate):\n\n # Check some simple cases\n \n assert candidate([1,2,3]) == 6\n assert candidate([1,4,9]) == 14\n assert candidate([]) == 0\n assert candidate([1,1,1,1,1,1,1,1,1]) == 9\n assert candidate([-1,-1,-1,-1,-1,-1,-1,-1,-1]) == -3\n assert candidate([0]) == 0\n assert candidate([-1,-5,2,-1,-5]) == -126\n assert candidate([-56,-99,1,0,-2]) == 3030\n assert candidate([-1,0,0,0,0,0,0,0,-1]) == 0\n assert candidate([-16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37]) == -14196\n assert candidate([-1, -3, 17, -1, -15, 13, -1, 14, -14, -12, -5, 14, -14, 6, 13, 11, 16, 16, 4, 10]) == -1448\n \n \n # Don't remove this line:\n"}
{"task_id": "HumanEval/143", "prompt": "\ndef words_in_sentence(sentence):\n \"\"\"\n You are given a string representing a sentence,\n the sentence contains some words separated by a space,\n and you have to return a string that contains the words from the original sentence,\n whose lengths are prime numbers,\n the order of the words in the new string should be the same as the original one.\n\n Example 1:\n Input: sentence = \"This is a test\"\n Output: \"is\"\n\n Example 2:\n Input: sentence = \"lets go for swimming\"\n Output: \"go for\"\n\n Constraints:\n * 1 <= len(sentence) <= 100\n * sentence contains only letters\n \"\"\"\n", "entry_point": "words_in_sentence", "canonical_solution": " new_lst = []\n for word in sentence.split():\n flg = 0\n if len(word) == 1:\n flg = 1\n for i in range(2, len(word)):\n if len(word)%i == 0:\n flg = 1\n if flg == 0 or len(word) == 2:\n new_lst.append(word)\n return \" \".join(new_lst)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"This is a test\") == \"is\"\n assert candidate(\"lets go for swimming\") == \"go for\"\n assert candidate(\"there is no place available here\") == \"there is no place\"\n assert candidate(\"Hi I am Hussein\") == \"Hi am Hussein\"\n assert candidate(\"go for it\") == \"go for it\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(\"here\") == \"\"\n assert candidate(\"here is\") == \"is\"\n\n"}
{"task_id": "HumanEval/144", "prompt": "\ndef simplify(x, n):\n \"\"\"Your task is to implement a function that will simplify the expression\n x * n. The function returns True if x * n evaluates to a whole number and False\n otherwise. Both x and n, are string representation of a fraction, and have the following format,\n <numerator>/<denominator> where both numerator and denominator are positive whole numbers.\n\n You can assume that x, and n are valid fractions, and do not have zero as denominator.\n\n simplify(\"1/5\", \"5/1\") = True\n simplify(\"1/6\", \"2/1\") = False\n simplify(\"7/10\", \"10/2\") = False\n \"\"\"\n", "entry_point": "simplify", "canonical_solution": " a, b = x.split(\"/\")\n c, d = n.split(\"/\")\n numerator = int(a) * int(c)\n denom = int(b) * int(d)\n if (numerator/denom == int(numerator/denom)):\n return True\n return False\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"1/5\", \"5/1\") == True, 'test1'\n assert candidate(\"1/6\", \"2/1\") == False, 'test2'\n assert candidate(\"5/1\", \"3/1\") == True, 'test3'\n assert candidate(\"7/10\", \"10/2\") == False, 'test4'\n assert candidate(\"2/10\", \"50/10\") == True, 'test5'\n assert candidate(\"7/2\", \"4/2\") == True, 'test6'\n assert candidate(\"11/6\", \"6/1\") == True, 'test7'\n assert candidate(\"2/3\", \"5/2\") == False, 'test8'\n assert candidate(\"5/2\", \"3/5\") == False, 'test9'\n assert candidate(\"2/4\", \"8/4\") == True, 'test10'\n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(\"2/4\", \"4/2\") == True, 'test11'\n assert candidate(\"1/5\", \"5/1\") == True, 'test12'\n assert candidate(\"1/5\", \"1/5\") == False, 'test13'\n\n"}
{"task_id": "HumanEval/145", "prompt": "\ndef order_by_points(nums):\n \"\"\"\n Write a function which sorts the given list of integers\n in ascending order according to the sum of their digits.\n Note: if there are several items with similar sum of their digits,\n order them based on their index in original list.\n\n For example:\n >>> order_by_points([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]\n >>> order_by_points([]) == []\n \"\"\"\n", "entry_point": "order_by_points", "canonical_solution": " def digits_sum(n):\n neg = 1\n if n < 0: n, neg = -1 * n, -1 \n n = [int(i) for i in str(n)]\n n[0] = n[0] * neg\n return sum(n)\n return sorted(nums, key=digits_sum)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]\n assert candidate([1234,423,463,145,2,423,423,53,6,37,3457,3,56,0,46]) == [0, 2, 3, 6, 53, 423, 423, 423, 1234, 145, 37, 46, 56, 463, 3457]\n assert candidate([]) == []\n assert candidate([1, -11, -32, 43, 54, -98, 2, -3]) == [-3, -32, -98, -11, 1, 2, 43, 54]\n assert candidate([1,2,3,4,5,6,7,8,9,10,11]) == [1, 10, 2, 11, 3, 4, 5, 6, 7, 8, 9]\n assert candidate([0,6,6,-76,-21,23,4]) == [-76, -21, 0, 4, 23, 6, 6]\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/146", "prompt": "\ndef specialFilter(nums):\n \"\"\"Write a function that takes an array of numbers as input and returns \n the number of elements in the array that are greater than 10 and both \n first and last digits of a number are odd (1, 3, 5, 7, 9).\n For example:\n specialFilter([15, -73, 14, -15]) => 1 \n specialFilter([33, -2, -3, 45, 21, 109]) => 2\n \"\"\"\n", "entry_point": "specialFilter", "canonical_solution": " \n count = 0\n for num in nums:\n if num > 10:\n odd_digits = (1, 3, 5, 7, 9)\n number_as_string = str(num)\n if int(number_as_string[0]) in odd_digits and int(number_as_string[-1]) in odd_digits:\n count += 1\n \n return count \n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([5, -2, 1, -5]) == 0 \n assert candidate([15, -73, 14, -15]) == 1\n assert candidate([33, -2, -3, 45, 21, 109]) == 2\n assert candidate([43, -12, 93, 125, 121, 109]) == 4\n assert candidate([71, -2, -33, 75, 21, 19]) == 3\n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([1]) == 0 \n assert candidate([]) == 0 \n\n"}
{"task_id": "HumanEval/147", "prompt": "\ndef get_max_triples(n):\n \"\"\"\n You are given a positive integer n. You have to create an integer array a of length n.\n For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n and a[i] + a[j] + a[k] is a multiple of 3.\n\n Example :\n Input: n = 5\n Output: 1\n Explanation: \n a = [1, 3, 7, 13, 21]\n The only valid triple is (1, 7, 13).\n \"\"\"\n", "entry_point": "get_max_triples", "canonical_solution": " A = [i*i - i + 1 for i in range(1,n+1)]\n ans = []\n for i in range(n):\n for j in range(i+1,n):\n for k in range(j+1,n):\n if (A[i]+A[j]+A[k])%3 == 0:\n ans += [(A[i],A[j],A[k])]\n return len(ans)\n", "test": "def check(candidate):\n\n assert candidate(5) == 1\n assert candidate(6) == 4\n assert candidate(10) == 36\n assert candidate(100) == 53361\n"}
{"task_id": "HumanEval/148", "prompt": "\ndef bf(planet1, planet2):\n '''\n There are eight planets in our solar system: the closerst to the Sun \n is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, \n Uranus, Neptune.\n Write a function that takes two planet names as strings planet1 and planet2. \n The function should return a tuple containing all planets whose orbits are \n located between the orbit of planet1 and the orbit of planet2, sorted by \n the proximity to the sun. \n The function should return an empty tuple if planet1 or planet2\n are not correct planet names. \n Examples\n bf(\"Jupiter\", \"Neptune\") ==> (\"Saturn\", \"Uranus\")\n bf(\"Earth\", \"Mercury\") ==> (\"Venus\")\n bf(\"Mercury\", \"Uranus\") ==> (\"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\")\n '''\n", "entry_point": "bf", "canonical_solution": " planet_names = (\"Mercury\", \"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\", \"Uranus\", \"Neptune\")\n if planet1 not in planet_names or planet2 not in planet_names or planet1 == planet2:\n return ()\n planet1_index = planet_names.index(planet1)\n planet2_index = planet_names.index(planet2)\n if planet1_index < planet2_index:\n return (planet_names[planet1_index + 1: planet2_index])\n else:\n return (planet_names[planet2_index + 1 : planet1_index])\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"Jupiter\", \"Neptune\") == (\"Saturn\", \"Uranus\"), \"First test error: \" + str(len(candidate(\"Jupiter\", \"Neptune\"))) \n assert candidate(\"Earth\", \"Mercury\") == (\"Venus\",), \"Second test error: \" + str(candidate(\"Earth\", \"Mercury\")) \n assert candidate(\"Mercury\", \"Uranus\") == (\"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\"), \"Third test error: \" + str(candidate(\"Mercury\", \"Uranus\")) \n assert candidate(\"Neptune\", \"Venus\") == (\"Earth\", \"Mars\", \"Jupiter\", \"Saturn\", \"Uranus\"), \"Fourth test error: \" + str(candidate(\"Neptune\", \"Venus\")) \n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(\"Earth\", \"Earth\") == ()\n assert candidate(\"Mars\", \"Earth\") == ()\n assert candidate(\"Jupiter\", \"Makemake\") == ()\n\n"}
{"task_id": "HumanEval/149", "prompt": "\ndef sorted_list_sum(lst):\n \"\"\"Write a function that accepts a list of strings as a parameter,\n deletes the strings that have odd lengths from it,\n and returns the resulted list with a sorted order,\n The list is always a list of strings and never an array of numbers,\n and it may contain duplicates.\n The order of the list should be ascending by length of each word, and you\n should return the list sorted by that rule.\n If two words have the same length, sort the list alphabetically.\n The function should return a list of strings in sorted order.\n You may assume that all words will have the same length.\n For example:\n assert list_sort([\"aa\", \"a\", \"aaa\"]) => [\"aa\"]\n assert list_sort([\"ab\", \"a\", \"aaa\", \"cd\"]) => [\"ab\", \"cd\"]\n \"\"\"\n", "entry_point": "sorted_list_sum", "canonical_solution": " lst.sort()\n new_lst = []\n for i in lst:\n if len(i)%2 == 0:\n new_lst.append(i)\n return sorted(new_lst, key=len)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([\"aa\", \"a\", \"aaa\"]) == [\"aa\"]\n assert candidate([\"school\", \"AI\", \"asdf\", \"b\"]) == [\"AI\", \"asdf\", \"school\"]\n assert candidate([\"d\", \"b\", \"c\", \"a\"]) == []\n assert candidate([\"d\", \"dcba\", \"abcd\", \"a\"]) == [\"abcd\", \"dcba\"]\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([\"AI\", \"ai\", \"au\"]) == [\"AI\", \"ai\", \"au\"]\n assert candidate([\"a\", \"b\", \"b\", \"c\", \"c\", \"a\"]) == []\n assert candidate(['aaaa', 'bbbb', 'dd', 'cc']) == [\"cc\", \"dd\", \"aaaa\", \"bbbb\"]\n\n"}
{"task_id": "HumanEval/150", "prompt": "\ndef x_or_y(n, x, y):\n \"\"\"A simple program which should return the value of x if n is \n a prime number and should return the value of y otherwise.\n\n Examples:\n for x_or_y(7, 34, 12) == 34\n for x_or_y(15, 8, 5) == 5\n \n \"\"\"\n", "entry_point": "x_or_y", "canonical_solution": " if n == 1:\n return y\n for i in range(2, n):\n if n % i == 0:\n return y\n break\n else:\n return x\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(7, 34, 12) == 34\n assert candidate(15, 8, 5) == 5\n assert candidate(3, 33, 5212) == 33\n assert candidate(1259, 3, 52) == 3\n assert candidate(7919, -1, 12) == -1\n assert candidate(3609, 1245, 583) == 583\n assert candidate(91, 56, 129) == 129\n assert candidate(6, 34, 1234) == 1234\n \n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(1, 2, 0) == 0\n assert candidate(2, 2, 0) == 2\n\n"}
{"task_id": "HumanEval/151", "prompt": "\ndef double_the_difference(lst):\n '''\n Given a list of numbers, return the sum of squares of the numbers\n in the list that are odd. Ignore numbers that are negative or not integers.\n \n double_the_difference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10\n double_the_difference([-1, -2, 0]) == 0\n double_the_difference([9, -2]) == 81\n double_the_difference([0]) == 0 \n \n If the input list is empty, return 0.\n '''\n", "entry_point": "double_the_difference", "canonical_solution": " return sum([i**2 for i in lst if i > 0 and i%2!=0 and \".\" not in str(i)])\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([]) == 0 , \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([5, 4]) == 25 , \"This prints if this assert fails 2 (good for debugging!)\"\n assert candidate([0.1, 0.2, 0.3]) == 0 , \"This prints if this assert fails 3 (good for debugging!)\"\n assert candidate([-10, -20, -30]) == 0 , \"This prints if this assert fails 4 (good for debugging!)\"\n\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate([-1, -2, 8]) == 0, \"This prints if this assert fails 5 (also good for debugging!)\"\n assert candidate([0.2, 3, 5]) == 34, \"This prints if this assert fails 6 (also good for debugging!)\"\n lst = list(range(-99, 100, 2))\n odd_sum = sum([i**2 for i in lst if i%2!=0 and i > 0])\n assert candidate(lst) == odd_sum , \"This prints if this assert fails 7 (good for debugging!)\"\n\n"}
{"task_id": "HumanEval/152", "prompt": "\ndef compare(game,guess):\n \"\"\"I think we all remember that feeling when the result of some long-awaited\n event is finally known. The feelings and thoughts you have at that moment are\n definitely worth noting down and comparing.\n Your task is to determine if a person correctly guessed the results of a number of matches.\n You are given two arrays of scores and guesses of equal length, where each index shows a match. \n Return an array of the same length denoting how far off each guess was. If they have guessed correctly,\n the value is 0, and if not, the value is the absolute difference between the guess and the score.\n \n \n example:\n\n compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3]\n compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6]\n \"\"\"\n", "entry_point": "compare", "canonical_solution": " return [abs(x-y) for x,y in zip(game,guess)]\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate([1,2,3,4,5,1],[1,2,3,4,2,-2])==[0,0,0,0,3,3], \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([0,0,0,0,0,0],[0,0,0,0,0,0])==[0,0,0,0,0,0], \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([1,2,3],[-1,-2,-3])==[2,4,6], \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate([1,2,3,5],[-1,2,3,4])==[2,0,0,1], \"This prints if this assert fails 1 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/153", "prompt": "\ndef Strongest_Extension(class_name, extensions):\n \"\"\"You will be given the name of a class (a string) and a list of extensions.\n The extensions are to be used to load additional classes to the class. The\n strength of the extension is as follows: Let CAP be the number of the uppercase\n letters in the extension's name, and let SM be the number of lowercase letters \n in the extension's name, the strength is given by the fraction CAP - SM. \n You should find the strongest extension and return a string in this \n format: ClassName.StrongestExtensionName.\n If there are two or more extensions with the same strength, you should\n choose the one that comes first in the list.\n For example, if you are given \"Slices\" as the class and a list of the\n extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should\n return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension \n (its strength is -1).\n Example:\n for Strongest_Extension('my_class', ['AA', 'Be', 'CC']) == 'my_class.AA'\n \"\"\"\n", "entry_point": "Strongest_Extension", "canonical_solution": " strong = extensions[0]\n my_val = len([x for x in extensions[0] if x.isalpha() and x.isupper()]) - len([x for x in extensions[0] if x.isalpha() and x.islower()])\n for s in extensions:\n val = len([x for x in s if x.isalpha() and x.isupper()]) - len([x for x in s if x.isalpha() and x.islower()])\n if val > my_val:\n strong = s\n my_val = val\n\n ans = class_name + \".\" + strong\n return ans\n\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate('Watashi', ['tEN', 'niNE', 'eIGHt8OKe']) == 'Watashi.eIGHt8OKe'\n assert candidate('Boku123', ['nani', 'NazeDa', 'YEs.WeCaNe', '32145tggg']) == 'Boku123.YEs.WeCaNe'\n assert candidate('__YESIMHERE', ['t', 'eMptY', 'nothing', 'zeR00', 'NuLl__', '123NoooneB321']) == '__YESIMHERE.NuLl__'\n assert candidate('K', ['Ta', 'TAR', 't234An', 'cosSo']) == 'K.TAR'\n assert candidate('__HAHA', ['Tab', '123', '781345', '-_-']) == '__HAHA.123'\n assert candidate('YameRore', ['HhAas', 'okIWILL123', 'WorkOut', 'Fails', '-_-']) == 'YameRore.okIWILL123'\n assert candidate('finNNalLLly', ['Die', 'NowW', 'Wow', 'WoW']) == 'finNNalLLly.WoW'\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate('_', ['Bb', '91245']) == '_.Bb'\n assert candidate('Sp', ['671235', 'Bb']) == 'Sp.671235'\n \n"}
{"task_id": "HumanEval/154", "prompt": "\ndef cycpattern_check(a , b):\n \"\"\"You are given 2 words. You need to return True if the second word or any of its rotations is a substring in the first word\n cycpattern_check(\"abcd\",\"abd\") => False\n cycpattern_check(\"hello\",\"ell\") => True\n cycpattern_check(\"whassup\",\"psus\") => False\n cycpattern_check(\"abab\",\"baa\") => True\n cycpattern_check(\"efef\",\"eeff\") => False\n cycpattern_check(\"himenss\",\"simen\") => True\n\n \"\"\"\n", "entry_point": "cycpattern_check", "canonical_solution": " l = len(b)\n pat = b + b\n for i in range(len(a) - l + 1):\n for j in range(l + 1):\n if a[i:i+l] == pat[j:j+l]:\n return True\n return False\n", "test": "def check(candidate):\n\n # Check some simple cases\n #assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n #assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate(\"xyzw\",\"xyw\") == False , \"test #0\"\n assert candidate(\"yello\",\"ell\") == True , \"test #1\"\n assert candidate(\"whattup\",\"ptut\") == False , \"test #2\"\n assert candidate(\"efef\",\"fee\") == True , \"test #3\"\n assert candidate(\"abab\",\"aabb\") == False , \"test #4\"\n assert candidate(\"winemtt\",\"tinem\") == True , \"test #5\"\n\n"}
{"task_id": "HumanEval/155", "prompt": "\ndef even_odd_count(num):\n \"\"\"Given an integer. return a tuple that has the number of even and odd digits respectively.\n\n Example:\n even_odd_count(-12) ==> (1, 1)\n even_odd_count(123) ==> (1, 2)\n \"\"\"\n", "entry_point": "even_odd_count", "canonical_solution": " even_count = 0\n odd_count = 0\n for i in str(abs(num)):\n if int(i)%2==0:\n even_count +=1\n else:\n odd_count +=1\n return (even_count, odd_count)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(7) == (0, 1)\n assert candidate(-78) == (1, 1)\n assert candidate(3452) == (2, 2)\n assert candidate(346211) == (3, 3)\n assert candidate(-345821) == (3, 3)\n assert candidate(-2) == (1, 0)\n assert candidate(-45347) == (2, 3)\n assert candidate(0) == (1, 0)\n\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/156", "prompt": "\ndef int_to_mini_roman(number):\n \"\"\"\n Given a positive integer, obtain its roman numeral equivalent as a string,\n and return it in lowercase.\n Restrictions: 1 <= num <= 1000\n\n Examples:\n >>> int_to_mini_roman(19) == 'xix'\n >>> int_to_mini_roman(152) == 'clii'\n >>> int_to_mini_roman(426) == 'cdxxvi'\n \"\"\"\n", "entry_point": "int_to_mini_roman", "canonical_solution": " num = [1, 4, 5, 9, 10, 40, 50, 90, \n 100, 400, 500, 900, 1000] \n sym = [\"I\", \"IV\", \"V\", \"IX\", \"X\", \"XL\", \n \"L\", \"XC\", \"C\", \"CD\", \"D\", \"CM\", \"M\"] \n i = 12\n res = ''\n while number: \n div = number // num[i] \n number %= num[i] \n while div: \n res += sym[i] \n div -= 1\n i -= 1\n return res.lower()\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(19) == 'xix'\n assert candidate(152) == 'clii'\n assert candidate(251) == 'ccli'\n assert candidate(426) == 'cdxxvi'\n assert candidate(500) == 'd'\n assert candidate(1) == 'i'\n assert candidate(4) == 'iv'\n assert candidate(43) == 'xliii'\n assert candidate(90) == 'xc'\n assert candidate(94) == 'xciv'\n assert candidate(532) == 'dxxxii'\n assert candidate(900) == 'cm'\n assert candidate(994) == 'cmxciv'\n assert candidate(1000) == 'm'\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/157", "prompt": "\ndef right_angle_triangle(a, b, c):\n '''\n Given the lengths of the three sides of a triangle. Return True if the three\n sides form a right-angled triangle, False otherwise.\n A right-angled triangle is a triangle in which one angle is right angle or \n 90 degree.\n Example:\n right_angle_triangle(3, 4, 5) == True\n right_angle_triangle(1, 2, 3) == False\n '''\n", "entry_point": "right_angle_triangle", "canonical_solution": " return a*a == b*b + c*c or b*b == a*a + c*c or c*c == a*a + b*b\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(3, 4, 5) == True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(1, 2, 3) == False\n assert candidate(10, 6, 8) == True\n assert candidate(2, 2, 2) == False\n assert candidate(7, 24, 25) == True\n assert candidate(10, 5, 7) == False\n assert candidate(5, 12, 13) == True\n assert candidate(15, 8, 17) == True\n assert candidate(48, 55, 73) == True\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(1, 1, 1) == False, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate(2, 2, 10) == False\n\n"}
{"task_id": "HumanEval/158", "prompt": "\ndef find_max(words):\n \"\"\"Write a function that accepts a list of strings.\n The list contains different words. Return the word with maximum number\n of unique characters. If multiple strings have maximum number of unique\n characters, return the one which comes first in lexicographical order.\n\n find_max([\"name\", \"of\", \"string\"]) == \"string\"\n find_max([\"name\", \"enam\", \"game\"]) == \"enam\"\n find_max([\"aaaaaaa\", \"bb\" ,\"cc\"]) == \"\"aaaaaaa\"\n \"\"\"\n", "entry_point": "find_max", "canonical_solution": " return sorted(words, key = lambda x: (-len(set(x)), x))[0]\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert (candidate([\"name\", \"of\", \"string\"]) == \"string\"), \"t1\"\n assert (candidate([\"name\", \"enam\", \"game\"]) == \"enam\"), 't2'\n assert (candidate([\"aaaaaaa\", \"bb\", \"cc\"]) == \"aaaaaaa\"), 't3'\n assert (candidate([\"abc\", \"cba\"]) == \"abc\"), 't4'\n assert (candidate([\"play\", \"this\", \"game\", \"of\",\"footbott\"]) == \"footbott\"), 't5'\n assert (candidate([\"we\", \"are\", \"gonna\", \"rock\"]) == \"gonna\"), 't6'\n assert (candidate([\"we\", \"are\", \"a\", \"mad\", \"nation\"]) == \"nation\"), 't7'\n assert (candidate([\"this\", \"is\", \"a\", \"prrk\"]) == \"this\"), 't8'\n\n # Check some edge cases that are easy to work out by hand.\n assert (candidate([\"b\"]) == \"b\"), 't9'\n assert (candidate([\"play\", \"play\", \"play\"]) == \"play\"), 't10'\n\n"}
{"task_id": "HumanEval/159", "prompt": "\ndef eat(number, need, remaining):\n \"\"\"\n You're a hungry rabbit, and you already have eaten a certain number of carrots,\n but now you need to eat more carrots to complete the day's meals.\n you should return an array of [ total number of eaten carrots after your meals,\n the number of carrots left after your meals ]\n if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n \n Example:\n * eat(5, 6, 10) -> [11, 4]\n * eat(4, 8, 9) -> [12, 1]\n * eat(1, 10, 10) -> [11, 0]\n * eat(2, 11, 5) -> [7, 0]\n \n Variables:\n @number : integer\n the number of carrots that you have eaten.\n @need : integer\n the number of carrots that you need to eat.\n @remaining : integer\n the number of remaining carrots thet exist in stock\n \n Constrain:\n * 0 <= number <= 1000\n * 0 <= need <= 1000\n * 0 <= remaining <= 1000\n\n Have fun :)\n \"\"\"\n", "entry_point": "eat", "canonical_solution": " if(need <= remaining):\n return [ number + need , remaining-need ]\n else:\n return [ number + remaining , 0]\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert True, \"This prints if this assert fails 1 (good for debugging!)\"\n assert candidate(5, 6, 10) == [11, 4], \"Error\"\n assert candidate(4, 8, 9) == [12, 1], \"Error\"\n assert candidate(1, 10, 10) == [11, 0], \"Error\"\n assert candidate(2, 11, 5) == [7, 0], \"Error\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n assert candidate(4, 5, 7) == [9, 2], \"Error\"\n assert candidate(4, 5, 1) == [5, 0], \"Error\"\n\n"}
{"task_id": "HumanEval/160", "prompt": "\ndef do_algebra(operator, operand):\n \"\"\"\n Given two lists operator, and operand. The first list has basic algebra operations, and \n the second list is a list of integers. Use the two given lists to build the algebric \n expression and return the evaluation of this expression.\n\n The basic algebra operations:\n Addition ( + ) \n Subtraction ( - ) \n Multiplication ( * ) \n Floor division ( // ) \n Exponentiation ( ** ) \n\n Example:\n operator['+', '*', '-']\n array = [2, 3, 4, 5]\n result = 2 + 3 * 4 - 5\n => result = 9\n\n Note:\n The length of operator list is equal to the length of operand list minus one.\n Operand is a list of of non-negative integers.\n Operator list has at least one operator, and operand list has at least two operands.\n\n \"\"\"\n", "entry_point": "do_algebra", "canonical_solution": " expression = str(operand[0])\n for oprt, oprn in zip(operator, operand[1:]):\n expression+= oprt + str(oprn)\n return eval(expression)\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(['**', '*', '+'], [2, 3, 4, 5]) == 37\n assert candidate(['+', '*', '-'], [2, 3, 4, 5]) == 9\n assert candidate(['//', '*'], [7, 3, 4]) == 8, \"This prints if this assert fails 1 (good for debugging!)\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}
{"task_id": "HumanEval/161", "prompt": "\ndef solve(s):\n \"\"\"You are given a string s.\n if s[i] is a letter, reverse its case from lower to upper or vise versa, \n otherwise keep it as it is.\n If the string contains no letters, reverse the string.\n The function should return the resulted string.\n Examples\n solve(\"1234\") = \"4321\"\n solve(\"ab\") = \"AB\"\n solve(\"#a@C\") = \"#A@c\"\n \"\"\"\n", "entry_point": "solve", "canonical_solution": " flg = 0\n idx = 0\n new_str = list(s)\n for i in s:\n if i.isalpha():\n new_str[idx] = i.swapcase()\n flg = 1\n idx += 1\n s = \"\"\n for i in new_str:\n s += i\n if flg == 0:\n return s[len(s)::-1]\n return s\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(\"AsDf\") == \"aSdF\"\n assert candidate(\"1234\") == \"4321\"\n assert candidate(\"ab\") == \"AB\"\n assert candidate(\"#a@C\") == \"#A@c\"\n assert candidate(\"#AsdfW^45\") == \"#aSDFw^45\"\n assert candidate(\"#6@2\") == \"2@6#\"\n\n # Check some edge cases that are easy to work out by hand.\n assert candidate(\"#$a^D\") == \"#$A^d\"\n assert candidate(\"#ccc\") == \"#CCC\"\n\n # Don't remove this line:\n"}
{"task_id": "HumanEval/162", "prompt": "\ndef string_to_md5(text):\n \"\"\"\n Given a string 'text', return its md5 hash equivalent string.\n If 'text' is an empty string, return None.\n\n >>> string_to_md5('Hello world') == '3e25960a79dbc69b674cd4ec67a72c62'\n \"\"\"\n", "entry_point": "string_to_md5", "canonical_solution": " import hashlib\n return hashlib.md5(text.encode('ascii')).hexdigest() if text else None\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate('Hello world') == '3e25960a79dbc69b674cd4ec67a72c62'\n assert candidate('') == None\n assert candidate('A B C') == '0ef78513b0cb8cef12743f5aeb35f888'\n assert candidate('password') == '5f4dcc3b5aa765d61d8327deb882cf99'\n\n # Check some edge cases that are easy to work out by hand.\n assert True\n\n"}
{"task_id": "HumanEval/163", "prompt": "\ndef generate_integers(a, b):\n \"\"\"\n Given two positive integers a and b, return the even digits between a\n and b, in ascending order.\n\n For example:\n generate_integers(2, 8) => [2, 4, 6, 8]\n generate_integers(8, 2) => [2, 4, 6, 8]\n generate_integers(10, 14) => []\n \"\"\"\n", "entry_point": "generate_integers", "canonical_solution": " lower = max(2, min(a, b))\n upper = min(8, max(a, b))\n\n return [i for i in range(lower, upper+1) if i % 2 == 0]\n", "test": "def check(candidate):\n\n # Check some simple cases\n assert candidate(2, 10) == [2, 4, 6, 8], \"Test 1\"\n assert candidate(10, 2) == [2, 4, 6, 8], \"Test 2\"\n assert candidate(132, 2) == [2, 4, 6, 8], \"Test 3\"\n assert candidate(17,89) == [], \"Test 4\"\n\n # Check some edge cases that are easy to work out by hand.\n assert True, \"This prints if this assert fails 2 (also good for debugging!)\"\n\n"}

View File

@@ -0,0 +1,10 @@
{
"name": "SWE-bench Lite",
"version": "1.0",
"description": "300 real-world GitHub issues for evaluation",
"source": "https://github.com/SWE-bench/SWE-bench",
"problems": 300,
"status": "PLACEHOLDER",
"install_command": "pip install swebench",
"run_command": "python -m swebench.harness.run_evaluation"
}

View File

@@ -0,0 +1,215 @@
#!/bin/bash
#===============================================================================
# Prepare SWE-bench Submission
# Converts benchmark results to official SWE-bench submission format
#
# Usage:
# ./benchmarks/prepare-submission.sh <results-dir>
# ./benchmarks/prepare-submission.sh benchmarks/results/2026-01-05-10-37-54
#
# Output:
# Creates submission-ready folder at benchmarks/submission/
#===============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m'
log_info() { echo -e "${CYAN}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[PASS]${NC} $1"; }
log_error() { echo -e "${RED}[FAIL]${NC} $1"; }
if [ $# -lt 1 ]; then
echo "Usage: $0 <results-directory>"
echo "Example: $0 benchmarks/results/2026-01-05-10-37-54"
exit 1
fi
RESULTS_DIR="$1"
SUBMISSION_DATE=$(date +%Y%m%d)
SUBMISSION_DIR="$SCRIPT_DIR/submission/${SUBMISSION_DATE}_loki_mode"
log_info "Preparing SWE-bench submission..."
log_info "Results: $RESULTS_DIR"
log_info "Output: $SUBMISSION_DIR"
# Check results directory
if [ ! -d "$RESULTS_DIR" ]; then
log_error "Results directory not found: $RESULTS_DIR"
exit 1
fi
# Check for required files
if [ ! -f "$RESULTS_DIR/swebench-loki-predictions.json" ]; then
log_error "Predictions file not found: $RESULTS_DIR/swebench-loki-predictions.json"
exit 1
fi
# Create submission directory
mkdir -p "$SUBMISSION_DIR"
# Copy template files
log_info "Copying template files..."
cp "$SCRIPT_DIR/submission-template/README.md" "$SUBMISSION_DIR/"
cp "$SCRIPT_DIR/submission-template/metadata.yaml" "$SUBMISSION_DIR/"
# Convert predictions to JSONL format
log_info "Converting predictions to JSONL format..."
python3 << CONVERT_PREDS
import json
with open("$RESULTS_DIR/swebench-loki-predictions.json", 'r') as f:
predictions = json.load(f)
with open("$SUBMISSION_DIR/all_preds.jsonl", 'w') as f:
for pred in predictions:
# Format required by SWE-bench
entry = {
"instance_id": pred["instance_id"],
"model_patch": pred["model_patch"],
"model_name_or_path": pred.get("model_name_or_path", "loki-mode")
}
f.write(json.dumps(entry) + '\n')
print(f"Converted {len(predictions)} predictions to JSONL format")
CONVERT_PREDS
# Copy trajectories if they exist
if [ -d "$RESULTS_DIR/trajs" ]; then
log_info "Copying trajectory files..."
cp -r "$RESULTS_DIR/trajs" "$SUBMISSION_DIR/"
TRAJ_COUNT=$(ls -1 "$SUBMISSION_DIR/trajs" 2>/dev/null | wc -l | tr -d ' ')
log_success "Copied $TRAJ_COUNT trajectory files"
else
log_info "No trajectory files found (run benchmark with --loki for trajectory logging)"
mkdir -p "$SUBMISSION_DIR/trajs"
fi
# Copy logs if they exist
if [ -d "$RESULTS_DIR/logs" ]; then
log_info "Copying log files..."
cp -r "$RESULTS_DIR/logs" "$SUBMISSION_DIR/"
LOG_COUNT=$(ls -1 "$SUBMISSION_DIR/logs" 2>/dev/null | wc -l | tr -d ' ')
log_success "Copied $LOG_COUNT log directories"
else
log_info "No log files found (run benchmark with --loki for log capture)"
mkdir -p "$SUBMISSION_DIR/logs"
fi
# Update metadata with actual results
log_info "Updating metadata with actual results..."
python3 << UPDATE_META
import json
import yaml
from datetime import datetime
# Load results
with open("$RESULTS_DIR/swebench-loki-results.json", 'r') as f:
results = json.load(f)
# Load metadata template
with open("$SUBMISSION_DIR/metadata.yaml", 'r') as f:
metadata = yaml.safe_load(f)
# Update with actual results
metadata['results'] = {
'patch_generation_rate': round((results.get('generated', 0) / results.get('total_problems', 1)) * 100, 2),
'problems_solved': results.get('generated', 0),
'problems_total': results.get('total_problems', 0),
'fixed_by_rarv': results.get('fixed_by_rarv', 0),
'avg_attempts': round(results.get('avg_attempts', 1.0), 2),
'total_time_seconds': round(results.get('elapsed_time', 0)),
'avg_time_per_problem_seconds': round(results.get('elapsed_time', 0) / max(results.get('total_problems', 1), 1))
}
metadata['submission']['date'] = datetime.now().strftime('%Y-%m-%d')
# Save updated metadata
with open("$SUBMISSION_DIR/metadata.yaml", 'w') as f:
yaml.dump(metadata, f, default_flow_style=False, sort_keys=False)
print("Metadata updated with actual results")
CONVERT_PREDS
# Generate submission summary
log_info "Generating submission summary..."
cat > "$SUBMISSION_DIR/SUBMISSION_CHECKLIST.md" << 'CHECKLIST'
# SWE-bench Submission Checklist
## Required Files
- [x] all_preds.jsonl - Predictions in JSONL format
- [x] README.md - Description of the system
- [x] metadata.yaml - Submission metadata
## Optional but Recommended
- [ ] trajs/ - Reasoning trajectories (required for some leaderboards)
- [ ] logs/ - Execution logs
## Pre-Submission Steps
1. **Verify predictions format:**
```bash
head -1 all_preds.jsonl | python -m json.tool
```
2. **Run SWE-bench evaluator (optional but recommended):**
```bash
python -m swebench.harness.run_evaluation \
--predictions all_preds.jsonl \
--max_workers 4 \
--run_id loki_mode_v2.25.0
```
3. **Fork and create PR:**
```bash
# Fork https://github.com/SWE-bench/experiments
# Clone your fork
git clone https://github.com/YOUR_USERNAME/experiments.git
cd experiments
# Copy submission
cp -r /path/to/submission evaluation/lite/20260105_loki_mode
# Create PR
git checkout -b loki-mode-submission
git add .
git commit -m "Add Loki Mode submission"
git push origin loki-mode-submission
```
4. **Submit PR with:**
- Link to this repository
- Brief description of the system
- Any relevant benchmark methodology notes
## Contact
For questions about this submission, open an issue at:
https://github.com/asklokesh/loki-mode/issues
CHECKLIST
# Final summary
echo ""
echo "======================================================================"
echo " SUBMISSION PREPARED"
echo "======================================================================"
echo " Location: $SUBMISSION_DIR"
echo ""
echo " Files:"
ls -la "$SUBMISSION_DIR/"
echo ""
echo " Next Steps:"
echo " 1. Review all_preds.jsonl format"
echo " 2. Run SWE-bench evaluator (optional)"
echo " 3. Fork SWE-bench/experiments"
echo " 4. Copy submission folder to evaluation/lite/"
echo " 5. Create pull request"
echo "======================================================================"
log_success "Submission preparation complete!"

View File

@@ -0,0 +1,48 @@
# Loki Mode Benchmark Results
## Overview
This directory contains benchmark results for Loki Mode multi-agent system.
## Benchmarks Available
### HumanEval
- **Problems:** 164 Python programming problems
- **Metric:** Pass@1 (percentage of problems solved on first attempt)
- **Competitor Baseline:** MetaGPT achieves 85.9-87.7%
### SWE-bench Lite
- **Problems:** 300 real-world GitHub issues
- **Metric:** Resolution rate
- **Competitor Baseline:** Top agents achieve 45-77%
## Running Benchmarks
```bash
# Run all benchmarks
./benchmarks/run-benchmarks.sh all
# Run specific benchmark
./benchmarks/run-benchmarks.sh humaneval --execute
./benchmarks/run-benchmarks.sh swebench --execute
```
## Results Format
Results are saved as JSON files with:
- Timestamp
- Problem count
- Pass rate
- Individual problem results
- Token usage
- Execution time
## Methodology
Loki Mode uses its multi-agent architecture to solve each problem:
1. **Architect Agent** analyzes the problem
2. **Engineer Agent** implements the solution
3. **QA Agent** validates with test cases
4. **Review Agent** checks code quality
This mirrors real-world software development more accurately than single-agent approaches.

View File

@@ -0,0 +1,15 @@
{
"benchmark": "HumanEval",
"version": "1.0",
"timestamp": "2026-01-05T00:24:04.904083",
"total_problems": 164,
"status": "INFRASTRUCTURE_READY",
"note": "Benchmark infrastructure created. Run with --execute to run actual tests.",
"sample_problems": [
"HumanEval/0",
"HumanEval/1",
"HumanEval/2",
"HumanEval/3",
"HumanEval/4"
]
}

View File

@@ -0,0 +1,10 @@
{
"benchmark": "SWE-bench Lite",
"version": "1.0",
"timestamp": "2026-01-05T00:24:04.950779",
"total_problems": 300,
"status": "INFRASTRUCTURE_READY",
"note": "Benchmark infrastructure created. Install swebench package for full evaluation.",
"install": "pip install swebench",
"evaluation": "python -m swebench.harness.run_evaluation --predictions predictions.json"
}

View File

@@ -0,0 +1,50 @@
# Loki Mode Benchmark Results
**Generated:** 2026-01-05 01:10:21
## Overview
This directory contains benchmark results for Loki Mode multi-agent system.
## HumanEval Results
| Metric | Value |
|--------|-------|
| Problems | 164 |
| Passed | 161 |
| Failed | 3 |
| **Pass Rate** | **98.17%** |
| Model | opus |
| Time | 1263.46s |
### Competitor Comparison
| System | Pass@1 |
|--------|--------|
| MetaGPT | 85.9-87.7% |
| **Loki Mode** | **98.17%** |
## Methodology
Loki Mode uses its multi-agent architecture to solve each problem:
1. **Architect Agent** analyzes the problem
2. **Engineer Agent** implements the solution
3. **QA Agent** validates with test cases
4. **Review Agent** checks code quality
This mirrors real-world software development more accurately than single-agent approaches.
## Running Benchmarks
```bash
# Setup only (download datasets)
./benchmarks/run-benchmarks.sh all
# Execute with Claude
./benchmarks/run-benchmarks.sh humaneval --execute
./benchmarks/run-benchmarks.sh humaneval --execute --limit 10 # First 10 only
./benchmarks/run-benchmarks.sh swebench --execute --limit 5 # First 5 only
# Use different model
./benchmarks/run-benchmarks.sh humaneval --execute --model opus
```

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
from typing import List
def has_close_elements(numbers: List[float], threshold: float) -> bool:
""" Check if in given list of numbers, are any two numbers closer to each other than
given threshold.
>>> has_close_elements([1.0, 2.0, 3.0], 0.5)
False
>>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)
True
"""
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if abs(numbers[i] - numbers[j]) < threshold:
return True
return False

View File

@@ -0,0 +1,28 @@
from typing import List
def separate_paren_groups(paren_string: str) -> List[str]:
""" Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
separate those group into separate strings and return the list of those.
Separate groups are balanced (each open brace is properly closed) and not nested within each other
Ignore any spaces in the input string.
>>> separate_paren_groups('( ) (( )) (( )( ))')
['()', '(())', '(()())']
"""
paren_string = paren_string.replace(' ', '')
result = []
current_group = ''
depth = 0
for char in paren_string:
if char == '(':
depth += 1
current_group += char
elif char == ')':
depth -= 1
current_group += char
if depth == 0:
result.append(current_group)
current_group = ''
return result

View File

@@ -0,0 +1,25 @@
def is_palindrome(string: str) -> bool:
""" Test if given string is a palindrome """
return string == string[::-1]
def make_palindrome(string: str) -> str:
""" Find the shortest palindrome that begins with a supplied string.
Algorithm idea is simple:
- Find the longest postfix of supplied string that is a palindrome.
- Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
>>> make_palindrome('')
''
>>> make_palindrome('cat')
'catac'
>>> make_palindrome('cata')
'catac'
"""
if not string:
return ''
for i in range(len(string)):
if is_palindrome(string[i:]):
return string + string[:i][::-1]
return string

View File

@@ -0,0 +1,20 @@
def make_a_pile(n):
"""
Given a positive integer n, you have to make a pile of n levels of stones.
The first level has n stones.
The number of stones in the next level is:
- the next odd number if n is odd.
- the next even number if n is even.
Return the number of stones in each level in a list, where element at index
i represents the number of stones in the level (i+1).
Examples:
>>> make_a_pile(3)
[3, 5, 7]
"""
result = []
current = n
for _ in range(n):
result.append(current)
current += 2
return result

View File

@@ -0,0 +1,15 @@
def words_string(s):
"""
You will be given a string of words separated by commas or spaces. Your task is
to split the string into words and return an array of the words.
For example:
words_string("Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
words_string("One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
"""
if not s:
return []
# Replace commas with spaces, then split on whitespace
s = s.replace(',', ' ')
return s.split()

View File

@@ -0,0 +1,16 @@
def choose_num(x, y):
"""This function takes two positive numbers x and y and returns the
biggest even integer number that is in the range [x, y] inclusive. If
there's no such number, then the function should return -1.
For example:
choose_num(12, 15) = 14
choose_num(13, 12) = -1
"""
if x > y:
return -1
if y % 2 == 0:
return y
if y - 1 >= x:
return y - 1
return -1

View File

@@ -0,0 +1,15 @@
def rounded_avg(n, m):
"""You are given two positive integers n and m, and your task is to compute the
average of the integers from n through m (including n and m).
Round the answer to the nearest integer and convert that to binary.
If n is greater than m, return -1.
Example:
rounded_avg(1, 5) => "0b11"
rounded_avg(7, 5) => -1
rounded_avg(10, 20) => "0b1111"
rounded_avg(20, 33) => "0b11010"
"""
if n > m:
return -1
avg = round((n + m) / 2)
return bin(avg)

View File

@@ -0,0 +1,22 @@
def unique_digits(x):
"""Given a list of positive integers x. return a sorted list of all
elements that hasn't any even digit.
Note: Returned list should be sorted in increasing order.
For example:
>>> unique_digits([15, 33, 1422, 1])
[1, 15, 33]
>>> unique_digits([152, 323, 1422, 10])
[]
"""
def has_even_digit(n):
while n > 0:
digit = n % 10
if digit % 2 == 0:
return True
n //= 10
return False
result = [num for num in x if not has_even_digit(num)]
return sorted(result)

View File

@@ -0,0 +1,39 @@
def by_length(arr):
"""
Given an array of integers, sort the integers that are between 1 and 9 inclusive,
reverse the resulting array, and then replace each digit by its corresponding name from
"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
For example:
arr = [2, 1, 1, 4, 5, 8, 2, 3]
-> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8]
-> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1]
return ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
If the array is empty, return an empty array:
arr = []
return []
If the array has any strange number ignore it:
arr = [1, -1 , 55]
-> sort arr -> [-1, 1, 55]
-> reverse arr -> [55, 1, -1]
return = ['One']
"""
names = {
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Seven",
8: "Eight",
9: "Nine"
}
filtered = [x for x in arr if 1 <= x <= 9]
filtered.sort()
filtered.reverse()
return [names[x] for x in filtered]

View File

@@ -0,0 +1,21 @@
def f(n):
""" Implement the function f that takes n as a parameter,
and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even
or the sum of numbers from 1 to i otherwise.
i starts from 1.
the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
Example:
f(5) == [1, 2, 6, 24, 15]
"""
result = []
for i in range(1, n + 1):
if i % 2 == 0:
# factorial of i
factorial = 1
for j in range(1, i + 1):
factorial *= j
result.append(factorial)
else:
# sum of numbers from 1 to i
result.append(sum(range(1, i + 1)))
return result

View File

@@ -0,0 +1,35 @@
def even_odd_palindrome(n):
"""
Given a positive integer n, return a tuple that has the number of even and odd
integer palindromes that fall within the range(1, n), inclusive.
Example 1:
Input: 3
Output: (1, 2)
Explanation:
Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
Example 2:
Input: 12
Output: (4, 6)
Explanation:
Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
Note:
1. 1 <= n <= 10^3
2. returned tuple has the number of even and odd integer palindromes respectively.
"""
even_count = 0
odd_count = 0
for i in range(1, n + 1):
s = str(i)
if s == s[::-1]:
if i % 2 == 0:
even_count += 1
else:
odd_count += 1
return (even_count, odd_count)

View File

@@ -0,0 +1,22 @@
def count_nums(arr):
"""
Write a function count_nums which takes an array of integers and returns
the number of elements which has a sum of digits > 0.
If a number is negative, then its first signed digit will be negative:
e.g. -123 has signed digits -1, 2, and 3.
>>> count_nums([]) == 0
>>> count_nums([-1, 11, -11]) == 1
>>> count_nums([1, 1, 2]) == 3
"""
count = 0
for num in arr:
if num == 0:
continue
elif num > 0:
digit_sum = sum(int(d) for d in str(num))
else:
s = str(abs(num))
digit_sum = -int(s[0]) + sum(int(d) for d in s[1:])
if digit_sum > 0:
count += 1
return count

View File

@@ -0,0 +1,41 @@
def move_one_ball(arr):
"""We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
numbers in the array will be randomly ordered. Your task is to determine if
it is possible to get an array sorted in non-decreasing order by performing
the following operation on the given array:
You are allowed to perform right shift operation any number of times.
One right shift operation means shifting all elements of the array by one
position in the right direction. The last element of the array will be moved to
the starting position in the array i.e. 0th index.
If it is possible to obtain the sorted array by performing the above operation
then return True else return False.
If the given array is empty then return True.
Note: The given list is guaranteed to have unique elements.
For Example:
move_one_ball([3, 4, 5, 1, 2])==>True
Explanation: By performin 2 right shift operations, non-decreasing order can
be achieved for the given array.
move_one_ball([3, 5, 4, 1, 2])==>False
Explanation:It is not possible to get non-decreasing order for the given
array by performing any number of right shift operations.
"""
if len(arr) == 0:
return True
# Count the number of "breaks" where arr[i] > arr[i+1]
# For a rotated sorted array, there should be at most one such break
breaks = 0
n = len(arr)
for i in range(n):
if arr[i] > arr[(i + 1) % n]:
breaks += 1
# If there's at most one break, the array can be sorted by rotation
return breaks <= 1

View File

@@ -0,0 +1,16 @@
from typing import List
def string_xor(a: str, b: str) -> str:
""" Input are two strings a and b consisting only of 1s and 0s.
Perform binary XOR on these inputs and return result also as a string.
>>> string_xor('010', '110')
'100'
"""
result = []
for char_a, char_b in zip(a, b):
if char_a == char_b:
result.append('0')
else:
result.append('1')
return ''.join(result)

View File

@@ -0,0 +1,20 @@
def exchange(lst1, lst2):
"""In this problem, you will implement a function that takes two lists of numbers,
and determines whether it is possible to perform an exchange of elements
between them to make lst1 a list of only even numbers.
There is no limit on the number of exchanged elements between lst1 and lst2.
If it is possible to exchange elements between the lst1 and lst2 to make
all the elements of lst1 to be even, return "YES".
Otherwise, return "NO".
For example:
exchange([1, 2, 3, 4], [1, 2, 3, 4]) => "YES"
exchange([1, 2, 3, 4], [1, 5, 3, 4]) => "NO"
It is assumed that the input lists will be non-empty.
"""
odd_count_lst1 = sum(1 for x in lst1 if x % 2 != 0)
even_count_lst2 = sum(1 for x in lst2 if x % 2 == 0)
if even_count_lst2 >= odd_count_lst1:
return "YES"
else:
return "NO"

View File

@@ -0,0 +1,28 @@
def histogram(test):
"""Given a string representing a space separated lowercase letters, return a dictionary
of the letter with the most repetition and containing the corresponding count.
If several letters have the same occurrence, return all of them.
Example:
histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}
histogram('a b b a') == {'a': 2, 'b': 2}
histogram('a b c a b') == {'a': 2, 'b': 2}
histogram('b b b b a') == {'b': 4}
histogram('') == {}
"""
if not test or test.strip() == '':
return {}
letters = test.split()
counts = {}
for letter in letters:
counts[letter] = counts.get(letter, 0) + 1
if not counts:
return {}
max_count = max(counts.values())
return {letter: count for letter, count in counts.items() if count == max_count}

View File

@@ -0,0 +1,14 @@
def reverse_delete(s,c):
"""Task
We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
then check if the result string is palindrome.
A string is called palindrome if it reads the same backward as forward.
You should return a tuple containing the result string and True/False for the check.
Example
For s = "abcde", c = "ae", the result should be ('bcd',False)
For s = "abcdef", c = "b" the result should be ('acdef',False)
For s = "abcdedcba", c = "ab", the result should be ('cdedc',True)
"""
result = ''.join(char for char in s if char not in c)
is_palindrome = result == result[::-1]
return (result, is_palindrome)

View File

@@ -0,0 +1,19 @@
def odd_count(lst):
"""Given a list of strings, where each string consists of only digits, return a list.
Each element i of the output should be "the number of odd elements in the
string i of the input." where all the i's should be replaced by the number
of odd digits in the i'th string of the input.
>>> odd_count(['1234567'])
["the number of odd elements 4n the str4ng 4 of the 4nput."]
>>> odd_count(['3',"11111111"])
["the number of odd elements 1n the str1ng 1 of the 1nput.",
"the number of odd elements 8n the str8ng 8 of the 8nput."]
"""
result = []
for s in lst:
count = sum(1 for c in s if c in '13579')
template = "the number of odd elements in the string i of the input."
replaced = template.replace('i', str(count))
result.append(replaced)
return result

View File

@@ -0,0 +1,16 @@
def minSubArraySum(nums):
"""
Given an array of integers nums, find the minimum sum of any non-empty sub-array
of nums.
Example
minSubArraySum([2, 3, 4, 1, 2, 4]) == 1
minSubArraySum([-1, -2, -3]) == -6
"""
min_sum = nums[0]
current_sum = nums[0]
for i in range(1, len(nums)):
current_sum = min(nums[i], current_sum + nums[i])
min_sum = min(min_sum, current_sum)
return min_sum

View File

@@ -0,0 +1,41 @@
def max_fill(grid, capacity):
import math
"""
You are given a rectangular grid of wells. Each row represents a single well,
and each 1 in a row represents a single unit of water.
Each well has a corresponding bucket that can be used to extract water from it,
and all buckets have the same capacity.
Your task is to use the buckets to empty the wells.
Output the number of times you need to lower the buckets.
Example 1:
Input:
grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]
bucket_capacity : 1
Output: 6
Example 2:
Input:
grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]
bucket_capacity : 2
Output: 5
Example 3:
Input:
grid : [[0,0,0], [0,0,0]]
bucket_capacity : 5
Output: 0
Constraints:
* all wells have the same length
* 1 <= grid.length <= 10^2
* 1 <= grid[:,1].length <= 10^2
* grid[i][j] -> 0 | 1
* 1 <= capacity <= 10
"""
total_lowerings = 0
for row in grid:
water_units = sum(row)
if water_units > 0:
total_lowerings += math.ceil(water_units / capacity)
return total_lowerings

View File

@@ -0,0 +1,12 @@
def sort_array(arr):
"""
In this Kata, you have to sort an array of non-negative integers according to
number of ones in their binary representation in ascending order.
For similar number of ones, sort based on decimal value.
It must be implemented like this:
>>> sort_array([1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
>>> sort_array([-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
>>> sort_array([1, 0, 2, 3, 4]) [0, 1, 2, 3, 4]
"""
return sorted(arr, key=lambda x: (bin(x).count('1'), x))

View File

@@ -0,0 +1,25 @@
def select_words(s, n):
"""Given a string s and a natural number n, you have been tasked to implement
a function that returns a list of all words from string s that contain exactly
n consonants, in order these words appear in the string s.
If the string s is empty then the function should return an empty list.
Note: you may assume the input string contains only letters and spaces.
Examples:
select_words("Mary had a little lamb", 4) ==> ["little"]
select_words("Mary had a little lamb", 3) ==> ["Mary", "lamb"]
select_words("simple white space", 2) ==> []
select_words("Hello world", 4) ==> ["world"]
select_words("Uncle sam", 3) ==> ["Uncle"]
"""
if not s:
return []
vowels = set('aeiouAEIOU')
result = []
for word in s.split():
consonant_count = sum(1 for char in word if char.isalpha() and char not in vowels)
if consonant_count == n:
result.append(word)
return result

View File

@@ -0,0 +1,26 @@
def get_closest_vowel(word):
"""You are given a word. Your task is to find the closest vowel that stands between
two consonants from the right side of the word (case sensitive).
Vowels in the beginning and ending doesn't count. Return empty string if you didn't
find any vowel met the above condition.
You may assume that the given string contains English letter only.
Example:
get_closest_vowel("yogurt") ==> "u"
get_closest_vowel("FULL") ==> "U"
get_closest_vowel("quick") ==> ""
get_closest_vowel("ab") ==> ""
"""
if len(word) < 3:
return ""
vowels = "aeiouAEIOU"
for i in range(len(word) - 2, 0, -1):
if word[i] in vowels:
if word[i-1] not in vowels and word[i+1] not in vowels:
return word[i]
return ""

View File

@@ -0,0 +1,30 @@
def match_parens(lst):
'''
You are given a list of two strings, both strings consist of open
parentheses '(' or close parentheses ')' only.
Your job is to check if it is possible to concatenate the two strings in
some order, that the resulting string will be good.
A string S is considered to be good if and only if all parentheses in S
are balanced. For example: the string '(())()' is good, while the string
'())' is not.
Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
Examples:
match_parens(['()(', ')']) == 'Yes'
match_parens([')', ')']) == 'No'
'''
def is_balanced(s):
count = 0
for c in s:
if c == '(':
count += 1
else:
count -= 1
if count < 0:
return False
return count == 0
s1, s2 = lst[0], lst[1]
if is_balanced(s1 + s2) or is_balanced(s2 + s1):
return 'Yes'
return 'No'

View File

@@ -0,0 +1,21 @@
from typing import List, Optional
def longest(strings: List[str]) -> Optional[str]:
""" Out of list of strings, return the longest one. Return the first one in case of multiple
strings of the same length. Return None in case the input list is empty.
>>> longest([])
>>> longest(['a', 'b', 'c'])
'a'
>>> longest(['a', 'bb', 'ccc'])
'ccc'
"""
if not strings:
return None
longest_str = strings[0]
for s in strings[1:]:
if len(s) > len(longest_str):
longest_str = s
return longest_str

View File

@@ -0,0 +1,28 @@
def maximum(arr, k):
"""
Given an array arr of integers and a positive integer k, return a sorted list
of length k with the maximum k numbers in arr.
Example 1:
Input: arr = [-3, -4, 5], k = 3
Output: [-4, -3, 5]
Example 2:
Input: arr = [4, -4, 4], k = 2
Output: [4, 4]
Example 3:
Input: arr = [-3, 2, 1, 2, -1, -2, 1], k = 1
Output: [2]
Note:
1. The length of the array will be in the range of [1, 1000].
2. The elements in the array will be in the range of [-1000, 1000].
3. 0 <= k <= len(arr)
"""
sorted_arr = sorted(arr, reverse=True)
top_k = sorted_arr[:k]
return sorted(top_k)

View File

@@ -0,0 +1,10 @@
def solution(lst):
"""Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.
Examples
solution([5, 8, 7, 1]) ==> 12
solution([3, 3, 3, 3, 3]) ==> 9
solution([30, 13, 24, 321]) ==>0
"""
return sum(x for i, x in enumerate(lst) if i % 2 == 0 and x % 2 == 1)

View File

@@ -0,0 +1,19 @@
def add_elements(arr, k):
"""
Given a non-empty array of integers arr and an integer k, return
the sum of the elements with at most two digits from the first k elements of arr.
Example:
Input: arr = [111,21,3,4000,5,6,7,8,9], k = 4
Output: 24 # sum of 21 + 3
Constraints:
1. 1 <= len(arr) <= 100
2. 1 <= k <= len(arr)
"""
total = 0
for i in range(k):
if -99 <= arr[i] <= 99:
total += arr[i]
return total

View File

@@ -0,0 +1,31 @@
def get_odd_collatz(n):
"""
Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
as follows: start with any positive integer n. Then each term is obtained from the
previous term as follows: if the previous term is even, the next term is one half of
the previous term. If the previous term is odd, the next term is 3 times the previous
term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
Note:
1. Collatz(1) is [1].
2. returned list sorted in increasing order.
For example:
get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
"""
odd_numbers = []
current = n
while current != 1:
if current % 2 == 1:
odd_numbers.append(current)
if current % 2 == 0:
current = current // 2
else:
current = 3 * current + 1
odd_numbers.append(1)
return sorted(odd_numbers)

View File

@@ -0,0 +1,56 @@
def valid_date(date):
"""You have to write a function which validates a given date string and
returns True if the date is valid otherwise False.
The date is valid if all of the following rules are satisfied:
1. The date string is not empty.
2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
3. The months should not be less than 1 or higher than 12.
4. The date should be in the format: mm-dd-yyyy
for example:
valid_date('03-11-2000') => True
valid_date('15-01-2012') => False
valid_date('04-0-2040') => False
valid_date('06-04-2020') => True
valid_date('06/04/2020') => False
"""
if not date:
return False
try:
parts = date.split('-')
if len(parts) != 3:
return False
mm, dd, yyyy = parts
if len(mm) != 2 or len(dd) != 2 or len(yyyy) != 4:
return False
month = int(mm)
day = int(dd)
year = int(yyyy)
if month < 1 or month > 12:
return False
if day < 1:
return False
if month in [1, 3, 5, 7, 8, 10, 12]:
if day > 31:
return False
elif month in [4, 6, 9, 11]:
if day > 30:
return False
elif month == 2:
if day > 29:
return False
return True
except:
return False

View File

@@ -0,0 +1,20 @@
def split_words(txt):
'''
Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you
should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
Examples
split_words("Hello world!") ➞ ["Hello", "world!"]
split_words("Hello,world!") ➞ ["Hello", "world!"]
split_words("abcdef") == 3
'''
if ' ' in txt:
return txt.split()
elif ',' in txt:
return txt.split(',')
else:
count = 0
for char in txt:
if char.islower() and (ord(char) - ord('a')) % 2 == 1:
count += 1
return count

View File

@@ -0,0 +1,29 @@
def is_sorted(lst):
'''
Given a list of numbers, return whether or not they are sorted
in ascending order. If list has more than 1 duplicate of the same
number, return False. Assume no negative numbers and only integers.
Examples
is_sorted([5]) ➞ True
is_sorted([1, 2, 3, 4, 5]) ➞ True
is_sorted([1, 3, 2, 4, 5]) ➞ False
is_sorted([1, 2, 3, 4, 5, 6]) ➞ True
is_sorted([1, 2, 3, 4, 5, 6, 7]) ➞ True
is_sorted([1, 3, 2, 4, 5, 6, 7]) ➞ False
is_sorted([1, 2, 2, 3, 3, 4]) ➞ True
is_sorted([1, 2, 2, 2, 3, 4]) ➞ False
'''
# Check if sorted in ascending order
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
return False
# Check for more than 1 duplicate of any number
from collections import Counter
counts = Counter(lst)
for count in counts.values():
if count > 2:
return False
return True

View File

@@ -0,0 +1,47 @@
def intersection(interval1, interval2):
"""You are given two intervals,
where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
The given intervals are closed which means that the interval (start, end)
includes both start and end.
For each given interval, it is assumed that its start is less or equal its end.
Your task is to determine whether the length of intersection of these two
intervals is a prime number.
Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
which its length is 1, which not a prime number.
If the length of the intersection is a prime number, return "YES",
otherwise, return "NO".
If the two intervals don't intersect, return "NO".
[input/output] samples:
intersection((1, 2), (2, 3)) ==> "NO"
intersection((-1, 1), (0, 4)) ==> "NO"
intersection((-3, -1), (-5, 5)) ==> "YES"
"""
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
start1, end1 = interval1
start2, end2 = interval2
intersection_start = max(start1, start2)
intersection_end = min(end1, end2)
if intersection_start > intersection_end:
return "NO"
length = intersection_end - intersection_start
if is_prime(length):
return "YES"
else:
return "NO"

View File

@@ -0,0 +1,25 @@
def prod_signs(arr):
"""
You are given an array arr of integers and you need to return
sum of magnitudes of integers multiplied by product of all signs
of each number in the array, represented by 1, -1 or 0.
Note: return None for empty arr.
Example:
>>> prod_signs([1, 2, 2, -4]) == -9
>>> prod_signs([0, 1]) == 0
>>> prod_signs([]) == None
"""
if not arr:
return None
sum_magnitudes = sum(abs(x) for x in arr)
sign_product = 1
for x in arr:
if x == 0:
return 0
elif x < 0:
sign_product *= -1
return sum_magnitudes * sign_product

View File

@@ -0,0 +1,61 @@
def minPath(grid, k):
"""
Given a grid with N rows and N columns (N >= 2) and a positive integer k,
each cell of the grid contains a value. Every integer in the range [1, N * N]
inclusive appears exactly once on the cells of the grid.
You have to find the minimum path of length k in the grid. You can start
from any cell, and in each step you can move to any of the neighbor cells,
in other words, you can go to cells which share an edge with you current
cell.
Please note that a path of length k means visiting exactly k cells (not
necessarily distinct).
You CANNOT go off the grid.
A path A (of length k) is considered less than a path B (of length k) if
after making the ordered lists of the values on the cells that A and B go
through (let's call them lst_A and lst_B), lst_A is lexicographically less
than lst_B, in other words, there exist an integer index i (1 <= i <= k)
such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
lst_A[j] = lst_B[j].
It is guaranteed that the answer is unique.
Return an ordered list of the values on the cells that the minimum path go through.
Examples:
Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3
Output: [1, 2, 1]
Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1
Output: [1]
"""
n = len(grid)
# Find position of value 1 (the minimum value)
pos_1 = None
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
pos_1 = (i, j)
break
if pos_1:
break
# Find the minimum neighbor of cell containing 1
i, j = pos_1
min_neighbor = float('inf')
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for di, dj in directions:
ni, nj = i + di, j + dj
if 0 <= ni < n and 0 <= nj < n:
min_neighbor = min(min_neighbor, grid[ni][nj])
# The minimum path starting from 1 will alternate between 1 and its minimum neighbor
# This is because we can always go back to 1 from any neighbor
result = []
for step in range(k):
if step % 2 == 0:
result.append(1)
else:
result.append(min_neighbor)
return result

View File

@@ -0,0 +1,10 @@
def greatest_common_divisor(a: int, b: int) -> int:
""" Return a greatest common divisor of two integers a and b
>>> greatest_common_divisor(3, 5)
1
>>> greatest_common_divisor(25, 15)
5
"""
while b:
a, b = b, a % b
return a

View File

@@ -0,0 +1,29 @@
def tri(n):
"""Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
the last couple centuries. However, what people don't know is Tribonacci sequence.
Tribonacci sequence is defined by the recurrence:
tri(1) = 3
tri(n) = 1 + n / 2, if n is even.
tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
For example:
tri(2) = 1 + (2 / 2) = 2
tri(4) = 3
tri(3) = tri(2) + tri(1) + tri(4)
= 2 + 3 + 3 = 8
You are given a non-negative integer number n, you have to a return a list of the
first n + 1 numbers of the Tribonacci sequence.
Examples:
tri(3) = [1, 3, 2, 8]
"""
if n == 0:
return [1]
result = [1, 3]
for i in range(2, n + 1):
if i % 2 == 0:
result.append(1 + i // 2)
else:
result.append(result[i - 1] + result[i - 2] + (1 + (i + 1) // 2))
return result

View File

@@ -0,0 +1,18 @@
def digits(n):
"""Given a positive integer n, return the product of the odd digits.
Return 0 if all digits are even.
For example:
digits(1) == 1
digits(4) == 0
digits(235) == 15
"""
product = 1
has_odd = False
for digit in str(n):
d = int(digit)
if d % 2 == 1:
product *= d
has_odd = True
return product if has_odd else 0

View File

@@ -0,0 +1,36 @@
def is_nested(string):
'''
Create a function that takes a string as input which contains only square brackets.
The function should return True if and only if there is a valid subsequence of brackets
where at least one bracket in the subsequence is nested.
is_nested('[[]]') ➞ True
is_nested('[]]]]]]][[[[[]') ➞ False
is_nested('[][]') ➞ False
is_nested('[]') ➞ False
is_nested('[[][]]') ➞ True
is_nested('[[]][[') ➞ True
'''
opening_bracket_index = []
closing_bracket_index = []
for i, c in enumerate(string):
if c == '[':
opening_bracket_index.append(i)
else:
closing_bracket_index.append(i)
closing_bracket_index.reverse()
cnt = 0
i = 0
j = 0
while i < len(opening_bracket_index) and j < len(closing_bracket_index):
if opening_bracket_index[i] < closing_bracket_index[j]:
cnt += 1
i += 1
else:
j += 1
return cnt >= 2

View File

@@ -0,0 +1,16 @@
import math
def sum_squares(lst):
"""You are given a list of numbers.
You need to return the sum of squared numbers in the given list,
round each element in the list to the upper int(Ceiling) first.
Examples:
For lst = [1,2,3] the output should be 14
For lst = [1,4,9] the output should be 98
For lst = [1,3,5,7] the output should be 84
For lst = [1.4,4.2,0] the output should be 29
For lst = [-2.4,1,1] the output should be 6
"""
return sum(math.ceil(x) ** 2 for x in lst)

View File

@@ -0,0 +1,27 @@
def check_if_last_char_is_a_letter(txt):
'''
Create a function that returns True if the last character
of a given string is an alphabetical character and is not
a part of a word, and False otherwise.
Note: "word" is a group of characters separated by space.
Examples:
check_if_last_char_is_a_letter("apple pie") ➞ False
check_if_last_char_is_a_letter("apple pi e") ➞ True
check_if_last_char_is_a_letter("apple pi e ") ➞ False
check_if_last_char_is_a_letter("") ➞ False
'''
if len(txt) == 0:
return False
last_char = txt[-1]
if not last_char.isalpha():
return False
if len(txt) == 1:
return True
second_last_char = txt[-2]
return second_last_char == ' '

View File

@@ -0,0 +1,15 @@
def can_arrange(arr):
"""Create a function which returns the largest index of an element which
is not greater than or equal to the element immediately preceding it. If
no such element exists then return -1. The given array will not contain
duplicate values.
Examples:
can_arrange([1,2,4,3,5]) = 3
can_arrange([1,2,3]) = -1
"""
result = -1
for i in range(1, len(arr)):
if arr[i] < arr[i - 1]:
result = i
return result

View File

@@ -0,0 +1,19 @@
def largest_smallest_integers(lst):
'''
Create a function that returns a tuple (a, b), where 'a' is
the largest of negative integers, and 'b' is the smallest
of positive integers in a list.
If there is no negative or positive integers, return them as None.
Examples:
largest_smallest_integers([2, 4, 1, 3, 5, 7]) == (None, 1)
largest_smallest_integers([]) == (None, None)
largest_smallest_integers([0]) == (None, None)
'''
negatives = [x for x in lst if x < 0]
positives = [x for x in lst if x > 0]
a = max(negatives) if negatives else None
b = min(positives) if positives else None
return (a, b)

View File

@@ -0,0 +1,26 @@
def compare_one(a, b):
"""
Create a function that takes integers, floats, or strings representing
real numbers, and returns the larger variable in its given variable type.
Return None if the values are equal.
Note: If a real number is represented as a string, the floating point might be . or ,
compare_one(1, 2.5) ➞ 2.5
compare_one(1, "2,3") ➞ "2,3"
compare_one("5,1", "6") ➞ "6"
compare_one("1", 1) ➞ None
"""
def to_float(x):
if isinstance(x, str):
return float(x.replace(",", "."))
return float(x)
val_a = to_float(a)
val_b = to_float(b)
if val_a == val_b:
return None
elif val_a > val_b:
return a
else:
return b

View File

@@ -0,0 +1,8 @@
def is_equal_to_sum_even(n):
"""Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
Example
is_equal_to_sum_even(4) == False
is_equal_to_sum_even(6) == False
is_equal_to_sum_even(8) == True
"""
return n >= 8 and n % 2 == 0

View File

@@ -0,0 +1,18 @@
def special_factorial(n):
"""The Brazilian factorial is defined as:
brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
where n > 0
For example:
>>> special_factorial(4)
288
The function will receive an integer as input and should return the special
factorial of this integer.
"""
result = 1
factorial = 1
for i in range(1, n + 1):
factorial *= i
result *= factorial
return result

View File

@@ -0,0 +1,9 @@
from typing import List
def all_prefixes(string: str) -> List[str]:
""" Return list of all prefixes from shortest to longest of the input string
>>> all_prefixes('abc')
['a', 'ab', 'abc']
"""
return [string[:i+1] for i in range(len(string))]

View File

@@ -0,0 +1,30 @@
def fix_spaces(text):
"""
Given a string text, replace all spaces in it with underscores,
and if a string has more than 2 consecutive spaces,
then replace all consecutive spaces with -
fix_spaces("Example") == "Example"
fix_spaces("Example 1") == "Example_1"
fix_spaces(" Example 2") == "_Example_2"
fix_spaces(" Example 3") == "_Example-3"
"""
result = []
i = 0
while i < len(text):
if text[i] == ' ':
# Count consecutive spaces
space_count = 0
while i < len(text) and text[i] == ' ':
space_count += 1
i += 1
# If more than 2 consecutive spaces, replace with -
if space_count > 2:
result.append('-')
else:
# Replace each space with underscore
result.append('_' * space_count)
else:
result.append(text[i])
i += 1
return ''.join(result)

View File

@@ -0,0 +1,35 @@
def file_name_check(file_name):
"""Create a function which takes a string representing a file's name, and returns
'Yes' if the the file's name is valid, and returns 'No' otherwise.
A file's name is considered to be valid if and only if all the following conditions
are met:
- There should not be more than three digits ('0'-'9') in the file's name.
- The file's name contains exactly one dot '.'
- The substring before the dot should not be empty, and it starts with a letter from
the latin alphapet ('a'-'z' and 'A'-'Z').
- The substring after the dot should be one of these: ['txt', 'exe', 'dll']
Examples:
file_name_check("example.txt") # => 'Yes'
file_name_check("1example.dll") # => 'No' (the name should start with a latin alphapet letter)
"""
# Check for exactly one dot
if file_name.count('.') != 1:
return 'No'
# Split the file name into name and extension
name, extension = file_name.split('.')
# Check if the name is not empty and starts with a letter
if len(name) == 0 or not name[0].isalpha():
return 'No'
# Check if extension is valid
if extension not in ['txt', 'exe', 'dll']:
return 'No'
# Count digits in the entire file name
digit_count = sum(1 for char in file_name if char.isdigit())
if digit_count > 3:
return 'No'
return 'Yes'

View File

@@ -0,0 +1,20 @@
def sum_squares(lst):
""""
This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a
multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not
change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries.
Examples:
For lst = [1,2,3] the output should be 6
For lst = [] the output should be 0
For lst = [-1,-5,2,-1,-5] the output should be -126
"""
result = 0
for i, val in enumerate(lst):
if i % 3 == 0:
result += val ** 2
elif i % 4 == 0:
result += val ** 3
else:
result += val
return result

View File

@@ -0,0 +1,35 @@
def words_in_sentence(sentence):
"""
You are given a string representing a sentence,
the sentence contains some words separated by a space,
and you have to return a string that contains the words from the original sentence,
whose lengths are prime numbers,
the order of the words in the new string should be the same as the original one.
Example 1:
Input: sentence = "This is a test"
Output: "is"
Example 2:
Input: sentence = "lets go for swimming"
Output: "go for"
Constraints:
* 1 <= len(sentence) <= 100
* sentence contains only letters
"""
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
words = sentence.split()
prime_words = [word for word in words if is_prime(len(word))]
return " ".join(prime_words)

View File

@@ -0,0 +1,19 @@
def simplify(x, n):
"""Your task is to implement a function that will simplify the expression
x * n. The function returns True if x * n evaluates to a whole number and False
otherwise. Both x and n, are string representation of a fraction, and have the following format,
<numerator>/<denominator> where both numerator and denominator are positive whole numbers.
You can assume that x, and n are valid fractions, and do not have zero as denominator.
simplify("1/5", "5/1") = True
simplify("1/6", "2/1") = False
simplify("7/10", "10/2") = False
"""
x_num, x_den = map(int, x.split('/'))
n_num, n_den = map(int, n.split('/'))
numerator = x_num * n_num
denominator = x_den * n_den
return numerator % denominator == 0

View File

@@ -0,0 +1,22 @@
def order_by_points(nums):
"""
Write a function which sorts the given list of integers
in ascending order according to the sum of their digits.
Note: if there are several items with similar sum of their digits,
order them based on their index in original list.
For example:
>>> order_by_points([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
>>> order_by_points([]) == []
"""
def digit_sum(n):
s = str(abs(n))
total = 0
for i, digit in enumerate(s):
if i == 0 and n < 0:
total -= int(digit)
else:
total += int(digit)
return total
return sorted(nums, key=digit_sum)

View File

@@ -0,0 +1,21 @@
def specialFilter(nums):
"""Write a function that takes an array of numbers as input and returns
the number of elements in the array that are greater than 10 and both
first and last digits of a number are odd (1, 3, 5, 7, 9).
For example:
specialFilter([15, -73, 14, -15]) => 1
specialFilter([33, -2, -3, 45, 21, 109]) => 2
"""
count = 0
odd_digits = {'1', '3', '5', '7', '9'}
for num in nums:
if num > 10:
num_str = str(num)
first_digit = num_str[0]
last_digit = num_str[-1]
if first_digit in odd_digits and last_digit in odd_digits:
count += 1
return count

View File

@@ -0,0 +1,22 @@
def get_max_triples(n):
"""
You are given a positive integer n. You have to create an integer array a of length n.
For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
and a[i] + a[j] + a[k] is a multiple of 3.
Example :
Input: n = 5
Output: 1
Explanation:
a = [1, 3, 7, 13, 21]
The only valid triple is (1, 7, 13).
"""
a = [i * i - i + 1 for i in range(1, n + 1)]
count = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if (a[i] + a[j] + a[k]) % 3 == 0:
count += 1
return count

View File

@@ -0,0 +1,28 @@
def bf(planet1, planet2):
'''
There are eight planets in our solar system: the closerst to the Sun
is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
Uranus, Neptune.
Write a function that takes two planet names as strings planet1 and planet2.
The function should return a tuple containing all planets whose orbits are
located between the orbit of planet1 and the orbit of planet2, sorted by
the proximity to the sun.
The function should return an empty tuple if planet1 or planet2
are not correct planet names.
Examples
bf("Jupiter", "Neptune") ==> ("Saturn", "Uranus")
bf("Earth", "Mercury") ==> ("Venus")
bf("Mercury", "Uranus") ==> ("Venus", "Earth", "Mars", "Jupiter", "Saturn")
'''
planets = ("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune")
if planet1 not in planets or planet2 not in planets:
return ()
idx1 = planets.index(planet1)
idx2 = planets.index(planet2)
if idx1 > idx2:
idx1, idx2 = idx2, idx1
return planets[idx1 + 1:idx2]

View File

@@ -0,0 +1,17 @@
def sorted_list_sum(lst):
"""Write a function that accepts a list of strings as a parameter,
deletes the strings that have odd lengths from it,
and returns the resulted list with a sorted order,
The list is always a list of strings and never an array of numbers,
and it may contain duplicates.
The order of the list should be ascending by length of each word, and you
should return the list sorted by that rule.
If two words have the same length, sort the list alphabetically.
The function should return a list of strings in sorted order.
You may assume that all words will have the same length.
For example:
assert list_sort(["aa", "a", "aaa"]) => ["aa"]
assert list_sort(["ab", "a", "aaa", "cd"]) => ["ab", "cd"]
"""
filtered = [s for s in lst if len(s) % 2 == 0]
return sorted(filtered, key=lambda x: (len(x), x))

View File

@@ -0,0 +1,8 @@
def string_sequence(n: int) -> str:
""" Return a string containing space-delimited numbers starting from 0 upto n inclusive.
>>> string_sequence(0)
'0'
>>> string_sequence(5)
'0 1 2 3 4 5'
"""
return ' '.join(str(i) for i in range(n + 1))

View File

@@ -0,0 +1,15 @@
def x_or_y(n, x, y):
"""A simple program which should return the value of x if n is
a prime number and should return the value of y otherwise.
Examples:
for x_or_y(7, 34, 12) == 34
for x_or_y(15, 8, 5) == 5
"""
if n < 2:
return y
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return y
return x

View File

@@ -0,0 +1,20 @@
def double_the_difference(lst):
'''
Given a list of numbers, return the sum of squares of the numbers
in the list that are odd. Ignore numbers that are negative or not integers.
double_the_difference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10
double_the_difference([-1, -2, 0]) == 0
double_the_difference([9, -2]) == 81
double_the_difference([0]) == 0
If the input list is empty, return 0.
'''
if not lst:
return 0
result = 0
for num in lst:
if isinstance(num, int) and not isinstance(num, bool) and num > 0 and num % 2 == 1:
result += num ** 2
return result

View File

@@ -0,0 +1,16 @@
def compare(game,guess):
"""I think we all remember that feeling when the result of some long-awaited
event is finally known. The feelings and thoughts you have at that moment are
definitely worth noting down and comparing.
Your task is to determine if a person correctly guessed the results of a number of matches.
You are given two arrays of scores and guesses of equal length, where each index shows a match.
Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
the value is 0, and if not, the value is the absolute difference between the guess and the score.
example:
compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3]
compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6]
"""
return [abs(g - s) for g, s in zip(guess, game)]

View File

@@ -0,0 +1,30 @@
def Strongest_Extension(class_name, extensions):
"""You will be given the name of a class (a string) and a list of extensions.
The extensions are to be used to load additional classes to the class. The
strength of the extension is as follows: Let CAP be the number of the uppercase
letters in the extension's name, and let SM be the number of lowercase letters
in the extension's name, the strength is given by the fraction CAP - SM.
You should find the strongest extension and return a string in this
format: ClassName.StrongestExtensionName.
If there are two or more extensions with the same strength, you should
choose the one that comes first in the list.
For example, if you are given "Slices" as the class and a list of the
extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
(its strength is -1).
Example:
for Strongest_Extension('my_class', ['AA', 'Be', 'CC']) == 'my_class.AA'
"""
strongest_ext = None
max_strength = None
for ext in extensions:
cap = sum(1 for c in ext if c.isupper())
sm = sum(1 for c in ext if c.islower())
strength = cap - sm
if max_strength is None or strength > max_strength:
max_strength = strength
strongest_ext = ext
return f"{class_name}.{strongest_ext}"

View File

@@ -0,0 +1,15 @@
def cycpattern_check(a , b):
"""You are given 2 words. You need to return True if the second word or any of its rotations is a substring in the first word
cycpattern_check("abcd","abd") => False
cycpattern_check("hello","ell") => True
cycpattern_check("whassup","psus") => False
cycpattern_check("abab","baa") => True
cycpattern_check("efef","eeff") => False
cycpattern_check("himenss","simen") => True
"""
for i in range(len(b)):
rotation = b[i:] + b[:i]
if rotation in a:
return True
return False

View File

@@ -0,0 +1,15 @@
def even_odd_count(num):
"""Given an integer. return a tuple that has the number of even and odd digits respectively.
Example:
even_odd_count(-12) ==> (1, 1)
even_odd_count(123) ==> (1, 2)
"""
even_count = 0
odd_count = 0
for digit in str(abs(num)):
if int(digit) % 2 == 0:
even_count += 1
else:
odd_count += 1
return (even_count, odd_count)

View File

@@ -0,0 +1,32 @@
def int_to_mini_roman(number):
"""
Given a positive integer, obtain its roman numeral equivalent as a string,
and return it in lowercase.
Restrictions: 1 <= num <= 1000
Examples:
>>> int_to_mini_roman(19) == 'xix'
>>> int_to_mini_roman(152) == 'clii'
>>> int_to_mini_roman(426) == 'cdxxvi'
"""
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syms = [
'm', 'cm', 'd', 'cd',
'c', 'xc', 'l', 'xl',
'x', 'ix', 'v', 'iv',
'i'
]
roman_num = ''
i = 0
while number > 0:
for _ in range(number // val[i]):
roman_num += syms[i]
number -= val[i]
i += 1
return roman_num

View File

@@ -0,0 +1,12 @@
def right_angle_triangle(a, b, c):
'''
Given the lengths of the three sides of a triangle. Return True if the three
sides form a right-angled triangle, False otherwise.
A right-angled triangle is a triangle in which one angle is right angle or
90 degree.
Example:
right_angle_triangle(3, 4, 5) == True
right_angle_triangle(1, 2, 3) == False
'''
sides = sorted([a, b, c])
return sides[0]**2 + sides[1]**2 == sides[2]**2

Some files were not shown because too many files have changed in this diff Show More