{"instruction":"Write a complete Python program to reverse a number.", "response":"def main():\n n = int(input('Enter a number: '))\n print(str(n)[::-1])\n"} {"instruction": "Build a complete Python script to find the missing number in a sequence from 1 to n.", "response": "def main():\n numbers = [1, 2, 3, 5, 6, 7, 8]\n n = 8\n expected = n * (n + 1) // 2\n actual = sum(numbers)\n print(\"Missing number =\", expected - actual)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to check whether a string is a palindrome ignoring spaces and punctuation.", "response": "def is_palindrome(text):\n cleaned = \"\".join(ch.lower() for ch in text if ch.isalnum())\n return cleaned == cleaned[::-1]\n\ndef main():\n text = input(\"Enter a string: \")\n print(\"Palindrome\" if is_palindrome(text) else \"Not a palindrome\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that count word frequencies in a sentence using a dictionary.", "response": "def main():\n text = \"this is a sample sample sentence with sample words\"\n words = text.split()\n freq = {}\n for word in words:\n freq[word] = freq.get(word, 0) + 1\n print(freq)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to rotate a list to the right by k positions.", "response": "def rotate_right(values, k):\n if not values:\n return values\n k %= len(values)\n return values[-k:] + values[:-k] if k else values[:]\n\ndef main():\n values = [1, 2, 3, 4, 5]\n k = 2\n print(rotate_right(values, k))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to check whether a string is a palindrome ignoring spaces and punctuation.", "response": "def is_palindrome(text):\n cleaned = \"\".join(ch.lower() for ch in text if ch.isalnum())\n return cleaned == cleaned[::-1]\n\ndef main():\n text = input(\"Enter a string: \")\n print(\"Palindrome\" if is_palindrome(text) else \"Not a palindrome\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to filter even numbers from a list.", "response": "def main():\n numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n evens = [n for n in numbers if n % 2 == 0]\n print(evens)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to find the missing number in a sequence from 1 to n.", "response": "def main():\n numbers = [1, 2, 3, 5, 6, 7, 8]\n n = 8\n expected = n * (n + 1) // 2\n actual = sum(numbers)\n print(\"Missing number =\", expected - actual)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to create a student class that calculates the average marks.", "response": "class Student:\n def __init__(self, name, marks):\n self.name = name\n self.marks = marks\n\n def average(self):\n return sum(self.marks) / len(self.marks) if self.marks else 0\n\ndef main():\n student = Student(\"Alice\", [85, 90, 78])\n print(student.name, \"average =\", student.average())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to check whether two strings are anagrams.", "response": "from collections import Counter\n\ndef normalize(text):\n return \"\".join(ch.lower() for ch in text if ch.isalnum())\n\ndef main():\n first = input(\"Enter first string: \")\n second = input(\"Enter second string: \")\n print(\"Anagram\" if Counter(normalize(first)) == Counter(normalize(second)) else \"Not anagram\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that remove duplicates from a list while preserving order.", "response": "def main():\n numbers = [1, 2, 2, 3, 4, 4, 5, 1, 6]\n unique_numbers = list(dict.fromkeys(numbers))\n print(\"Original list:\", numbers)\n print(\"Without duplicates:\", unique_numbers)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to create a file if it does not exist.", "response": "from pathlib import Path\n\ndef main():\n file_path = Path(\"notes.txt\")\n file_path.touch(exist_ok=True)\n print(f\"{file_path} is ready\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that reverse a string entered by the user.", "response": "def main():\n text = input(\"Enter a string: \")\n print(text[::-1])\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to merge two JSON objects from files.", "response": "import json\n\ndef main():\n file1 = \"a.json\"\n file2 = \"b.json\"\n try:\n with open(file1, \"r\", encoding=\"utf-8\") as f1, open(file2, \"r\", encoding=\"utf-8\") as f2:\n data1 = json.load(f1)\n data2 = json.load(f2)\n merged = {**data1, **data2}\n print(merged)\n except FileNotFoundError as e:\n print(f\"File not found: {e.filename}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to count the number of words in a sentence.", "response": "def main():\n text = input(\"Enter a sentence: \")\n words = text.split()\n print(\"Word count =\", len(words))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to merge two JSON objects from files.", "response": "import json\n\ndef main():\n file1 = \"a.json\"\n file2 = \"b.json\"\n try:\n with open(file1, \"r\", encoding=\"utf-8\") as f1, open(file2, \"r\", encoding=\"utf-8\") as f2:\n data1 = json.load(f1)\n data2 = json.load(f2)\n merged = {**data1, **data2}\n print(merged)\n except FileNotFoundError as e:\n print(f\"File not found: {e.filename}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to compute the greatest common divisor and least common multiple of two numbers.", "response": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\ndef main():\n a = int(input(\"Enter first number: \"))\n b = int(input(\"Enter second number: \"))\n print(\"GCD =\", gcd(a, b))\n print(\"LCM =\", lcm(a, b))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to sort a dictionary by its values.", "response": "def main():\n data = {\"a\": 3, \"b\": 1, \"c\": 2}\n sorted_data = dict(sorted(data.items(), key=lambda item: item[1]))\n print(sorted_data)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that read a CSV file and print all rows.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that count the number of lines in a text file.", "response": "def main():\n file_path = \"sample.txt\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n line_count = sum(1 for _ in f)\n print(\"Line count =\", line_count)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that check whether a number is prime.", "response": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Prime\" if is_prime(n) else \"Not prime\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that find the factorial of a number.", "response": "def factorial(n):\n result = 1\n for i in range(2, n + 1):\n result *= i\n return result\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Factorial =\", factorial(n))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to handle division by zero with exception handling.", "response": "def main():\n try:\n a = float(input(\"Enter numerator: \"))\n b = float(input(\"Enter denominator: \"))\n print(\"Result =\", a / b)\n except ZeroDivisionError:\n print(\"Cannot divide by zero\")\n except ValueError:\n print(\"Please enter valid numbers\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that filter even numbers from a list.", "response": "def main():\n numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n evens = [n for n in numbers if n % 2 == 0]\n print(evens)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to count the frequency of elements in a list.", "response": "from collections import Counter\n\ndef main():\n values = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]\n print(dict(Counter(values)))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to split a list into chunks of a given size.", "response": "def chunk_list(values, size):\n return [values[i:i + size] for i in range(0, len(values), size)]\n\ndef main():\n values = [1, 2, 3, 4, 5, 6, 7]\n print(chunk_list(values, 3))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that find the factorial of a number.", "response": "def factorial(n):\n result = 1\n for i in range(2, n + 1):\n result *= i\n return result\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Factorial =\", factorial(n))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to compute the greatest common divisor and least common multiple of two numbers.", "response": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\ndef main():\n a = int(input(\"Enter first number: \"))\n b = int(input(\"Enter second number: \"))\n print(\"GCD =\", gcd(a, b))\n print(\"LCM =\", lcm(a, b))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to copy the contents of one file into another file.", "response": "def main():\n source = \"input.txt\"\n destination = \"copy.txt\"\n try:\n with open(source, \"r\", encoding=\"utf-8\") as src:\n content = src.read()\n with open(destination, \"w\", encoding=\"utf-8\") as dst:\n dst.write(content)\n print(\"File copied successfully\")\n except FileNotFoundError:\n print(f\"File not found: {source}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that handle division by zero with exception handling.", "response": "def main():\n try:\n a = float(input(\"Enter numerator: \"))\n b = float(input(\"Enter denominator: \"))\n print(\"Result =\", a / b)\n except ZeroDivisionError:\n print(\"Cannot divide by zero\")\n except ValueError:\n print(\"Please enter valid numbers\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that check whether a number is a palindrome.", "response": "def main():\n n = input(\"Enter a number: \")\n print(\"Palindrome\" if n == n[::-1] else \"Not a palindrome\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that extract all values for a key from a JSON list.", "response": "import json\n\ndef main():\n file_path = \"records.json\"\n key = \"name\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n values = [item.get(key) for item in data if isinstance(item, dict)]\n print(values)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to read a CSV file and print all rows.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that convert a string to title case.", "response": "def main():\n text = input(\"Enter text: \")\n print(text.title())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that rotate a list to the right by k positions.", "response": "def rotate_right(values, k):\n if not values:\n return values\n k %= len(values)\n return values[-k:] + values[:-k] if k else values[:]\n\ndef main():\n values = [1, 2, 3, 4, 5]\n k = 2\n print(rotate_right(values, k))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to sort a list using bubble sort.", "response": "def bubble_sort(values):\n arr = values[:]\n n = len(arr)\n for i in range(n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n return arr\n\ndef main():\n values = [64, 34, 25, 12, 22, 11, 90]\n print(bubble_sort(values))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to remove punctuation from a string.", "response": "import string\n\ndef main():\n text = input(\"Enter a string: \")\n translator = str.maketrans(\"\", \"\", string.punctuation)\n print(text.translate(translator))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to check whether a number is an Armstrong number.", "response": "def is_armstrong(n):\n digits = [int(d) for d in str(n)]\n power = len(digits)\n return sum(d ** power for d in digits) == n\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Armstrong number\" if is_armstrong(n) else \"Not an Armstrong number\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to count word frequencies in a sentence using a dictionary.", "response": "def main():\n text = \"this is a sample sample sentence with sample words\"\n words = text.split()\n freq = {}\n for word in words:\n freq[word] = freq.get(word, 0) + 1\n print(freq)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to find the missing number in a sequence from 1 to n.", "response": "def main():\n numbers = [1, 2, 3, 5, 6, 7, 8]\n n = 8\n expected = n * (n + 1) // 2\n actual = sum(numbers)\n print(\"Missing number =\", expected - actual)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that count the number of words in a sentence.", "response": "def main():\n text = input(\"Enter a sentence: \")\n words = text.split()\n print(\"Word count =\", len(words))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that print a file with line numbers.", "response": "def main():\n file_path = \"sample.txt\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n for i, line in enumerate(f, start=1):\n print(f\"{i}: {line.rstrip()}\")\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to create a rectangle class that calculates area and perimeter.", "response": "class Rectangle:\n def __init__(self, length, width):\n self.length = length\n self.width = width\n\n def area(self):\n return self.length * self.width\n\n def perimeter(self):\n return 2 * (self.length + self.width)\n\ndef main():\n rect = Rectangle(10, 5)\n print(\"Area:\", rect.area())\n print(\"Perimeter:\", rect.perimeter())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to merge two sorted lists into one sorted list.", "response": "def merge_sorted_lists(a, b):\n i = j = 0\n merged = []\n while i < len(a) and j < len(b):\n if a[i] <= b[j]:\n merged.append(a[i])\n i += 1\n else:\n merged.append(b[j])\n j += 1\n merged.extend(a[i:])\n merged.extend(b[j:])\n return merged\n\ndef main():\n a = [1, 3, 5, 7]\n b = [2, 4, 6, 8]\n print(merge_sorted_lists(a, b))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to find the factorial of a number.", "response": "def factorial(n):\n result = 1\n for i in range(2, n + 1):\n result *= i\n return result\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Factorial =\", factorial(n))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to filter CSV rows by a column value.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n column = \"city\"\n target = \"Bangalore\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n matches = [row for row in reader if row.get(column) == target]\n for row in matches:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to encrypt a string using a Caesar cipher with shift 3.", "response": "def shift_char(ch, shift):\n if ch.isalpha():\n base = ord(\"A\") if ch.isupper() else ord(\"a\")\n return chr((ord(ch) - base + shift) % 26 + base)\n return ch\n\ndef main():\n text = input(\"Enter text: \")\n encrypted = \"\".join(shift_char(ch, 3) for ch in text)\n print(encrypted)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that count the number of lines in a text file.", "response": "def main():\n file_path = \"sample.txt\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n line_count = sum(1 for _ in f)\n print(\"Line count =\", line_count)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to group numbers by parity in a dictionary.", "response": "def main():\n numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n grouped = {\n \"even\": [n for n in numbers if n % 2 == 0],\n \"odd\": [n for n in numbers if n % 2 != 0],\n }\n print(grouped)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to count the number of words in a sentence.", "response": "def main():\n text = input(\"Enter a sentence: \")\n words = text.split()\n print(\"Word count =\", len(words))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to count the frequency of elements in a list.", "response": "from collections import Counter\n\ndef main():\n values = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]\n print(dict(Counter(values)))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to perform binary search on a sorted list.", "response": "def binary_search(values, target):\n left, right = 0, len(values) - 1\n while left <= right:\n mid = (left + right) // 2\n if values[mid] == target:\n return mid\n if values[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n return -1\n\ndef main():\n values = [1, 3, 5, 7, 9, 11, 13]\n target = 7\n print(\"Index:\", binary_search(values, target))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to sum a numeric column from a CSV file.", "response": "import csv\n\ndef main():\n file_path = \"sales.csv\"\n column = \"amount\"\n total = 0.0\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n total += float(row[column])\n print(\"Total =\", total)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except KeyError:\n print(f\"Column not found: {column}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that pretty print a JSON file.", "response": "import json\n\ndef main():\n file_path = \"data.json\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n print(json.dumps(data, indent=4))\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that create a file if it does not exist.", "response": "from pathlib import Path\n\ndef main():\n file_path = Path(\"notes.txt\")\n file_path.touch(exist_ok=True)\n print(f\"{file_path} is ready\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that find the second largest number in a list.", "response": "def main():\n numbers = [12, 45, 7, 89, 23, 89, 5]\n unique_sorted = sorted(set(numbers))\n second_largest = unique_sorted[-2] if len(unique_sorted) >= 2 else None\n print(\"Second largest:\", second_largest)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to encrypt a string using a Caesar cipher with shift 3.", "response": "def shift_char(ch, shift):\n if ch.isalpha():\n base = ord(\"A\") if ch.isupper() else ord(\"a\")\n return chr((ord(ch) - base + shift) % 26 + base)\n return ch\n\ndef main():\n text = input(\"Enter text: \")\n encrypted = \"\".join(shift_char(ch, 3) for ch in text)\n print(encrypted)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to find the maximum subarray sum using Kadane's algorithm.", "response": "def max_subarray_sum(values):\n current = best = values[0]\n for num in values[1:]:\n current = max(num, current + num)\n best = max(best, current)\n return best\n\ndef main():\n values = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\n print(\"Maximum subarray sum =\", max_subarray_sum(values))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that create a calculator class with basic arithmetic methods.", "response": "class Calculator:\n def add(self, a, b):\n return a + b\n\n def subtract(self, a, b):\n return a - b\n\n def multiply(self, a, b):\n return a * b\n\n def divide(self, a, b):\n if b == 0:\n return \"Cannot divide by zero\"\n return a / b\n\ndef main():\n calc = Calculator()\n print(calc.add(10, 5))\n print(calc.subtract(10, 5))\n print(calc.multiply(10, 5))\n print(calc.divide(10, 5))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to generate the first n Fibonacci numbers.", "response": "def fibonacci(n):\n seq = [0, 1]\n while len(seq) < n:\n seq.append(seq[-1] + seq[-2])\n return seq[:n]\n\ndef main():\n n = int(input(\"Enter how many terms: \"))\n print(fibonacci(n))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to create a file if it does not exist.", "response": "from pathlib import Path\n\ndef main():\n file_path = Path(\"notes.txt\")\n file_path.touch(exist_ok=True)\n print(f\"{file_path} is ready\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to copy the contents of one file into another file.", "response": "def main():\n source = \"input.txt\"\n destination = \"copy.txt\"\n try:\n with open(source, \"r\", encoding=\"utf-8\") as src:\n content = src.read()\n with open(destination, \"w\", encoding=\"utf-8\") as dst:\n dst.write(content)\n print(\"File copied successfully\")\n except FileNotFoundError:\n print(f\"File not found: {source}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to reverse a string entered by the user.", "response": "def main():\n text = input(\"Enter a string: \")\n print(text[::-1])\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to remove duplicates from a list while preserving order.", "response": "def main():\n numbers = [1, 2, 2, 3, 4, 4, 5, 1, 6]\n unique_numbers = list(dict.fromkeys(numbers))\n print(\"Original list:\", numbers)\n print(\"Without duplicates:\", unique_numbers)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that split a list into chunks of a given size.", "response": "def chunk_list(values, size):\n return [values[i:i + size] for i in range(0, len(values), size)]\n\ndef main():\n values = [1, 2, 3, 4, 5, 6, 7]\n print(chunk_list(values, 3))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to find the second largest number in a list.", "response": "def main():\n numbers = [12, 45, 7, 89, 23, 89, 5]\n unique_sorted = sorted(set(numbers))\n second_largest = unique_sorted[-2] if len(unique_sorted) >= 2 else None\n print(\"Second largest:\", second_largest)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to count the vowels in a string.", "response": "def count_vowels(text):\n vowels = \"aeiouAEIOU\"\n return sum(1 for ch in text if ch in vowels)\n\ndef main():\n text = input(\"Enter a string: \")\n print(\"Vowel count =\", count_vowels(text))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to count word frequencies in a sentence using a dictionary.", "response": "def main():\n text = \"this is a sample sample sentence with sample words\"\n words = text.split()\n freq = {}\n for word in words:\n freq[word] = freq.get(word, 0) + 1\n print(freq)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that find two numbers in a list that add up to a target.", "response": "def main():\n numbers = [2, 7, 11, 15]\n target = 9\n seen = {}\n for i, num in enumerate(numbers):\n diff = target - num\n if diff in seen:\n print((seen[diff], i))\n return\n seen[num] = i\n print(\"No pair found\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to find the longest word in a sentence.", "response": "def main():\n text = input(\"Enter a sentence: \")\n words = text.split()\n longest = max(words, key=len) if words else \"\"\n print(\"Longest word:\", longest)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to generate the first n Fibonacci numbers.", "response": "def fibonacci(n):\n seq = [0, 1]\n while len(seq) < n:\n seq.append(seq[-1] + seq[-2])\n return seq[:n]\n\ndef main():\n n = int(input(\"Enter how many terms: \"))\n print(fibonacci(n))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that check whether two strings are anagrams.", "response": "from collections import Counter\n\ndef normalize(text):\n return \"\".join(ch.lower() for ch in text if ch.isalnum())\n\ndef main():\n first = input(\"Enter first string: \")\n second = input(\"Enter second string: \")\n print(\"Anagram\" if Counter(normalize(first)) == Counter(normalize(second)) else \"Not anagram\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that append a new line to a file.", "response": "def main():\n file_path = \"log.txt\"\n line = \"New entry added\"\n with open(file_path, \"a\", encoding=\"utf-8\") as f:\n f.write(line + \"\\n\")\n print(\"Line appended\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to reverse a string entered by the user.", "response": "def main():\n text = input(\"Enter a string: \")\n print(text[::-1])\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that update a field in a JSON file.", "response": "import json\n\ndef main():\n file_path = \"data.json\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n data[\"status\"] = \"updated\"\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(data, f, indent=4)\n print(\"JSON updated\")\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that sort a list using bubble sort.", "response": "def bubble_sort(values):\n arr = values[:]\n n = len(arr)\n for i in range(n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n return arr\n\ndef main():\n values = [64, 34, 25, 12, 22, 11, 90]\n print(bubble_sort(values))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that create a simple bank account class with deposit and withdraw methods.", "response": "class BankAccount:\n def __init__(self, balance=0):\n self.balance = balance\n\n def deposit(self, amount):\n self.balance += amount\n\n def withdraw(self, amount):\n if amount > self.balance:\n print(\"Insufficient balance\")\n return\n self.balance -= amount\n\ndef main():\n account = BankAccount(1000)\n account.deposit(500)\n account.withdraw(200)\n print(\"Balance:\", account.balance)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to count the number of lines in a text file.", "response": "def main():\n file_path = \"sample.txt\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n line_count = sum(1 for _ in f)\n print(\"Line count =\", line_count)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to pretty print a JSON file.", "response": "import json\n\ndef main():\n file_path = \"data.json\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n print(json.dumps(data, indent=4))\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to sort a dictionary by its values.", "response": "def main():\n data = {\"a\": 3, \"b\": 1, \"c\": 2}\n sorted_data = dict(sorted(data.items(), key=lambda item: item[1]))\n print(sorted_data)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to check whether two strings are anagrams.", "response": "from collections import Counter\n\ndef normalize(text):\n return \"\".join(ch.lower() for ch in text if ch.isalnum())\n\ndef main():\n first = input(\"Enter first string: \")\n second = input(\"Enter second string: \")\n print(\"Anagram\" if Counter(normalize(first)) == Counter(normalize(second)) else \"Not anagram\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to append a new line to a file.", "response": "def main():\n file_path = \"log.txt\"\n line = \"New entry added\"\n with open(file_path, \"a\", encoding=\"utf-8\") as f:\n f.write(line + \"\\n\")\n print(\"Line appended\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that create a rectangle class that calculates area and perimeter.", "response": "class Rectangle:\n def __init__(self, length, width):\n self.length = length\n self.width = width\n\n def area(self):\n return self.length * self.width\n\n def perimeter(self):\n return 2 * (self.length + self.width)\n\ndef main():\n rect = Rectangle(10, 5)\n print(\"Area:\", rect.area())\n print(\"Perimeter:\", rect.perimeter())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to filter even numbers from a list.", "response": "def main():\n numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n evens = [n for n in numbers if n % 2 == 0]\n print(evens)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that compute the greatest common divisor and least common multiple of two numbers.", "response": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\ndef main():\n a = int(input(\"Enter first number: \"))\n b = int(input(\"Enter second number: \"))\n print(\"GCD =\", gcd(a, b))\n print(\"LCM =\", lcm(a, b))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that merge two sorted lists into one sorted list.", "response": "def merge_sorted_lists(a, b):\n i = j = 0\n merged = []\n while i < len(a) and j < len(b):\n if a[i] <= b[j]:\n merged.append(a[i])\n i += 1\n else:\n merged.append(b[j])\n j += 1\n merged.extend(a[i:])\n merged.extend(b[j:])\n return merged\n\ndef main():\n a = [1, 3, 5, 7]\n b = [2, 4, 6, 8]\n print(merge_sorted_lists(a, b))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that find the first non-repeating character in a string.", "response": "from collections import Counter\n\ndef main():\n text = input(\"Enter a string: \")\n counts = Counter(text)\n result = next((ch for ch in text if counts[ch] == 1), None)\n print(\"First non-repeating character:\", result if result is not None else \"None\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that append a new line to a file.", "response": "def main():\n file_path = \"log.txt\"\n line = \"New entry added\"\n with open(file_path, \"a\", encoding=\"utf-8\") as f:\n f.write(line + \"\\n\")\n print(\"Line appended\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that count the vowels in a string.", "response": "def count_vowels(text):\n vowels = \"aeiouAEIOU\"\n return sum(1 for ch in text if ch in vowels)\n\ndef main():\n text = input(\"Enter a string: \")\n print(\"Vowel count =\", count_vowels(text))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that check whether a number is a palindrome.", "response": "def main():\n n = input(\"Enter a number: \")\n print(\"Palindrome\" if n == n[::-1] else \"Not a palindrome\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to check whether a number is an Armstrong number.", "response": "def is_armstrong(n):\n digits = [int(d) for d in str(n)]\n power = len(digits)\n return sum(d ** power for d in digits) == n\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Armstrong number\" if is_armstrong(n) else \"Not an Armstrong number\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to rotate a list to the right by k positions.", "response": "def rotate_right(values, k):\n if not values:\n return values\n k %= len(values)\n return values[-k:] + values[:-k] if k else values[:]\n\ndef main():\n values = [1, 2, 3, 4, 5]\n k = 2\n print(rotate_right(values, k))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that find the longest word in a sentence.", "response": "def main():\n text = input(\"Enter a sentence: \")\n words = text.split()\n longest = max(words, key=len) if words else \"\"\n print(\"Longest word:\", longest)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to sort a list using bubble sort.", "response": "def bubble_sort(values):\n arr = values[:]\n n = len(arr)\n for i in range(n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n return arr\n\ndef main():\n values = [64, 34, 25, 12, 22, 11, 90]\n print(bubble_sort(values))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to reverse a string entered by the user.", "response": "def main():\n text = input(\"Enter a string: \")\n print(text[::-1])\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to check whether a number is prime.", "response": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Prime\" if is_prime(n) else \"Not prime\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to append a new line to a file.", "response": "def main():\n file_path = \"log.txt\"\n line = \"New entry added\"\n with open(file_path, \"a\", encoding=\"utf-8\") as f:\n f.write(line + \"\\n\")\n print(\"Line appended\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to find the factorial of a number.", "response": "def factorial(n):\n result = 1\n for i in range(2, n + 1):\n result *= i\n return result\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Factorial =\", factorial(n))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to find the first non-repeating character in a string.", "response": "from collections import Counter\n\ndef main():\n text = input(\"Enter a string: \")\n counts = Counter(text)\n result = next((ch for ch in text if counts[ch] == 1), None)\n print(\"First non-repeating character:\", result if result is not None else \"None\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that group numbers by parity in a dictionary.", "response": "def main():\n numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n grouped = {\n \"even\": [n for n in numbers if n % 2 == 0],\n \"odd\": [n for n in numbers if n % 2 != 0],\n }\n print(grouped)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to keep asking the user for a valid integer until the input is correct.", "response": "def main():\n while True:\n try:\n value = int(input(\"Enter an integer: \"))\n print(\"You entered:\", value)\n break\n except ValueError:\n print(\"Invalid input, try again\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to merge two sorted lists into one sorted list.", "response": "def merge_sorted_lists(a, b):\n i = j = 0\n merged = []\n while i < len(a) and j < len(b):\n if a[i] <= b[j]:\n merged.append(a[i])\n i += 1\n else:\n merged.append(b[j])\n j += 1\n merged.extend(a[i:])\n merged.extend(b[j:])\n return merged\n\ndef main():\n a = [1, 3, 5, 7]\n b = [2, 4, 6, 8]\n print(merge_sorted_lists(a, b))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that sort a dictionary by its values.", "response": "def main():\n data = {\"a\": 3, \"b\": 1, \"c\": 2}\n sorted_data = dict(sorted(data.items(), key=lambda item: item[1]))\n print(sorted_data)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to find the longest word in a sentence.", "response": "def main():\n text = input(\"Enter a sentence: \")\n words = text.split()\n longest = max(words, key=len) if words else \"\"\n print(\"Longest word:\", longest)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that handle division by zero with exception handling.", "response": "def main():\n try:\n a = float(input(\"Enter numerator: \"))\n b = float(input(\"Enter denominator: \"))\n print(\"Result =\", a / b)\n except ZeroDivisionError:\n print(\"Cannot divide by zero\")\n except ValueError:\n print(\"Please enter valid numbers\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to perform binary search on a sorted list.", "response": "def binary_search(values, target):\n left, right = 0, len(values) - 1\n while left <= right:\n mid = (left + right) // 2\n if values[mid] == target:\n return mid\n if values[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n return -1\n\ndef main():\n values = [1, 3, 5, 7, 9, 11, 13]\n target = 7\n print(\"Index:\", binary_search(values, target))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that generate the first n Fibonacci numbers.", "response": "def fibonacci(n):\n seq = [0, 1]\n while len(seq) < n:\n seq.append(seq[-1] + seq[-2])\n return seq[:n]\n\ndef main():\n n = int(input(\"Enter how many terms: \"))\n print(fibonacci(n))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that find the maximum subarray sum using Kadane's algorithm.", "response": "def max_subarray_sum(values):\n current = best = values[0]\n for num in values[1:]:\n current = max(num, current + num)\n best = max(best, current)\n return best\n\ndef main():\n values = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\n print(\"Maximum subarray sum =\", max_subarray_sum(values))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that create a file if it does not exist.", "response": "from pathlib import Path\n\ndef main():\n file_path = Path(\"notes.txt\")\n file_path.touch(exist_ok=True)\n print(f\"{file_path} is ready\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to append a new line to a file.", "response": "def main():\n file_path = \"log.txt\"\n line = \"New entry added\"\n with open(file_path, \"a\", encoding=\"utf-8\") as f:\n f.write(line + \"\\n\")\n print(\"Line appended\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that compute the greatest common divisor and least common multiple of two numbers.", "response": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\ndef main():\n a = int(input(\"Enter first number: \"))\n b = int(input(\"Enter second number: \"))\n print(\"GCD =\", gcd(a, b))\n print(\"LCM =\", lcm(a, b))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to split a list into chunks of a given size.", "response": "def chunk_list(values, size):\n return [values[i:i + size] for i in range(0, len(values), size)]\n\ndef main():\n values = [1, 2, 3, 4, 5, 6, 7]\n print(chunk_list(values, 3))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to find the longest word in a sentence.", "response": "def main():\n text = input(\"Enter a sentence: \")\n words = text.split()\n longest = max(words, key=len) if words else \"\"\n print(\"Longest word:\", longest)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to update a field in a JSON file.", "response": "import json\n\ndef main():\n file_path = \"data.json\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n data[\"status\"] = \"updated\"\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(data, f, indent=4)\n print(\"JSON updated\")\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to create a rectangle class that calculates area and perimeter.", "response": "class Rectangle:\n def __init__(self, length, width):\n self.length = length\n self.width = width\n\n def area(self):\n return self.length * self.width\n\n def perimeter(self):\n return 2 * (self.length + self.width)\n\ndef main():\n rect = Rectangle(10, 5)\n print(\"Area:\", rect.area())\n print(\"Perimeter:\", rect.perimeter())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that update a field in a JSON file.", "response": "import json\n\ndef main():\n file_path = \"data.json\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n data[\"status\"] = \"updated\"\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(data, f, indent=4)\n print(\"JSON updated\")\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that check whether two strings are anagrams.", "response": "from collections import Counter\n\ndef normalize(text):\n return \"\".join(ch.lower() for ch in text if ch.isalnum())\n\ndef main():\n first = input(\"Enter first string: \")\n second = input(\"Enter second string: \")\n print(\"Anagram\" if Counter(normalize(first)) == Counter(normalize(second)) else \"Not anagram\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to create a calculator class with basic arithmetic methods.", "response": "class Calculator:\n def add(self, a, b):\n return a + b\n\n def subtract(self, a, b):\n return a - b\n\n def multiply(self, a, b):\n return a * b\n\n def divide(self, a, b):\n if b == 0:\n return \"Cannot divide by zero\"\n return a / b\n\ndef main():\n calc = Calculator()\n print(calc.add(10, 5))\n print(calc.subtract(10, 5))\n print(calc.multiply(10, 5))\n print(calc.divide(10, 5))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that sort CSV rows by a given column.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n sort_column = \"name\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n rows = list(reader)\n rows.sort(key=lambda row: row.get(sort_column, \"\"))\n for row in rows:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that filter even numbers from a list.", "response": "def main():\n numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n evens = [n for n in numbers if n % 2 == 0]\n print(evens)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that create a calculator class with basic arithmetic methods.", "response": "class Calculator:\n def add(self, a, b):\n return a + b\n\n def subtract(self, a, b):\n return a - b\n\n def multiply(self, a, b):\n return a * b\n\n def divide(self, a, b):\n if b == 0:\n return \"Cannot divide by zero\"\n return a / b\n\ndef main():\n calc = Calculator()\n print(calc.add(10, 5))\n print(calc.subtract(10, 5))\n print(calc.multiply(10, 5))\n print(calc.divide(10, 5))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to generate the first n Fibonacci numbers.", "response": "def fibonacci(n):\n seq = [0, 1]\n while len(seq) < n:\n seq.append(seq[-1] + seq[-2])\n return seq[:n]\n\ndef main():\n n = int(input(\"Enter how many terms: \"))\n print(fibonacci(n))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that find the missing number in a sequence from 1 to n.", "response": "def main():\n numbers = [1, 2, 3, 5, 6, 7, 8]\n n = 8\n expected = n * (n + 1) // 2\n actual = sum(numbers)\n print(\"Missing number =\", expected - actual)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to sort a list using bubble sort.", "response": "def bubble_sort(values):\n arr = values[:]\n n = len(arr)\n for i in range(n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n return arr\n\ndef main():\n values = [64, 34, 25, 12, 22, 11, 90]\n print(bubble_sort(values))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that sum a numeric column from a CSV file.", "response": "import csv\n\ndef main():\n file_path = \"sales.csv\"\n column = \"amount\"\n total = 0.0\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n total += float(row[column])\n print(\"Total =\", total)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except KeyError:\n print(f\"Column not found: {column}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to remove punctuation from a string.", "response": "import string\n\ndef main():\n text = input(\"Enter a string: \")\n translator = str.maketrans(\"\", \"\", string.punctuation)\n print(text.translate(translator))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to extract all values for a key from a JSON list.", "response": "import json\n\ndef main():\n file_path = \"records.json\"\n key = \"name\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n values = [item.get(key) for item in data if isinstance(item, dict)]\n print(values)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to count the number of lines in a text file.", "response": "def main():\n file_path = \"sample.txt\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n line_count = sum(1 for _ in f)\n print(\"Line count =\", line_count)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that find the maximum subarray sum using Kadane's algorithm.", "response": "def max_subarray_sum(values):\n current = best = values[0]\n for num in values[1:]:\n current = max(num, current + num)\n best = max(best, current)\n return best\n\ndef main():\n values = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\n print(\"Maximum subarray sum =\", max_subarray_sum(values))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to find the factorial of a number.", "response": "def factorial(n):\n result = 1\n for i in range(2, n + 1):\n result *= i\n return result\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Factorial =\", factorial(n))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that print a file with line numbers.", "response": "def main():\n file_path = \"sample.txt\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n for i, line in enumerate(f, start=1):\n print(f\"{i}: {line.rstrip()}\")\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to create a file if it does not exist.", "response": "from pathlib import Path\n\ndef main():\n file_path = Path(\"notes.txt\")\n file_path.touch(exist_ok=True)\n print(f\"{file_path} is ready\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that sort a list using bubble sort.", "response": "def bubble_sort(values):\n arr = values[:]\n n = len(arr)\n for i in range(n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n return arr\n\ndef main():\n values = [64, 34, 25, 12, 22, 11, 90]\n print(bubble_sort(values))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to pretty print a JSON file.", "response": "import json\n\ndef main():\n file_path = \"data.json\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n print(json.dumps(data, indent=4))\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to create a calculator class with basic arithmetic methods.", "response": "class Calculator:\n def add(self, a, b):\n return a + b\n\n def subtract(self, a, b):\n return a - b\n\n def multiply(self, a, b):\n return a * b\n\n def divide(self, a, b):\n if b == 0:\n return \"Cannot divide by zero\"\n return a / b\n\ndef main():\n calc = Calculator()\n print(calc.add(10, 5))\n print(calc.subtract(10, 5))\n print(calc.multiply(10, 5))\n print(calc.divide(10, 5))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that check whether a number is an Armstrong number.", "response": "def is_armstrong(n):\n digits = [int(d) for d in str(n)]\n power = len(digits)\n return sum(d ** power for d in digits) == n\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Armstrong number\" if is_armstrong(n) else \"Not an Armstrong number\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to group numbers by parity in a dictionary.", "response": "def main():\n numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n grouped = {\n \"even\": [n for n in numbers if n % 2 == 0],\n \"odd\": [n for n in numbers if n % 2 != 0],\n }\n print(grouped)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to find the maximum subarray sum using Kadane's algorithm.", "response": "def max_subarray_sum(values):\n current = best = values[0]\n for num in values[1:]:\n current = max(num, current + num)\n best = max(best, current)\n return best\n\ndef main():\n values = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\n print(\"Maximum subarray sum =\", max_subarray_sum(values))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to keep asking the user for a valid integer until the input is correct.", "response": "def main():\n while True:\n try:\n value = int(input(\"Enter an integer: \"))\n print(\"You entered:\", value)\n break\n except ValueError:\n print(\"Invalid input, try again\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that rotate a list to the right by k positions.", "response": "def rotate_right(values, k):\n if not values:\n return values\n k %= len(values)\n return values[-k:] + values[:-k] if k else values[:]\n\ndef main():\n values = [1, 2, 3, 4, 5]\n k = 2\n print(rotate_right(values, k))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to check whether a number is a palindrome.", "response": "def main():\n n = input(\"Enter a number: \")\n print(\"Palindrome\" if n == n[::-1] else \"Not a palindrome\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to keep asking the user for a valid integer until the input is correct.", "response": "def main():\n while True:\n try:\n value = int(input(\"Enter an integer: \"))\n print(\"You entered:\", value)\n break\n except ValueError:\n print(\"Invalid input, try again\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that find the first non-repeating character in a string.", "response": "from collections import Counter\n\ndef main():\n text = input(\"Enter a string: \")\n counts = Counter(text)\n result = next((ch for ch in text if counts[ch] == 1), None)\n print(\"First non-repeating character:\", result if result is not None else \"None\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that keep asking the user for a valid integer until the input is correct.", "response": "def main():\n while True:\n try:\n value = int(input(\"Enter an integer: \"))\n print(\"You entered:\", value)\n break\n except ValueError:\n print(\"Invalid input, try again\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that count word frequencies in a sentence using a dictionary.", "response": "def main():\n text = \"this is a sample sample sentence with sample words\"\n words = text.split()\n freq = {}\n for word in words:\n freq[word] = freq.get(word, 0) + 1\n print(freq)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to print a file with line numbers.", "response": "def main():\n file_path = \"sample.txt\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n for i, line in enumerate(f, start=1):\n print(f\"{i}: {line.rstrip()}\")\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that sum a numeric column from a CSV file.", "response": "import csv\n\ndef main():\n file_path = \"sales.csv\"\n column = \"amount\"\n total = 0.0\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n total += float(row[column])\n print(\"Total =\", total)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except KeyError:\n print(f\"Column not found: {column}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to sort CSV rows by a given column.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n sort_column = \"name\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n rows = list(reader)\n rows.sort(key=lambda row: row.get(sort_column, \"\"))\n for row in rows:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to sum a numeric column from a CSV file.", "response": "import csv\n\ndef main():\n file_path = \"sales.csv\"\n column = \"amount\"\n total = 0.0\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n total += float(row[column])\n print(\"Total =\", total)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except KeyError:\n print(f\"Column not found: {column}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to remove duplicates from a list while preserving order.", "response": "def main():\n numbers = [1, 2, 2, 3, 4, 4, 5, 1, 6]\n unique_numbers = list(dict.fromkeys(numbers))\n print(\"Original list:\", numbers)\n print(\"Without duplicates:\", unique_numbers)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that remove punctuation from a string.", "response": "import string\n\ndef main():\n text = input(\"Enter a string: \")\n translator = str.maketrans(\"\", \"\", string.punctuation)\n print(text.translate(translator))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to merge two JSON objects from files.", "response": "import json\n\ndef main():\n file1 = \"a.json\"\n file2 = \"b.json\"\n try:\n with open(file1, \"r\", encoding=\"utf-8\") as f1, open(file2, \"r\", encoding=\"utf-8\") as f2:\n data1 = json.load(f1)\n data2 = json.load(f2)\n merged = {**data1, **data2}\n print(merged)\n except FileNotFoundError as e:\n print(f\"File not found: {e.filename}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to count word frequencies in a sentence using a dictionary.", "response": "def main():\n text = \"this is a sample sample sentence with sample words\"\n words = text.split()\n freq = {}\n for word in words:\n freq[word] = freq.get(word, 0) + 1\n print(freq)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to merge two sorted lists into one sorted list.", "response": "def merge_sorted_lists(a, b):\n i = j = 0\n merged = []\n while i < len(a) and j < len(b):\n if a[i] <= b[j]:\n merged.append(a[i])\n i += 1\n else:\n merged.append(b[j])\n j += 1\n merged.extend(a[i:])\n merged.extend(b[j:])\n return merged\n\ndef main():\n a = [1, 3, 5, 7]\n b = [2, 4, 6, 8]\n print(merge_sorted_lists(a, b))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to find two numbers in a list that add up to a target.", "response": "def main():\n numbers = [2, 7, 11, 15]\n target = 9\n seen = {}\n for i, num in enumerate(numbers):\n diff = target - num\n if diff in seen:\n print((seen[diff], i))\n return\n seen[num] = i\n print(\"No pair found\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to create a student class that calculates the average marks.", "response": "class Student:\n def __init__(self, name, marks):\n self.name = name\n self.marks = marks\n\n def average(self):\n return sum(self.marks) / len(self.marks) if self.marks else 0\n\ndef main():\n student = Student(\"Alice\", [85, 90, 78])\n print(student.name, \"average =\", student.average())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to count the vowels in a string.", "response": "def count_vowels(text):\n vowels = \"aeiouAEIOU\"\n return sum(1 for ch in text if ch in vowels)\n\ndef main():\n text = input(\"Enter a string: \")\n print(\"Vowel count =\", count_vowels(text))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that merge two sorted lists into one sorted list.", "response": "def merge_sorted_lists(a, b):\n i = j = 0\n merged = []\n while i < len(a) and j < len(b):\n if a[i] <= b[j]:\n merged.append(a[i])\n i += 1\n else:\n merged.append(b[j])\n j += 1\n merged.extend(a[i:])\n merged.extend(b[j:])\n return merged\n\ndef main():\n a = [1, 3, 5, 7]\n b = [2, 4, 6, 8]\n print(merge_sorted_lists(a, b))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to perform binary search on a sorted list.", "response": "def binary_search(values, target):\n left, right = 0, len(values) - 1\n while left <= right:\n mid = (left + right) // 2\n if values[mid] == target:\n return mid\n if values[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n return -1\n\ndef main():\n values = [1, 3, 5, 7, 9, 11, 13]\n target = 7\n print(\"Index:\", binary_search(values, target))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to filter CSV rows by a column value.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n column = \"city\"\n target = \"Bangalore\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n matches = [row for row in reader if row.get(column) == target]\n for row in matches:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to find the second largest number in a list.", "response": "def main():\n numbers = [12, 45, 7, 89, 23, 89, 5]\n unique_sorted = sorted(set(numbers))\n second_largest = unique_sorted[-2] if len(unique_sorted) >= 2 else None\n print(\"Second largest:\", second_largest)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to check whether a number is a palindrome.", "response": "def main():\n n = input(\"Enter a number: \")\n print(\"Palindrome\" if n == n[::-1] else \"Not a palindrome\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that copy the contents of one file into another file.", "response": "def main():\n source = \"input.txt\"\n destination = \"copy.txt\"\n try:\n with open(source, \"r\", encoding=\"utf-8\") as src:\n content = src.read()\n with open(destination, \"w\", encoding=\"utf-8\") as dst:\n dst.write(content)\n print(\"File copied successfully\")\n except FileNotFoundError:\n print(f\"File not found: {source}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to create a simple bank account class with deposit and withdraw methods.", "response": "class BankAccount:\n def __init__(self, balance=0):\n self.balance = balance\n\n def deposit(self, amount):\n self.balance += amount\n\n def withdraw(self, amount):\n if amount > self.balance:\n print(\"Insufficient balance\")\n return\n self.balance -= amount\n\ndef main():\n account = BankAccount(1000)\n account.deposit(500)\n account.withdraw(200)\n print(\"Balance:\", account.balance)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to rotate a list to the right by k positions.", "response": "def rotate_right(values, k):\n if not values:\n return values\n k %= len(values)\n return values[-k:] + values[:-k] if k else values[:]\n\ndef main():\n values = [1, 2, 3, 4, 5]\n k = 2\n print(rotate_right(values, k))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that read a CSV file and print all rows.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that encrypt a string using a Caesar cipher with shift 3.", "response": "def shift_char(ch, shift):\n if ch.isalpha():\n base = ord(\"A\") if ch.isupper() else ord(\"a\")\n return chr((ord(ch) - base + shift) % 26 + base)\n return ch\n\ndef main():\n text = input(\"Enter text: \")\n encrypted = \"\".join(shift_char(ch, 3) for ch in text)\n print(encrypted)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to create a simple bank account class with deposit and withdraw methods.", "response": "class BankAccount:\n def __init__(self, balance=0):\n self.balance = balance\n\n def deposit(self, amount):\n self.balance += amount\n\n def withdraw(self, amount):\n if amount > self.balance:\n print(\"Insufficient balance\")\n return\n self.balance -= amount\n\ndef main():\n account = BankAccount(1000)\n account.deposit(500)\n account.withdraw(200)\n print(\"Balance:\", account.balance)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to pretty print a JSON file.", "response": "import json\n\ndef main():\n file_path = \"data.json\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n print(json.dumps(data, indent=4))\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that remove punctuation from a string.", "response": "import string\n\ndef main():\n text = input(\"Enter a string: \")\n translator = str.maketrans(\"\", \"\", string.punctuation)\n print(text.translate(translator))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to extract all values for a key from a JSON list.", "response": "import json\n\ndef main():\n file_path = \"records.json\"\n key = \"name\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n values = [item.get(key) for item in data if isinstance(item, dict)]\n print(values)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that find the second largest number in a list.", "response": "def main():\n numbers = [12, 45, 7, 89, 23, 89, 5]\n unique_sorted = sorted(set(numbers))\n second_largest = unique_sorted[-2] if len(unique_sorted) >= 2 else None\n print(\"Second largest:\", second_largest)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that merge two JSON objects from files.", "response": "import json\n\ndef main():\n file1 = \"a.json\"\n file2 = \"b.json\"\n try:\n with open(file1, \"r\", encoding=\"utf-8\") as f1, open(file2, \"r\", encoding=\"utf-8\") as f2:\n data1 = json.load(f1)\n data2 = json.load(f2)\n merged = {**data1, **data2}\n print(merged)\n except FileNotFoundError as e:\n print(f\"File not found: {e.filename}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that remove duplicates from a list while preserving order.", "response": "def main():\n numbers = [1, 2, 2, 3, 4, 4, 5, 1, 6]\n unique_numbers = list(dict.fromkeys(numbers))\n print(\"Original list:\", numbers)\n print(\"Without duplicates:\", unique_numbers)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to invert a dictionary with unique values.", "response": "def main():\n data = {\"a\": 1, \"b\": 2, \"c\": 3}\n inverted = {value: key for key, value in data.items()}\n print(inverted)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to invert a dictionary with unique values.", "response": "def main():\n data = {\"a\": 1, \"b\": 2, \"c\": 3}\n inverted = {value: key for key, value in data.items()}\n print(inverted)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that encrypt a string using a Caesar cipher with shift 3.", "response": "def shift_char(ch, shift):\n if ch.isalpha():\n base = ord(\"A\") if ch.isupper() else ord(\"a\")\n return chr((ord(ch) - base + shift) % 26 + base)\n return ch\n\ndef main():\n text = input(\"Enter text: \")\n encrypted = \"\".join(shift_char(ch, 3) for ch in text)\n print(encrypted)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that invert a dictionary with unique values.", "response": "def main():\n data = {\"a\": 1, \"b\": 2, \"c\": 3}\n inverted = {value: key for key, value in data.items()}\n print(inverted)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to update a field in a JSON file.", "response": "import json\n\ndef main():\n file_path = \"data.json\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n data[\"status\"] = \"updated\"\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(data, f, indent=4)\n print(\"JSON updated\")\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that copy the contents of one file into another file.", "response": "def main():\n source = \"input.txt\"\n destination = \"copy.txt\"\n try:\n with open(source, \"r\", encoding=\"utf-8\") as src:\n content = src.read()\n with open(destination, \"w\", encoding=\"utf-8\") as dst:\n dst.write(content)\n print(\"File copied successfully\")\n except FileNotFoundError:\n print(f\"File not found: {source}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that generate the first n Fibonacci numbers.", "response": "def fibonacci(n):\n seq = [0, 1]\n while len(seq) < n:\n seq.append(seq[-1] + seq[-2])\n return seq[:n]\n\ndef main():\n n = int(input(\"Enter how many terms: \"))\n print(fibonacci(n))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to check whether a number is prime.", "response": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Prime\" if is_prime(n) else \"Not prime\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to count the number of words in a sentence.", "response": "def main():\n text = input(\"Enter a sentence: \")\n words = text.split()\n print(\"Word count =\", len(words))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to find two numbers in a list that add up to a target.", "response": "def main():\n numbers = [2, 7, 11, 15]\n target = 9\n seen = {}\n for i, num in enumerate(numbers):\n diff = target - num\n if diff in seen:\n print((seen[diff], i))\n return\n seen[num] = i\n print(\"No pair found\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to handle division by zero with exception handling.", "response": "def main():\n try:\n a = float(input(\"Enter numerator: \"))\n b = float(input(\"Enter denominator: \"))\n print(\"Result =\", a / b)\n except ZeroDivisionError:\n print(\"Cannot divide by zero\")\n except ValueError:\n print(\"Please enter valid numbers\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to split a list into chunks of a given size.", "response": "def chunk_list(values, size):\n return [values[i:i + size] for i in range(0, len(values), size)]\n\ndef main():\n values = [1, 2, 3, 4, 5, 6, 7]\n print(chunk_list(values, 3))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that flatten a nested list.", "response": "def flatten(items):\n result = []\n for item in items:\n if isinstance(item, list):\n result.extend(flatten(item))\n else:\n result.append(item)\n return result\n\ndef main():\n items = [1, [2, 3], [4, [5, 6]], 7]\n print(flatten(items))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to extract all values for a key from a JSON list.", "response": "import json\n\ndef main():\n file_path = \"records.json\"\n key = \"name\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n values = [item.get(key) for item in data if isinstance(item, dict)]\n print(values)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that keep asking the user for a valid integer until the input is correct.", "response": "def main():\n while True:\n try:\n value = int(input(\"Enter an integer: \"))\n print(\"You entered:\", value)\n break\n except ValueError:\n print(\"Invalid input, try again\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to remove punctuation from a string.", "response": "import string\n\ndef main():\n text = input(\"Enter a string: \")\n translator = str.maketrans(\"\", \"\", string.punctuation)\n print(text.translate(translator))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to create a rectangle class that calculates area and perimeter.", "response": "class Rectangle:\n def __init__(self, length, width):\n self.length = length\n self.width = width\n\n def area(self):\n return self.length * self.width\n\n def perimeter(self):\n return 2 * (self.length + self.width)\n\ndef main():\n rect = Rectangle(10, 5)\n print(\"Area:\", rect.area())\n print(\"Perimeter:\", rect.perimeter())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to check whether two strings are anagrams.", "response": "from collections import Counter\n\ndef normalize(text):\n return \"\".join(ch.lower() for ch in text if ch.isalnum())\n\ndef main():\n first = input(\"Enter first string: \")\n second = input(\"Enter second string: \")\n print(\"Anagram\" if Counter(normalize(first)) == Counter(normalize(second)) else \"Not anagram\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to sum a numeric column from a CSV file.", "response": "import csv\n\ndef main():\n file_path = \"sales.csv\"\n column = \"amount\"\n total = 0.0\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n total += float(row[column])\n print(\"Total =\", total)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except KeyError:\n print(f\"Column not found: {column}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to invert a dictionary with unique values.", "response": "def main():\n data = {\"a\": 1, \"b\": 2, \"c\": 3}\n inverted = {value: key for key, value in data.items()}\n print(inverted)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that pretty print a JSON file.", "response": "import json\n\ndef main():\n file_path = \"data.json\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n print(json.dumps(data, indent=4))\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to update a field in a JSON file.", "response": "import json\n\ndef main():\n file_path = \"data.json\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n data[\"status\"] = \"updated\"\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(data, f, indent=4)\n print(\"JSON updated\")\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to filter even numbers from a list.", "response": "def main():\n numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n evens = [n for n in numbers if n % 2 == 0]\n print(evens)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that filter CSV rows by a column value.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n column = \"city\"\n target = \"Bangalore\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n matches = [row for row in reader if row.get(column) == target]\n for row in matches:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to convert a string to title case.", "response": "def main():\n text = input(\"Enter text: \")\n print(text.title())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that sort a dictionary by its values.", "response": "def main():\n data = {\"a\": 3, \"b\": 1, \"c\": 2}\n sorted_data = dict(sorted(data.items(), key=lambda item: item[1]))\n print(sorted_data)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that find the longest word in a sentence.", "response": "def main():\n text = input(\"Enter a sentence: \")\n words = text.split()\n longest = max(words, key=len) if words else \"\"\n print(\"Longest word:\", longest)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to read a CSV file and print all rows.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to copy the contents of one file into another file.", "response": "def main():\n source = \"input.txt\"\n destination = \"copy.txt\"\n try:\n with open(source, \"r\", encoding=\"utf-8\") as src:\n content = src.read()\n with open(destination, \"w\", encoding=\"utf-8\") as dst:\n dst.write(content)\n print(\"File copied successfully\")\n except FileNotFoundError:\n print(f\"File not found: {source}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that create a student class that calculates the average marks.", "response": "class Student:\n def __init__(self, name, marks):\n self.name = name\n self.marks = marks\n\n def average(self):\n return sum(self.marks) / len(self.marks) if self.marks else 0\n\ndef main():\n student = Student(\"Alice\", [85, 90, 78])\n print(student.name, \"average =\", student.average())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that count the vowels in a string.", "response": "def count_vowels(text):\n vowels = \"aeiouAEIOU\"\n return sum(1 for ch in text if ch in vowels)\n\ndef main():\n text = input(\"Enter a string: \")\n print(\"Vowel count =\", count_vowels(text))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to find the second largest number in a list.", "response": "def main():\n numbers = [12, 45, 7, 89, 23, 89, 5]\n unique_sorted = sorted(set(numbers))\n second_largest = unique_sorted[-2] if len(unique_sorted) >= 2 else None\n print(\"Second largest:\", second_largest)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that find the missing number in a sequence from 1 to n.", "response": "def main():\n numbers = [1, 2, 3, 5, 6, 7, 8]\n n = 8\n expected = n * (n + 1) // 2\n actual = sum(numbers)\n print(\"Missing number =\", expected - actual)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that count the frequency of elements in a list.", "response": "from collections import Counter\n\ndef main():\n values = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]\n print(dict(Counter(values)))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that invert a dictionary with unique values.", "response": "def main():\n data = {\"a\": 1, \"b\": 2, \"c\": 3}\n inverted = {value: key for key, value in data.items()}\n print(inverted)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to convert a string to title case.", "response": "def main():\n text = input(\"Enter text: \")\n print(text.title())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to sort a dictionary by its values.", "response": "def main():\n data = {\"a\": 3, \"b\": 1, \"c\": 2}\n sorted_data = dict(sorted(data.items(), key=lambda item: item[1]))\n print(sorted_data)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to find two numbers in a list that add up to a target.", "response": "def main():\n numbers = [2, 7, 11, 15]\n target = 9\n seen = {}\n for i, num in enumerate(numbers):\n diff = target - num\n if diff in seen:\n print((seen[diff], i))\n return\n seen[num] = i\n print(\"No pair found\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to check whether a number is a palindrome.", "response": "def main():\n n = input(\"Enter a number: \")\n print(\"Palindrome\" if n == n[::-1] else \"Not a palindrome\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that count the frequency of elements in a list.", "response": "from collections import Counter\n\ndef main():\n values = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]\n print(dict(Counter(values)))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to handle division by zero with exception handling.", "response": "def main():\n try:\n a = float(input(\"Enter numerator: \"))\n b = float(input(\"Enter denominator: \"))\n print(\"Result =\", a / b)\n except ZeroDivisionError:\n print(\"Cannot divide by zero\")\n except ValueError:\n print(\"Please enter valid numbers\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that find two numbers in a list that add up to a target.", "response": "def main():\n numbers = [2, 7, 11, 15]\n target = 9\n seen = {}\n for i, num in enumerate(numbers):\n diff = target - num\n if diff in seen:\n print((seen[diff], i))\n return\n seen[num] = i\n print(\"No pair found\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to find the first non-repeating character in a string.", "response": "from collections import Counter\n\ndef main():\n text = input(\"Enter a string: \")\n counts = Counter(text)\n result = next((ch for ch in text if counts[ch] == 1), None)\n print(\"First non-repeating character:\", result if result is not None else \"None\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that perform binary search on a sorted list.", "response": "def binary_search(values, target):\n left, right = 0, len(values) - 1\n while left <= right:\n mid = (left + right) // 2\n if values[mid] == target:\n return mid\n if values[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n return -1\n\ndef main():\n values = [1, 3, 5, 7, 9, 11, 13]\n target = 7\n print(\"Index:\", binary_search(values, target))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to count the frequency of elements in a list.", "response": "from collections import Counter\n\ndef main():\n values = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]\n print(dict(Counter(values)))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to check whether a number is an Armstrong number.", "response": "def is_armstrong(n):\n digits = [int(d) for d in str(n)]\n power = len(digits)\n return sum(d ** power for d in digits) == n\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Armstrong number\" if is_armstrong(n) else \"Not an Armstrong number\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that create a simple bank account class with deposit and withdraw methods.", "response": "class BankAccount:\n def __init__(self, balance=0):\n self.balance = balance\n\n def deposit(self, amount):\n self.balance += amount\n\n def withdraw(self, amount):\n if amount > self.balance:\n print(\"Insufficient balance\")\n return\n self.balance -= amount\n\ndef main():\n account = BankAccount(1000)\n account.deposit(500)\n account.withdraw(200)\n print(\"Balance:\", account.balance)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to encrypt a string using a Caesar cipher with shift 3.", "response": "def shift_char(ch, shift):\n if ch.isalpha():\n base = ord(\"A\") if ch.isupper() else ord(\"a\")\n return chr((ord(ch) - base + shift) % 26 + base)\n return ch\n\ndef main():\n text = input(\"Enter text: \")\n encrypted = \"\".join(shift_char(ch, 3) for ch in text)\n print(encrypted)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that check whether a number is prime.", "response": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Prime\" if is_prime(n) else \"Not prime\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to create a calculator class with basic arithmetic methods.", "response": "class Calculator:\n def add(self, a, b):\n return a + b\n\n def subtract(self, a, b):\n return a - b\n\n def multiply(self, a, b):\n return a * b\n\n def divide(self, a, b):\n if b == 0:\n return \"Cannot divide by zero\"\n return a / b\n\ndef main():\n calc = Calculator()\n print(calc.add(10, 5))\n print(calc.subtract(10, 5))\n print(calc.multiply(10, 5))\n print(calc.divide(10, 5))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that reverse a string entered by the user.", "response": "def main():\n text = input(\"Enter a string: \")\n print(text[::-1])\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to compute the greatest common divisor and least common multiple of two numbers.", "response": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\ndef main():\n a = int(input(\"Enter first number: \"))\n b = int(input(\"Enter second number: \"))\n print(\"GCD =\", gcd(a, b))\n print(\"LCM =\", lcm(a, b))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to check whether a number is prime.", "response": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Prime\" if is_prime(n) else \"Not prime\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that split a list into chunks of a given size.", "response": "def chunk_list(values, size):\n return [values[i:i + size] for i in range(0, len(values), size)]\n\ndef main():\n values = [1, 2, 3, 4, 5, 6, 7]\n print(chunk_list(values, 3))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to sort CSV rows by a given column.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n sort_column = \"name\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n rows = list(reader)\n rows.sort(key=lambda row: row.get(sort_column, \"\"))\n for row in rows:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to find the maximum subarray sum using Kadane's algorithm.", "response": "def max_subarray_sum(values):\n current = best = values[0]\n for num in values[1:]:\n current = max(num, current + num)\n best = max(best, current)\n return best\n\ndef main():\n values = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\n print(\"Maximum subarray sum =\", max_subarray_sum(values))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that flatten a nested list.", "response": "def flatten(items):\n result = []\n for item in items:\n if isinstance(item, list):\n result.extend(flatten(item))\n else:\n result.append(item)\n return result\n\ndef main():\n items = [1, [2, 3], [4, [5, 6]], 7]\n print(flatten(items))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to group numbers by parity in a dictionary.", "response": "def main():\n numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n grouped = {\n \"even\": [n for n in numbers if n % 2 == 0],\n \"odd\": [n for n in numbers if n % 2 != 0],\n }\n print(grouped)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that check whether a number is an Armstrong number.", "response": "def is_armstrong(n):\n digits = [int(d) for d in str(n)]\n power = len(digits)\n return sum(d ** power for d in digits) == n\n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(\"Armstrong number\" if is_armstrong(n) else \"Not an Armstrong number\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to create a simple bank account class with deposit and withdraw methods.", "response": "class BankAccount:\n def __init__(self, balance=0):\n self.balance = balance\n\n def deposit(self, amount):\n self.balance += amount\n\n def withdraw(self, amount):\n if amount > self.balance:\n print(\"Insufficient balance\")\n return\n self.balance -= amount\n\ndef main():\n account = BankAccount(1000)\n account.deposit(500)\n account.withdraw(200)\n print(\"Balance:\", account.balance)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that extract all values for a key from a JSON list.", "response": "import json\n\ndef main():\n file_path = \"records.json\"\n key = \"name\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n values = [item.get(key) for item in data if isinstance(item, dict)]\n print(values)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that create a rectangle class that calculates area and perimeter.", "response": "class Rectangle:\n def __init__(self, length, width):\n self.length = length\n self.width = width\n\n def area(self):\n return self.length * self.width\n\n def perimeter(self):\n return 2 * (self.length + self.width)\n\ndef main():\n rect = Rectangle(10, 5)\n print(\"Area:\", rect.area())\n print(\"Perimeter:\", rect.perimeter())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to remove duplicates from a list while preserving order.", "response": "def main():\n numbers = [1, 2, 2, 3, 4, 4, 5, 1, 6]\n unique_numbers = list(dict.fromkeys(numbers))\n print(\"Original list:\", numbers)\n print(\"Without duplicates:\", unique_numbers)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that filter CSV rows by a column value.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n column = \"city\"\n target = \"Bangalore\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n matches = [row for row in reader if row.get(column) == target]\n for row in matches:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that check whether a string is a palindrome ignoring spaces and punctuation.", "response": "def is_palindrome(text):\n cleaned = \"\".join(ch.lower() for ch in text if ch.isalnum())\n return cleaned == cleaned[::-1]\n\ndef main():\n text = input(\"Enter a string: \")\n print(\"Palindrome\" if is_palindrome(text) else \"Not a palindrome\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to sort CSV rows by a given column.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n sort_column = \"name\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n rows = list(reader)\n rows.sort(key=lambda row: row.get(sort_column, \"\"))\n for row in rows:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to print a file with line numbers.", "response": "def main():\n file_path = \"sample.txt\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n for i, line in enumerate(f, start=1):\n print(f\"{i}: {line.rstrip()}\")\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to flatten a nested list.", "response": "def flatten(items):\n result = []\n for item in items:\n if isinstance(item, list):\n result.extend(flatten(item))\n else:\n result.append(item)\n return result\n\ndef main():\n items = [1, [2, 3], [4, [5, 6]], 7]\n print(flatten(items))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to flatten a nested list.", "response": "def flatten(items):\n result = []\n for item in items:\n if isinstance(item, list):\n result.extend(flatten(item))\n else:\n result.append(item)\n return result\n\ndef main():\n items = [1, [2, 3], [4, [5, 6]], 7]\n print(flatten(items))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that convert a string to title case.", "response": "def main():\n text = input(\"Enter text: \")\n print(text.title())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to check whether a string is a palindrome ignoring spaces and punctuation.", "response": "def is_palindrome(text):\n cleaned = \"\".join(ch.lower() for ch in text if ch.isalnum())\n return cleaned == cleaned[::-1]\n\ndef main():\n text = input(\"Enter a string: \")\n print(\"Palindrome\" if is_palindrome(text) else \"Not a palindrome\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that check whether a string is a palindrome ignoring spaces and punctuation.", "response": "def is_palindrome(text):\n cleaned = \"\".join(ch.lower() for ch in text if ch.isalnum())\n return cleaned == cleaned[::-1]\n\ndef main():\n text = input(\"Enter a string: \")\n print(\"Palindrome\" if is_palindrome(text) else \"Not a palindrome\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that group numbers by parity in a dictionary.", "response": "def main():\n numbers = [1, 2, 3, 4, 5, 6, 7, 8]\n grouped = {\n \"even\": [n for n in numbers if n % 2 == 0],\n \"odd\": [n for n in numbers if n % 2 != 0],\n }\n print(grouped)\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that sort CSV rows by a given column.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n sort_column = \"name\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n rows = list(reader)\n rows.sort(key=lambda row: row.get(sort_column, \"\"))\n for row in rows:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to convert a string to title case.", "response": "def main():\n text = input(\"Enter text: \")\n print(text.title())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to read a CSV file and print all rows.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that perform binary search on a sorted list.", "response": "def binary_search(values, target):\n left, right = 0, len(values) - 1\n while left <= right:\n mid = (left + right) // 2\n if values[mid] == target:\n return mid\n if values[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n return -1\n\ndef main():\n values = [1, 3, 5, 7, 9, 11, 13]\n target = 7\n print(\"Index:\", binary_search(values, target))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to create a student class that calculates the average marks.", "response": "class Student:\n def __init__(self, name, marks):\n self.name = name\n self.marks = marks\n\n def average(self):\n return sum(self.marks) / len(self.marks) if self.marks else 0\n\ndef main():\n student = Student(\"Alice\", [85, 90, 78])\n print(student.name, \"average =\", student.average())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that merge two JSON objects from files.", "response": "import json\n\ndef main():\n file1 = \"a.json\"\n file2 = \"b.json\"\n try:\n with open(file1, \"r\", encoding=\"utf-8\") as f1, open(file2, \"r\", encoding=\"utf-8\") as f2:\n data1 = json.load(f1)\n data2 = json.load(f2)\n merged = {**data1, **data2}\n print(merged)\n except FileNotFoundError as e:\n print(f\"File not found: {e.filename}\")\n except json.JSONDecodeError:\n print(\"Invalid JSON file\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Create a runnable Python script that count the number of words in a sentence.", "response": "def main():\n text = input(\"Enter a sentence: \")\n words = text.split()\n print(\"Word count =\", len(words))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Generate a Python program that create a student class that calculates the average marks.", "response": "class Student:\n def __init__(self, name, marks):\n self.name = name\n self.marks = marks\n\n def average(self):\n return sum(self.marks) / len(self.marks) if self.marks else 0\n\ndef main():\n student = Student(\"Alice\", [85, 90, 78])\n print(student.name, \"average =\", student.average())\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to find the first non-repeating character in a string.", "response": "from collections import Counter\n\ndef main():\n text = input(\"Enter a string: \")\n counts = Counter(text)\n result = next((ch for ch in text if counts[ch] == 1), None)\n print(\"First non-repeating character:\", result if result is not None else \"None\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Build a complete Python script to count the number of lines in a text file.", "response": "def main():\n file_path = \"sample.txt\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n line_count = sum(1 for _ in f)\n print(\"Line count =\", line_count)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to print a file with line numbers.", "response": "def main():\n file_path = \"sample.txt\"\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n for i, line in enumerate(f, start=1):\n print(f\"{i}: {line.rstrip()}\")\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Write a complete Python program to filter CSV rows by a column value.", "response": "import csv\n\ndef main():\n file_path = \"data.csv\"\n column = \"city\"\n target = \"Bangalore\"\n try:\n with open(file_path, \"r\", newline=\"\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f)\n matches = [row for row in reader if row.get(column) == target]\n for row in matches:\n print(row)\n except FileNotFoundError:\n print(f\"File not found: {file_path}\")\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to count the vowels in a string.", "response": "def count_vowels(text):\n vowels = \"aeiouAEIOU\"\n return sum(1 for ch in text if ch in vowels)\n\ndef main():\n text = input(\"Enter a string: \")\n print(\"Vowel count =\", count_vowels(text))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction": "Provide a full Python program to flatten a nested list.", "response": "def flatten(items):\n result = []\n for item in items:\n if isinstance(item, list):\n result.extend(flatten(item))\n else:\n result.append(item)\n return result\n\ndef main():\n items = [1, [2, 3], [4, [5, 6]], 7]\n print(flatten(items))\n\nif __name__ == \"__main__\":\n main()\n"} {"instruction":"Write a complete Python program to convert an integer to a string.","response":"def main():\n number = 12345\n text = str(number)\n print('Integer:', number)\n print('String:', text)\n\nif __name__ == '__main__':\n main()\n"} {"instruction":"Write a complete Python program to convert a string to an integer.","response":"def main():\n text = '12345'\n number = int(text)\n print('String:', text)\n print('Integer:', number)\n\nif __name__ == '__main__':\n main()\n"} {"instruction":"Write a complete Python program to reverse a number.","response":"def main():\n number = int(input('Enter a number: '))\n reversed_number = int(str(number)[::-1])\n print('Reversed number =', reversed_number)\n\nif __name__ == '__main__':\n main()\n"} {"instruction":"Write a complete Python program to check whether a number is a palindrome.","response":"def main():\n number = int(input('Enter a number: '))\n reversed_number = int(str(number)[::-1])\n\n if number == reversed_number:\n print('Palindrome')\n else:\n print('Not a palindrome')\n\nif __name__ == '__main__':\n main()\n"} {"instruction":"Write a complete Python program to calculate the sum of digits of a number.","response":"def main():\n number = int(input('Enter a number: '))\n digit_sum = sum(int(digit) for digit in str(number))\n print('Digit sum =', digit_sum)\n\nif __name__ == '__main__':\n main()\n"} {"instruction":"Write a complete Python program to calculate the sum of digits of a number.","response":"def main():\n number = int(input('Enter a number: '))\n digit_sum = sum(int(digit) for digit in str(number))\n print('Digit sum =', digit_sum)\n\nif __name__ == '__main__':\n main()\n"} {"instruction":"Write a complete Python program to extract each digit from a number.","response":"def main():\n number = input('Enter a number: ')\n\n for digit in number:\n print(digit)\n\nif __name__ == '__main__':\n main()\n"} {"instruction":"Write a complete Python program to determine whether a number is an Armstrong number.","response":"def main():\n number = int(input('Enter a number: '))\n digits = [int(d) for d in str(number)]\n power = len(digits)\n\n armstrong_sum = sum(d ** power for d in digits)\n\n if armstrong_sum == number:\n print('Armstrong Number')\n else:\n print('Not an Armstrong Number')\n\nif __name__ == '__main__':\n main()\n"}