text
stringlengths
170
7.88k
<s>[INST] Instruction: Create a function to calculate the sum of a sequence of integers. Input: [1, 2, 3, 4, 5] [/INST] Output: # Python code def sum_sequence(sequence): sum = 0 for num in sequence: sum += num return sum</s>
<s>[INST] Instruction: Generate a Python code for crawling a website for a specific type of data. Input: website: www.example.com data to crawl: phone numbers [/INST] Output: import requests import re def crawl_website_for_phone_numbers(website): response = requests.get(website) phone_numbers = re.findall('\d{3}-\d{3}-\d{4}', response.text) return phone_numbers if __name__ == '__main__': print(crawl_website_for_phone_numbers('www.example.com'))</s>
<s>[INST] Instruction: Create a Python list comprehension to get the squared values of a list [1, 2, 3, 5, 8, 13]. Input: [/INST] Output: [x*x for x in [1, 2, 3, 5, 8, 13]]</s>
<s>[INST] Instruction: Generate a python script to perform this action. Input: Given a string, remove all the consecutive duplicates from the string. Input: "AAABBCCCD" [/INST] Output: def remove_duplicates(string): result = "" prev = '' for char in string: if char != prev: result += char prev = char return result result = remove_duplicates("AAABBCCCD") print(result)</s>
<s>[INST] Instruction: Write a python script to generates random numbers between 0 and 9 that are divisible by 3. Input: [/INST] Output: def generate_random_divisible_number(): import random while True: # Generate a random number process = random.randint(0, 9) # Check if the number is divisible by 3 if process % 3 == 0: # If it is divisible, return it return process</s>
<s>[INST] Instruction: Write a Python code to get the third largest element in a given row. Input: [12, 13, 13, 45, 22, 99] [/INST] Output: def third_largest(lst): if len(lst) < 3: return distinct = [] for i in lst: if i not in distinct: distinct.append(i) distinct.sort(reverse=True) return distinct[2]</s>
<s>[INST] Instruction: Generate a REST API with Python and Flask that allows users to create, read, update, and delete records from a database. Input: Not applicable [/INST] Output: from flask import Flask, request from flask_sqlalchemy import SQLAlchemy app = Flask(name) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class Record(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(120), unique=True) db.create_all() @app.route('/records', methods=['GET']) def get_records(): records = Record.query.all() return {'records':[record.name for record in records]} @app.route('/records', methods=['POST']) def create_record(): record = Record(name=request.json['name']) db.session.add(record) db.session.commit() return {'id': record.id} @app.route('/records/int:id', methods=['PUT']) def update_record(id): record = Record.query.get(id) record.name = request.json['name'] db.session.commit() return {'message': 'Record updated'} @app.route('/records/int:id', methods=['DELETE']) def delete_record(id): Record.query.filter_by(id=id).delete() db.session.commit() return {'message': 'Record deleted'} if name == 'main': app.run(debug=True)</s>
<s>[INST] Instruction: Create a Python function that takes in a string and a list of words and returns true if the string contains all the words in the list. Input: 'This is a test', ['test', 'this', 'is'] [/INST] Output: def contains_words(input_string, words): for word in words: if word not in input_string: return False return True print(contains_words('This is a test', ['test', 'this', 'is'])) # True</s>
<s>[INST] Instruction: What should this Python program do? Input: def is_palindrome(s): '''Write your code here.''' [/INST] Output: def is_palindrome(s): '''This function returns True if the string s is a palindrome and False if it isn't.''' return s == s[::-1] # Checks if s is the same as its reverse.</s>
<s>[INST] Instruction: Create a Python program to sort and print out the elements of an array of integers. Input: [17, 41, 5, 22, 54, 6, 29, 3, 13] [/INST] Output: arr = [17, 41, 5, 22, 54, 6, 29, 3, 13] arr.sort() print(arr) # Output: [3, 5, 6, 13, 17, 22, 29, 41, 54]</s>
<s>[INST] Instruction: Generate a Python program that adds two then doubles the result. Input: [/INST] Output: def double_add(num1, num2): return (num1 + num2) * 2</s>
<s>[INST] Instruction: Write a python program to extract the non-vowel words in a sentence. Input: This machine learning project is challenging. [/INST] Output: def extract_words(sentence): non_vowel_words = [] words = sentence.split() vowels = ['a','e','i','o','u','A','E','I','O','U'] for word in words: if not any(char in vowels for char in word): non_vowel_words.append(word) return non_vowel_words</s>
<s>[INST] Instruction: Write a Python program to calculate the average of a list of positive integers and output the result. Input: List of positive integers: [1, 5, 6, 7, 8] [/INST] Output: list_of_positive_integers = [1, 5, 6, 7, 8] total = sum(list_of_positive_integers) avg = total/len(list_of_positive_integers) print("The average of the list of positive integers is {}".format(avg))</s>
<s>[INST] Instruction: Develop a function in Python that prints out the Pascal's triangle for a given number of rows. Input: [/INST] Output: def pascal_triangle(n): trow = [1] y = [0] for x in range(max(n, 0)): print(trow) trow=[l+r for l,r in zip(trow + y, y + trow)] return n>=1 pascal_triangle(5)</s>
<s>[INST] Instruction: Implement a decision-making algorithm for a rock-paper-scissors game using Python. Input: [/INST] Output: # Rock, paper, scissors game! def play_game(player1, player2): # Define the winning rules rules = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'} if player1 == player2: return 'It is a draw!' elif rules[player1] == player2: return 'Player 1 wins!' elif rules[player2] == player1: return 'Player 2 wins!' # Get user input player1 = input('Player 1, make a choice: rock, paper, or scissors? ').lower() player2 = input('Player 2, make a choice: rock, paper, or scissors? ').lower() # Start the game and get the result result = play_game(player1, player2) print(result)</s>
<s>[INST] Instruction: Collate a machine learning model in Python that distinguishes between cats and dogs. Input: A dataset of 800 images of cats and dogs [/INST] Output: import numpy as np import keras from keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten from keras.models import Sequential from keras.preprocessing.image import ImageDataGenerator # Create the neural network model model = Sequential() # Input layer model.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) # Hidden layers model.add(MaxPooling2D(pool_size = (2, 2))) model.add(Dropout(0.3)) model.add(Conv2D(64, (3, 3), activation = 'relu')) model.add(MaxPooling2D(pool_size = (2, 2))) model.add(Dropout(0.3)) model.add(Conv2D(64, (3, 3), activation = 'relu')) model.add(MaxPooling2D(pool_size = (2, 2))) model.add(Dropout(0.3)) # Output layer model.add(Flatten()) model.add(Dense(units = 128, activation = 'relu')) model.add(Dense(units = 1, activation = 'sigmoid')) # Compile the model model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy']) # Create data generator datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) # Fit the model train_generator = datagen.flow_from_directory(directory = '/path/to/dataset', target_size = (64, 64), color_mode = 'rgb', class_mode = 'binary', batch_size = 32) model.fit_generator(generator = train_generator, steps_per_epoch = 800, epochs = 5, validation_data = test_generator, validation_steps = 200)</s>
<s>[INST] Instruction: Write a Python program to find all the numbers divisible by a certain number within a certain range. Input: int m=36, int n=74, int divisor=6 [/INST] Output: def find_numbers_divisible_by(m, n, divisor): divisible_numbers = [] for i in range(m, n+1): if i % divisor == 0: divisible_numbers.append(i) return divisible_numbers</s>
<s>[INST] Instruction: Implement a Python function that will take two strings and return true if the first string contains the second. Input: query = "catering" word = "cat" [/INST] Output: def check_contains(query, word): if query.find(word) != -1: return True return False result = check_contains(query, word)</s>
<s>[INST] Instruction: Write an algorithm in Python 3 that calculates the factorial of a number. Input: Not applicable [/INST] Output: def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)</s>
<s>[INST] Instruction: Develop a Python function to predict the class labels of a given set of data. Input: The dataset contains 4 features: Length, Width, Height and Weight. [/INST] Output: # Load the dataset import pandas as pd csv_url = 'http://test.test/test.csv' df = pd.read_csv(csv_url) # Split the dataset into features and label X = df.iloc[:, 0:4].values y = df.iloc[:, 4].values # Import the ML model from sklearn.tree import DecisionTreeClassifier # Create and fit the model model = DecisionTreeClassifier() model.fit(X, y) # Predict the label def predict(data): predicted_label = model.predict([data]) return predicted_label</s>
<s>[INST] Instruction: Develop a Python program to generate random passwords that consist of 8 characters. Input: Not applicable [/INST] Output: import string import random def generate_password(): chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for _ in range(8)) password = generate_password() print(password)</s>
<s>[INST] Instruction: Generate a list using a while loop in Python and appends the current number to the list. Input: [/INST] Output: my_list = [] num = 0 while num < 10: my_list.append(num) num += 1 print(my_list)</s>
<s>[INST] Instruction: Write a Python program to query Twitter to get the most recent tweets from a user. Input: username: @elonmusk [/INST] Output: import tweepy # Authenticate to Twitter auth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET") auth.set_access_token("ACCESS_TOKEN", "ACCESS_TOKEN_SECRET") # Create API object api = tweepy.API(auth) # Get the most recent tweets from the given user tweets = api.user_timeline(screen_name="@elonmusk") for tweet in tweets: print(tweet.text)</s>
<s>[INST] Instruction: Create a Python neural network model that takes in a given trajectory of stock prices and predicts the stock price for the next day. Input: [10, 10.4, 10.5, 10.6, 10.7, 10.9, 11] [/INST] Output: import numpy as np import tensorflow as tf def create_model(): model = tf.keras.Sequential([ tf.keras.layers.Dense(64, activation='relu', input_shape=(7, )), tf.keras.layers.Dense(1) ]) model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy']) return model if __name__ == "__main__": model = create_model() input_data = np.array([[10, 10.4, 10.5, 10.6, 10.7, 10.9, 11]]) predictions = model.predict(input_data) print(f"Predicted stock price for the next day is: {predictions[0][0]}")</s>
<s>[INST] Instruction: Create a way to encrypt a message using a key in Python. Input: message = "Hello world!" key = "secret" [/INST] Output: import hashlib def encrypt(message, key): encrypted_msg = "" for char in message: encrypted_msg += chr(ord(char) + ord(key[0])) return encrypted_msg encrypted_msg = encrypt(message, key) print(encrypted_msg)</s>
<s>[INST] Instruction: Create a function in Python that takes two parameters and prints out the larger of them. Input: parameter_1 = 7 parameter_2 = 9 [/INST] Output: def printMax(parameter_1, parameter_2): if parameter_1 > parameter_2: print(parameter_1) else: print(parameter_2)</s>
<s>[INST] Instruction: Rewrite the following Python code by introducing list comprehensions. Input: even_numbers = [] for i in range(1,21): if i % 2 == 0: even_numbers.append(i) [/INST] Output: even_numbers = [i for i in range(1, 21) if i % 2 == 0]</s>
<s>[INST] Instruction: Develop an algorithm in Python to print Fibonacci series up to a given number. Input: [/INST] Output: def fibonacci(n): a = 0 b = 1 if n < 0: print("Incorrect input") elif n == 0: return a elif n == 1: return b else: for i in range(2,n): c = a + b a = b b = c return b n = int(input("Enter a number: ")) print(fibonacci(n))</s>
<s>[INST] Instruction: Make the following code snippet into a function in Python3 capable of solving Any Sudoku puzzle Input: board = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,9], [0,0,0,6,0,1,0,7,8], [0,0,7,0,4,0,2,6,0], [0,0,1,0,5,0,9,3,0], [9,0,4,0,6,0,0,0,5], [0,7,0,3,0,0,0,1,2], [1,2,0,0,0,7,4,0,0], [0,4,9,2,0,6,0,0,7] ] [/INST] Output: def solve_sudoku(board): # Utility function to find vacant cells # Returns a boolean def find_vacant_cell(board, l): for row in range(9): for col in range(9): if board[row][col] == 0: l[0] = row l[1] = col return True return False # Utility function to check if a number # is not currently placed in a particular # row, column and block def is_safe(board, row, col, num): # Check if 'num' is not already placed # in current row, current column # and current 3x3 box for i in range(9): # Check the rows if(board[row][i] == num): return False # Check the columns if(board[i][col] == num): return False # Check the 3x3 boxes if(board[(row//3)*3 + i//3][(col//3)*3 + i%3] == num): return False return True # Solve the sudoku def solve(board): # 'l' is a list variable that keeps # the record of row and col in # find_vacant_cell function l = [0, 0] # If there is no unassigned location, # we are done if (not find_vacant_cell(board, l)): return True # Assigning the list values row = l[0] col = l[1] # consider digits 1 to 9 for num in range(1, 10): # if it is a safe position if (is_safe(board, row, col, num)): # make tentative assignment board[row][col] = num # return if succcess if (solve(board)): return True # failure, unmake and try again board[row][col] = 0 # trigger backtracking return False #Driver Program if (solve(board)): for row in board: print(row) else: print("No solution")</s>
<s>[INST] Instruction: Write a function in Python to calculate the sum of the digits in a given number. Input: [/INST] Output: def sum_digits(num): total = 0 while num > 0: digit = num % 10 total += digit num = num // 10 return total</s>
<s>[INST] Instruction: Take the list of people below and create a Python dictionary with the names as keys and the ages as values. Input: John (20), Jane (40), Alex (18), Peter (45) [/INST] Output: people_dict = {'John': 20, 'Jane': 40, 'Alex': 18, 'Peter': 45}</s>
<s>[INST] Instruction: Develop a Python program to clearly understand the concept of recursion. Input: [/INST] Output: # This program is to understand recursion in Python. # Define a recursive function to calculate the factorial of a number def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) # Calculate factorial of number 5 result = factorial(5) print("Factorial of 5 is ", result) # Output: Factorial of 5 is 120</s>
<s>[INST] Instruction: Generate a random 6-digits number in Python. Input: [/INST] Output: import random number = random.randint(100000, 999999) print(number)</s>
<s>[INST] Instruction: Create a sorting algorithm in Python to sort strings by their length. Input: ["cat", "dog", "apple", "banana"] [/INST] Output: def sort_by_length(strings): for i in range(len(strings) - 1): for j in range(i + 1, len(strings)): if len(strings[i]) > len(strings[j]): strings[i], strings[j] = strings[j], strings[i] return strings unsorted_list = ["cat", "dog", "apple", "banana"] sorted_list = sort_by_length(unsorted_list) print(sorted_list)</s>
<s>[INST] Instruction: Write a Python function to get the maximum and minimum values in a given list. Input: Not applicable [/INST] Output: def get_max_min(lst): min_value = lst[0] max_value = lst[0] for i in range(1, len(lst)): if lst[i] > max_value: max_value = lst[i] if lst[i] < min_value: min_value = lst[i] return (min_value, max_value)</s>
<s>[INST] Instruction: Create a for loop in Python to iterate over a list of numbers and print only the even numbers. Input: my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [/INST] Output: for num in my_list: if num % 2 == 0: print(num)</s>
<s>[INST] Instruction: Can you suggest a pure python alternative to declaring a Float32 array with numbers from 0 to 10? Input: [/INST] Output: myArray = [float(i) for i in range(0,11)]</s>
<s>[INST] Instruction: Construct a neural network model in Python to classify the MNIST data set correctly. Input: [/INST] Output: import keras # Input layer input_layer = keras.layers.Input(shape=(784,)) # Hidden layer hidden_layer = keras.layers.Dense(128, activation='relu')(input_layer) # Output layer output_layer = keras.layers.Dense(10, activation='softmax')(hidden_layer) # Model model = keras.Model(inputs=input_layer, outputs=output_layer) # Compile model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])</s>
<s>[INST] Instruction: Create a machine learning classifier in Python for categorizing user input. Input: [/INST] Output: from sklearn.naive_bayes import MultinomialNB # Assuming an input string is passed to the function as a parameter def classify_string(input_string): # Feature extraction and transformation from string to numeric features = . . . # Create an instance of the classifier model = MultinomialNB() # Train the classifier on the data model.fit(data, target) # Make a prediction based on the input prediction = model.predict([features]) # Return the prediction return prediction</s>
<s>[INST] Instruction: Implement a algorithm in Python for sorting two large lists A and B. The algorithm should take the first element of list A and compare it with the first element of list B. If it is greater, then it should add the element to the result list and move the pointer of B to the next element. If the element of A is smaller, the pointer should move to the next element of A, and so on. Input: A = [3, 6, 8, 10, 11] B = [2, 5, 7, 12] [/INST] Output: def merge_sort(A, B): result = [] i, j = 0, 0 # Compare elements and add lower one to result while i < len(A) and j < len(B): if A[i] < B[j]: result.append(A[i]) i += 1 else: result.append(B[j]) j += 1 # Add remaining elements result += A[i:] result += B[j:] return result #Test the algorithm A = [3, 6, 8, 10, 11] B = [2, 5, 7, 12] print(merge_sort(A, B)) # Output: [2, 3, 5, 6, 7, 8, 10, 11, 12]</s>
<s>[INST] Instruction: Develop a program in Python for finding the longest common subsequence between two strings. Input: "ABCDF", "ABECD" [/INST] Output: def longest_common_subsequence(string1, string2): table = [[0]*(len(string2)+1) for _ in range(len(string1)+1)] for i, x in enumerate(string1): for j, y in enumerate(string2): if x == y: table[i+1][j+1] = table[i][j]+1 else: table[i+1][j+1] = max(table[i+1][j], table[i][j+1]) result = "" x, y = len(string1), len(string2) while x != 0 and y != 0: if table[x][y] == table[x-1][y]: x -= 1 elif table[x][y] == table[x][y-1]: y -= 1 else: result = string1[x-1] + result x -= 1 y -= 1 return result result = longest_common_subsequence("ABCDF", "ABECD") print(result)</s>
<s>[INST] Instruction: Convert a given Python program to a C# program. Input: def power(x, y): if y == 0: return 1 else: return x * power(x, y - 1) [/INST] Output: public int Power(int x, int y) { if (y == 0) { return 1; } else { return x * Power(x, y - 1); } }</s>
<s>[INST] Instruction: Rewrite the following code in a different programming language. Input: // JavaScript code let arr = [1, 2, 3, 4, 5]; arr.forEach(item => { console.log(item * 2); }); [/INST] Output: # Python code arr = [1, 2, 3, 4, 5] for item in arr: print(item * 2)</s>
<s>[INST] Instruction: Create a TicTacToe game in Python. Input: [/INST] Output: class TicTacToe: def __init__(self): self.board = [['_' for _ in range(3)] for _ in range(3)] self.turn = 'x' def display(self): for row in self.board: print(' '.join(row)) def check_win(self): board = self.board # check if the player with the current turn has a row of three for row in self.board: if row.count(self.turn) == 3: return True # check if the player with the current turn has a column of three for col in range(3): if board[0][col] == board[1][col] and board[1][col] == board[2][col] and board[2][col] == self.turn: return True # check for the two diagonals if board[0][0] == board[1][1] and board[1][1] == board[2][2] and board[2][2] == self.turn: return True if board[0][2] == board[1][1] and board[1][1] == board[2][0] and board[2][0] == self.turn: return True return False</s>
<s>[INST] Instruction: Create a Python program to store the strings "Hello" and "World" and print them in the same line. Input: [/INST] Output: string1 = "Hello" string2 = "World" print(string1 + " " + string2)</s>
<s>[INST] Instruction: Use the inputs provided, write Python code to check if two integers are equal. Input: First Integer: 10 Second Integer: 10 [/INST] Output: if int(10) == int(10): print("The two integers are equal") else: print("The two integers are not equal")</s>
<s>[INST] Instruction: Create a Python program for analyzing the sentiment of given text. The program should categorize the text into positive, negative, and neutral sentiments. Input: Not applicable [/INST] Output: import nltk from nltk.tokenize import sent_tokenize from nltk.classify import NaiveBayesClassifier def analyze_sentiment(text): sents = sent_tokenize(text) neg = 0 pos = 0 for sentence in sents: sentiment_analysis = NaiveBayesClassifier.classify(sentence) if sentiment_analysis == 'neg': neg += 1 if sentiment_analysis == 'pos': pos += 1 if neg > pos: sentiment = 'negative' elif pos > neg: sentiment = 'positive' else: sentiment = 'neutral' return sentiment # End analyze sentiment definition</s>
<s>[INST] Instruction: Create a Python program to calculate the average of five numbers entered by a user. Input: [/INST] Output: nums = [] for i in range(5): nums.append(int(input("Please enter number: "))) #Calculate average average = sum(nums) / len(nums) #Print average print("The average is ", average)</s>
<s>[INST] Instruction: Write a Python program to generate a Markov chain given a text input. Input: Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, `and what is the use of a book,' thought Alice `without pictures or conversation?' [/INST] Output: import random def generateMarkov(text): words = text.split(' ') markovChain = {} for i in range(len(words) - 2): current = words[i] next = words[i + 1] if current in markovChain: if next in markovChain[current]: markovChain[current][next] += 1 else: markovChain[current][next] = 1 else: markovChain[current] = {next: 1} generatedText = "" current = random.choice(list(markovChain)) generatedText += current for i in range(100): choices = markovChain[current] choices = [ key for key, value in choices.items() for i in range(value) ] try: current = random.choice(choices) generatedText += " " + current except: break return generatedText text = 'Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, `and what is the use of a book,' thought Alice `without pictures or conversation?' print(generateMarkov(text))</s>
<s>[INST] Instruction: Write a Python program to determine if a number provided by the user is prime or not. Input: 17 [/INST] Output: # Ask the user for a number num = int(input('Enter a number: ')) # Set initial values is_prime = True # Check for prime for i in range(2, num): if num % i == 0: is_prime = False break # Output result if is_prime: print(f'{num} is a prime number.') else: print(f'{num} is not a prime number.')</s>
<s>[INST] Instruction: Write a Python program to calculate the difference between the lowest and highest value for an array of integers. Input: [12, 24, 3, 8, -1] [/INST] Output: def diffHighestLowest(arr): lowest = min(arr) highest = max(arr) return highest - lowest arr = [12, 24, 3, 8, -1] difference = diffHighestLowest(arr) print(difference) # 25</s>
<s>[INST] Instruction: Rewrite the following code snippet to find prime numbers using Python. Input: Not applicable [/INST] Output: def is_prime(num): # Iterate from 2 to the square root of the number for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True # Iterate from 2 to n for n in range(2, n+1): # Check if the number is prime if is_prime(n): print(n)</s>
<s>[INST] Instruction: Write a Python program to create a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. Input: [/INST] Output: d = {} for i in range(1, 16): d[i] = i**2 print(d)</s>
<s>[INST] Instruction: Write a Python program to calculate the sum of all even numbers less than or equal to n. Input: [/INST] Output: def sum_of_even_numbers(n): result = 0 for i in range(2, n+1, 2): result += i return result</s>
<s>[INST] Instruction: Create a Python script to calculate the Fibonacci numbers up to a given number. Input: [/INST] Output: def Fibonacci(n): if n==0: return 0 if n==1: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2)</s>
<s>[INST] Instruction: Write a Python program to calculate the total cost of a shopping cart. The program should consider the item prices, quantity, shipping cost, and any applicable taxes. Input: [ {"name": "widget", "price": 10, "quantity": 5 }, {"name": "thingy", "price": 7, "quantity": 3 }, {"name": "doodad", "price": 5, "quantity": 2 }, ] Shipping cost: 7.50 Tax rate: 9.5% [/INST] Output: items = [ {"name": "widget", "price": 10, "quantity": 5 }, {"name": "thingy", "price": 7, "quantity": 3 }, {"name": "doodad", "price": 5, "quantity": 2 }, ] taxRate = 0.095 shippingCost = 7.50 totalCost = 0 for item in items: totalCost += item['price'] * item['quantity'] totalCost += totalCost * taxRate totalCost += shippingCost print('Total cost:', totalCost)</s>
<s>[INST] Instruction: In Python, create a function to find the maximum value within a nested dictionary. Input: sample_dict = { "key1": { "value1": 10, "value2": 20 }, "key2": { "value3": 40 }, } [/INST] Output: def findMaxValue(dict): max_val = None for key, value in dict.items(): if isinstance(value, dict): max_val = max(findMaxValue(value), max_val) else: max_val = max(value, max_val) return max_val print(findMaxValue(sample_dict))</s>
<s>[INST] Instruction: Write a function in Python that returns an object of the following time and date: Sunday March 7 5:30 PM. Input: [/INST] Output: from datetime import datetime def get_date_time(): dt = datetime(year=2021, month=3, day=7, hour=17, minute=30) return dt date_time = get_date_time() print(date_time) # will output 2021-03-07 17:30:00</s>
<s>[INST] Instruction: Generate a Python program to perform matrix multiplication on two given matrices. Input: [/INST] Output: def matrix_multiplication(A, B): rows_A = len(A) cols_A = len(A[0]) rows_B = len(B) cols_B = len(B[0]) result = [[0 for i in range(cols_B)] for j in range(rows_A)] for i in range(rows_A): for j in range(cols_B): for k in range(cols_A): result[i][j] += A[i][k] * B[k][j] return result</s>
<s>[INST] Instruction: Write a Python script to read an array from the user and then determine the mean and median of the array. Input: arr = [10, 15, 20, 25, 30, 35] [/INST] Output: def mean_median(arr): arr_sum = 0 for i in range(len(arr)): arr_sum += arr[i] mean = arr_sum/len(arr) arr = sorted(arr) if len(arr) % 2 != 0: median = arr[floor(len(arr)/2)] else: median = (arr[len(arr)//2] + arr[len(arr)//2 - 1]) / 2 return mean, median mean, median = mean_median(arr) print("Mean =", mean) print("Median =", median)</s>
<s>[INST] Instruction: Create an algorithm in Python to check whether an array has even or odd number of elements. Input: [1, 2, 3, 4] [/INST] Output: def is_array_even(arr): if len(arr)%2 == 0: return True else: return False</s>
<s>[INST] Instruction: Implement a Python function to calculate the Gini coefficient of a given dataset. Input: [2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,21] [/INST] Output: def gini(x): """Calculate Gini Coefficient of a given dataset.""" # calculate the frequency of each item in x x_value_counts = x.value_counts().sort_index() # calculate the cumulative sum of x_value_counts x_cum_sum = x_value_counts.cumsum() # calculate the Lorenz values n = len(x) lorenz = x_cum_sum / n lorenz = np.insert(lorenz, 0, 0) # add 0 to the beginning of array # calculate the Gini Coefficient width = lorenz[:-1] - lorenz[1:] gini_coef = (1 / n) * sum(width * (lorenz[1:] + lorenz[:-1])) return gini_coef if __name__ == '__main__': x = np.array([2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,21]) gini_coef = gini(x) print(gini_coef) # should print 0.605</s>
<s>[INST] Instruction: Generate a neural network model with TensorFlow and Python for classifying hand-written digits from the MNIST dataset. Input: Not applicable [/INST] Output: import tensorflow as tf # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data", one_hot=True) # Parameters learning_rate = 0.001 training_epochs = 15 batch_size = 100 display_step = 1 # Network Parameters n_hidden_1 = 256 # 1st layer number of neurons n_hidden_2 = 256 # 2nd layer number of neurons n_input = 784 # MNIST data input (img shape: 28*28) n_classes = 10 # MNIST total classes (0-9 digits) # tf Graph input X = tf.placeholder("float", [None, n_input]) Y = tf.placeholder("float", [None, n_classes]) # Store layers weight & bias weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_classes])) } # Create model def multilayer_perceptron(x): # Hidden fully connected layer with 256 neurons layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) # Hidden fully connected layer with 256 neurons layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) # Output fully connected layer with a neuron for each class out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] return out_layer # Construct model logits = multilayer_perceptron(X) # Define loss and optimizer loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=Y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(loss_op) # Initializing the variables init = tf.global_variables_initializer() # Train model model = tf.Session() model.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(mnist.train.num_examples/batch_size) # Loop over all batches for i in range(total_batch): batch_x, batch_y = mnist.train.next_batch(batch_size) # Run optimization op (backprop) and cost op (to get loss value) _, c = model.run([train_op, loss_op], feed_dict={X: batch_x, Y: batch_y}) # Compute average loss avg_cost += c / total_batch # Display logs per epoch step if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", \ "{:.9f}".format(avg_cost)) print("Optimization Finished!") # Test model pred = tf.nn.softmax(logits) # Apply softmax to logits correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print("Accuracy:", accuracy.eval({X: mnist.test.images, Y: mnist.test.labels}, model))</s>
<s>[INST] Instruction: Write a function to generate a prime number sequence using Python. Input: [/INST] Output: def generate_prime_numbers(n): primes = [True for i in range(n+ 1)] p = 2 while (p * p <= n): if (primes[p] == True): for i in range(p * p, n + 1, p): primes[i] = False p += 1 primes[0] = False primes[1] = False for p in range(n + 1): if primes[p]: print(p)</s>
<s>[INST] Instruction: Write a Python program that removes duplicates from a list. Input: Input List: [1, 2, 3, 4, 3, 2, 1] [/INST] Output: def remove_duplicates(my_list): return list(dict.fromkeys(my_list)) my_list = [1, 2, 3, 4, 3, 2, 1] print(remove_duplicates(my_list)) # output [1, 2, 3, 4]</s>
<s>[INST] Instruction: Generate a Python script to sort the given list of words. Input: ['bubble', 'selection', 'quicksort', 'insertion'] [/INST] Output: # function to sort the given list of words def sort_words(words): # sort the list of words in alphabetical order words.sort() # print the sorted list of words print(words) # driver code words = ['bubble', 'selection', 'quicksort', 'insertion'] sort_words(words) # output ['bubble', 'insertion', 'quicksort', 'selection']</s>
<s>[INST] Instruction: Generate a function for calculating the average of a list of numbers in Python. Input: Not applicable [/INST] Output: def avg_list(lst): sum = 0 count = 0 for i in lst: sum += i count += 1 avg = sum / count return avg</s>
<s>[INST] Instruction: Generate a Python program that compares two binary trees to check if they are similar. Input: [/INST] Output: class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def are_similar(root1, root2): if root1 is None and root2 is None: return True if (root1 and root2) is None or (root1 or root2) is None: return False if root1.val != root2.val: return False else: return are_similar(root1.left, root2.left) and are_similar(root1.right, root2.right)</s>
<s>[INST] Instruction: Create a program for solving a quadratic equation in Python. Input: Equation: x2 + 3x - 4 = 0 [/INST] Output: import math def solveQuadratic(a, b, c): discriminant = (b**2) - (4*a*c); # If discriminant is negative there are no real roots. if (discriminant < 0): return { "status": false, "roots": [] } # If discriminant is zero, there is only one real roots. elif (discriminant == 0): x = -b/(2*a) return { "status": true, "roots": [x] } # Otherwise there are 2 real roots else: x1 = (-b + math.sqrt(discriminant)) / (2*a); x2 = (-b - math.sqrt(discriminant)) / (2*a); return { "status": true, "roots": [x1, x2] } a = 1 b = 3 c = -4 print(solveQuadratic(a, b, c)) #{'status': True, 'roots': [-4.0, 1.0]}</s>
<s>[INST] Instruction: Construct a Python code for adding two matrices. Input: [/INST] Output: def add_matrix(matrix1, matrix2): if len(matrix1) != len(matrix2): return 'Matrices not compatible' if len(matrix1[0]) != len(matrix2[0]): return 'Matrices not compatible' rows = len(matrix1) cols = len(matrix1[0]) result = [[sum(row) for row in zip(*size)] for size in zip(matrix1, matrix2)] return result</s>
<s>[INST] Instruction: Generate a Python program which takes a string as input and prints all of its substrings in order from longest to shortest length. Input: [/INST] Output: def substring_in_order(string): result = [] n = len(string) for l in range(n, 0, -1): for i in range(n-l + 1): result.append(string[i:i+l]) return result string = input("Enter the string: ") print ("All substrings in order from longest to shortest:") print (substring_in_order(string))</s>
<s>[INST] Instruction: Generate a Python function which takes an array and a value and returns the index at which this value is present in the array. Input: arr = [2, 5, 9, 15], x = 5 [/INST] Output: def find_index(arr, x): for i in range(len(arr)): if arr[i] == x: return i return -1 print(find_index(arr, x))</s>
<s>[INST] Instruction: Develop a Python program to find the common elements in two lists. Input: List 1: [3, 9, 15, 21, 27] List 2: [21, 7, 13, 29, 31] [/INST] Output: common_elements = [] # using loop for i in [3, 9, 15, 21, 27]: for j in [21, 7, 13, 29, 31]: if i == j: common_elements.append(i) # printing common elements print(common_elements) # Output: [21]</s>
<s>[INST] Instruction: Create a Python program that takes in two strings and returns an integer indicating the number of common substrings between the two strings. Input: s1 = "abcd", s2 = "bae" [/INST] Output: def num_common_substrings(s1, s2): count = 0 for i in range(len(s1)): for j in range(len(s2)): if s1[i] == s2[j]: count += 1 return count result = num_common_substrings("abcd", "bae") print(result)</s>
<s>[INST] Instruction: Generate a Python program to convert a string to its lowercase version. Input: [/INST] Output: def str_to_lower(string): new_string = "" for char in string: new_string += char.lower() return new_string</s>
<s>[INST] Instruction: Can you generate a function in Python that shuffles a given list? Input: [/INST] Output: import random def shuffle_list(list): # Initialize the random number generator random.seed() # Shuffle the list random.shuffle(list) # Return the list return list</s>
<s>[INST] Instruction: Write a Python function to validate an a list of emails. The function should return a boolean indicating whether a given email address is valid. Input: mail_list = ["example.user@gmail.com", "bad@example"] [/INST] Output: def validate_mail_list(mail_list): for mail in mail_list: if not re.match("[^@]+@[^@]+\.[^@]+", mail): return False return True</s>
<s>[INST] Instruction: Create a Python script that will perform several simple math operations. The script should accept two integers as inputs and output the results of the following operations: addition, subtraction, multiplication, division, and modulo. Input: int1 = 10 int2 = 5 [/INST] Output: int1 = 10 int2 = 5 addition = int1 + int2 print('Addition:', addition) subtraction = int1 - int2 print('Subtraction:', subtraction) multiplication = int1 * int2 print('Multiplication:', multiplication) division = int1 / int2 print('Division:', division) modulo = int1 % int2 print('Modulo:', modulo)</s>
<s>[INST] Instruction: Create a Python program to perform sentiment analysis on product reviews. The program should use natural language processing techniques like tokenization and n-grams to generate features for sentiment analysis and use a classification model to assign sentiments to the reviews. Input: Not applicable [/INST] Output: import numpy as np import pandas as pd import nltk from nltk.tokenize import word_tokenize import matplotlib.pyplot as plt from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report # Read in the data data = pd.read_csv('reviews.csv') # Tokenise the texts data['tokenised'] = data['review'].apply(word_tokenize) # Remove stopwords stop_words = set(stopwords.words('english')) data['filtered'] = data['tokenised'].apply(lambda x: [val for val in x if val not in stop_words]) # Normalize words wordnet_lemmatizer = WordNetLemmatizer() data['normalised'] = data['filtered'].apply(lambda x: [wordnet_lemmatizer.lemmatize(val) for val in x]) # Generate features using CountVectorizer cv = CountVectorizer() data['features'] = cv.fit_transform(data['normalised'].astype('str')).toarray() # Split into training and test sets X = data['features'] y = data['sentiment'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Train model model = MultinomialNB(alpha=0.1) model.fit(X_train, y_train) # Predict using the test set predictions = model.predict(X_test) # Generate a classification report report = classification_report(y_test, predictions) print(report)</s>
<s>[INST] Instruction: Write a python program to clean up a list of emails and put them into a new list. Input: The original list of emails: ['bob@example.com', 'alice+bob@cafe.com', 'bob@gmail.com.uk', 'bob+alice@example'] [/INST] Output: original_list = ['bob@example.com', 'alice+bob@cafe.com', 'bob@gmail.com.uk', 'bob+alice@example'] clean_list = [] for email in original_list: email_without_plus = email.split('+')[0] email_without_dot_uk = email_without_plus.split('.uk')[0] clean_list.append(email_without_dot_uk) print(clean_list) # prints ['bob@example.com', 'alice@cafe.com', 'bob@gmail.com', 'bob@example']</s>
<s>[INST] Instruction: Generate sample data for a web application using Python's faker library. The output should contain three columns of data: name, email, and age. Input: Not applicable [/INST] Output: from faker import Faker fake = Faker() for _ in range(10): print(fake.name(), fake.email(), fake.random_int(min=18, max=60))</s>
<s>[INST] Instruction: Create a Python algorithm to classify positive and negative sentiment in tweets. Input: [/INST] Output: def sentiment_analysis(tweets): # Initialize a list to store the result results = [] # Iterate through each tweet for tweet in tweets: # Clean the tweet tweet = preprocessing(tweet) # Vectorize the tweet and obtain the prediction tweet_vector = vectorize(tweet) prediction = predict_sentiment(tweet_vector) # Append the prediction to the result list if prediction == 1: results.append("Positive") elif preduction == 0: results.append("Negative") return results</s>
<s>[INST] Instruction: Parse the given URL and print out the protocol, domain name, and path using Python. Input: https://www.example.com/path/to/file [/INST] Output: import urllib.parse url = 'https://www.example.com/path/to/file' parsed_url = urllib.parse.urlparse(url) # Get the protocol protocol = parsed_url.scheme # Get the domain name domain_name = parsed_url.netloc # Get the path path = parsed_url.path # Print the results print('Protocol:', protocol) print('Domain name:', domain_name) print('Path:', path) # Output: # Protocol: https # Domain name: www.example.com # Path: /path/to/file</s>
<s>[INST] Instruction: Write a recursive Python function to generate Fibonacci numbers. Input: [/INST] Output: def fibonacci(n): if n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(10))</s>
<s>[INST] Instruction: Create a Kubernetes pod setup that publishes a tweet every 5 minutes. Input: Not applicable [/INST] Output: apiVersion: v1 kind: Pod metadata: name: tweet-publisher spec: containers: - name: tweet-publisher image: <INSERT_PUBLIC_PULLABLE_IMAGE_PATH_HERE> command: - sh - -c - 'crontab -lcrontab && while true; do python publish-tweet.py && crontab -l | { cat; echo "*/5 * * * * python publish-tweet.py"; } | crontab -; sleep 31622400; done' volumeMounts: - mountPath: /crontab/crontab subPath: crontab name: cronmount volumes: - name: cronmount configMap: name: tweet-cron --- apiVersion: v1 kind: ConfigMap metadata: name: tweet-cron data: crontab: "* * * * * python publish-tweet.py"</s>
<s>[INST] Instruction: Write a code to generate a two-dimensional array with zeros shapes in Python Input: Row = 3, Column = 3 [/INST] Output: """ Write a code to generate a two-dimensional array with zeros shapes in Python """ def generate_zeros_array(row,col): return [[0] * col for _ in range(row)] # Example row = 3 col = 3 array = generate_zeros_array(row, col) print(array) # Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]</s>
<s>[INST] Instruction: Write a Python code to create a dictionary which contains a data structrue in the form of [x:x^2] where x is the key and x^2 is the value. Input: numbers = [1, 2, 3, 4, 5] [/INST] Output: numbers = [1, 2, 3, 4, 5] dict_numbers = {num: num**2 for num in numbers} print(dict_numbers)</s>
<s>[INST] Instruction: Create a Python script to print the numbers from 1 to 50, but for multiples of 3 print "Fizz" instead of the number, for multiples of 5 print "Buzz" instead of the number and for multiples of both 3 and 5 print "FizzBuzz". Input: Not applicable [/INST] Output: for i in range(1, 51): if i % 3 == 0 and i % 5 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i)</s>
<s>[INST] Instruction: Create a Python program to calculate the square root of a user-defined positive number. Input: n = 100 [/INST] Output: import math n = 100 #Calculate the square root of a number square_root = math.sqrt(n) print(f'Square root of {n} is {square_root}')</s>
<s>[INST] Instruction: Create a Python class called Rectangle to represent a two-dimensional rectangle with a length and width. Input: [/INST] Output: class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width</s>
<s>[INST] Instruction: Create a data visualization dashboard in Python using Matplotlib. Input: [/INST] Output: import matplotlib import matplotlib.pyplot as plt # Generate the data for the dashboard x = [1,2,3,4,5] y = [10,25,30,50,80] # Create the figure and set the size fig = plt.figure(figsize=(10,6)) # Configure the plot plt.plot(x, y, color='green', marker='o', linestyle='dashed', linewidth=2, markersize=12) plt.title("My Data Visualization Dashboard") plt.xlabel('X-axis') plt.ylabel('Y-axis') # Show the plot plt.show()</s>
<s>[INST] Instruction: Edit the following python code to prompt the user to enter the value of radius to calculate the area of a circle. Input: [/INST] Output: # Calculate area of a circle Pi = 3.14 # Get radius from user radius = float(input("Please enter the radius of the circle: ")) # Calculate the circle area area = Pi*radius**2 # Print the area print("The area of the circle is:", area)</s>
<s>[INST] Instruction: Create a Python algorithm to identify the longest word in a sentence. Input: “The rain in Spain stays mainly in the plain.” [/INST] Output: def find_longest_word(sentence): words = sentence.split() # initialise longest_word variable with 0 longest_word = 0 for word in words: if len(word) > longest_word: longest_word = len(word) longest_word_str = word return longest_word_str</s>
<s>[INST] Instruction: Write a Python script that can convert degrees Fahrenheit to degrees Celsius. Input: [/INST] Output: def FahrenheitToCelsius(temp_fahrenheit): temp_celsius = (temp_fahrenheit - 32) * 5/9 return temp_celsius</s>
<s>[INST] Instruction: Generate a Python function that checks if a given number is an Armstrong number. Input: [/INST] Output: def is_armstrong_number(num): n = len(str(num)) # initialize sum temp = num sum_of_digits = 0 # find sum of nth power of individual digits while temp > 0: digit = temp % 10 sum_of_digits += digit ** n temp //= 10 # if num is equal to sum_of_digits then the number is an Armstrong number if num == sum_of_digits: return True else: return False</s>
<s>[INST] Instruction: Write a code in Python to print the following pattern: Input: [/INST] Output: for i in range(5): for j in range(i+1): print("*", end="") print("") for i in range(5, 0, -1): for j in range(i): print("*", end="") print("")</s>
<s>[INST] Instruction: Program a web scraper in Python to extract the latest stock prices from specific websites. Input: ["AAPL stocks", "MSFT stocks", "FB stocks", "GOOG stocks"] [/INST] Output: import requests from bs4 import BeautifulSoup # input stocks = ["AAPL stocks", "MSFT stocks", "FB stocks", "GOOG stocks"] # process def get_stock_price(stock): url = f"https://finance.yahoo.com/quote/{stock}" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') price = soup.find('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text return price # output for stock in stocks: price = get_stock_price(stock) print(f'The price of {stock} is {price}.')</s>
<s>[INST] Instruction: The code provides Python wrappers around TensorFlow ops for decoding LibSVM input to tensors. To use it, call the `decode_libsvm` function with the following arguments: `input` (a `Tensor` of type `string`), `num_features` (an `int` that is `>= 1`), `dtype` (an optional `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to `tf.float32`), `label_dtype` (an optional `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to `tf.int64`), and `name` (a name for the operation, optional). The function returns a tuple of `Tensor` objects `(label, feature_indices, feature_values, feature_shape)`, where `label` is a `Tensor` of type `label_dtype`, `feature_indices` is a `Tensor` of type `int64`, `feature_values` is a `Tensor` of type `dtype`, and `feature_shape` is a `Tensor` of type `int64`. Input: [/INST] Output: """Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. Original C++ source file: libsvm_ops.cc """ import collections as _collections import six as _six from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow from tensorflow.python.eager import context as _context from tensorflow.python.eager import core as _core from tensorflow.python.eager import execute as _execute from tensorflow.python.framework import dtypes as _dtypes from tensorflow.python.framework import errors as _errors from tensorflow.python.framework import tensor_shape as _tensor_shape from tensorflow.core.framework import op_def_pb2 as _op_def_pb2 # Needed to trigger the call to _set_call_cpp_shape_fn. from tensorflow.python.framework import common_shapes as _common_shapes from tensorflow.python.framework import op_def_registry as _op_def_registry from tensorflow.python.framework import ops as _ops from tensorflow.python.framework import op_def_library as _op_def_library from tensorflow.python.util.tf_export import tf_export _decode_libsvm_outputs = ["label", "feature_indices", "feature_values", "feature_shape"] _DecodeLibsvmOutput = _collections.namedtuple( "DecodeLibsvm", _decode_libsvm_outputs) @tf_export('decode_libsvm') def decode_libsvm(input, num_features, dtype=_dtypes.float32, label_dtype=_dtypes.int64, name=None): r"""Convert LibSVM input to tensors. The output consists of a label and a feature tensor. The shape of the label tensor is the same as input and the shape of the feature tensor is `[input_shape, num_features]`. Args: input: A `Tensor` of type `string`. Each string is a record in the LibSVM. num_features: An `int` that is `>= 1`. The number of features. dtype: An optional `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to `tf.float32`. label_dtype: An optional `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to `tf.int64`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (label, feature_indices, feature_values, feature_shape). label: A `Tensor` of type `label_dtype`. A tensor of the same shape as input. feature_indices: A `Tensor` of type `int64`. A 2-D int64 tensor of dense_shape [N, ndims]. feature_values: A `Tensor` of type `dtype`. A 1-D tensor of any type and dense_shape [N]. feature_shape: A `Tensor` of type `int64`. A 1-D int64 tensor of dense_shape [ndims]. """ _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: num_features = _execute.make_int(num_features, "num_features") if dtype is None: dtype = _dtypes.float32 dtype = _execute.make_type(dtype, "dtype") if label_dtype is None: label_dtype = _dtypes.int64 label_dtype = _execute.make_type(label_dtype, "label_dtype") _, _, _op = _op_def_lib._apply_op_helper( "DecodeLibsvm", input=input, num_features=num_features, dtype=dtype, label_dtype=label_dtype, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("dtype", _op.get_attr("dtype"), "label_dtype", _op.get_attr("label_dtype"), "num_features", _op.get_attr("num_features")) _execute.record_gradient( "DecodeLibsvm", _inputs_flat, _attrs, _result, name) _result = _DecodeLibsvmOutput._make(_result) return _result else: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "DecodeLibsvm", name, _ctx._post_execution_callbacks, input, "dtype", dtype, "label_dtype", label_dtype, "num_features", num_features) _result = _DecodeLibsvmOutput._make(_result) return _result except _core._FallbackException: return decode_libsvm_eager_fallback( input, dtype=dtype, label_dtype=label_dtype, num_features=num_features, name=name, ctx=_ctx) except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) def decode_libsvm_eager_fallback(input, num_features, dtype=_dtypes.float32, label_dtype=_dtypes.int64, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function decode_libsvm """ _ctx = ctx if ctx else _context.context() num_features = _execute.make_int(num_features, "num_features") if dtype is None: dtype = _dtypes.float32 dtype = _execute.make_type(dtype, "dtype") if label_dtype is None: label_dtype = _dtypes.int64 label_dtype = _execute.make_type(label_dtype, "label_dtype") input = _ops.convert_to_tensor(input, _dtypes.string) _inputs_flat = [input] _attrs = ("dtype", dtype, "label_dtype", label_dtype, "num_features", num_features) _result = _execute.execute(b"DecodeLibsvm", 4, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "DecodeLibsvm", _inputs_flat, _attrs, _result, name) _result = _DecodeLibsvmOutput._make(_result) return _result _ops.RegisterShape("DecodeLibsvm")(None) def _InitOpDefLibrary(op_list_proto_bytes): op_list = _op_def_pb2.OpList() op_list.ParseFromString(op_list_proto_bytes) _op_def_registry.register_op_list(op_list) op_def_lib = _op_def_library.OpDefLibrary() op_def_lib.add_op_list(op_list) return op_def_lib # op { # name: "DecodeLibsvm" # input_arg { # name: "input" # type: DT_STRING # } # output_arg { # name: "label" # type_attr: "label_dtype" # } # output_arg { # name: "feature_indices" # type: DT_INT64 # } # output_arg { # name: "feature_values" # type_attr: "dtype" # } # output_arg { # name: "feature_shape" # type: DT_INT64 # } # attr { # name: "dtype" # type: "type" # default_value { # type: DT_FLOAT # } # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "label_dtype" # type: "type" # default_value { # type: DT_INT64 # } # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "num_features" # type: "int" # has_minimum: true # minimum: 1 # } # } _op_def_lib = _InitOpDefLibrary(b"\n\311\001\n\014DecodeLibsvm\022\t\n\005input\030\007\032\024\n\005label\"\013label_dtype\032\023\n\017feature_indices\030\t\032\027\n\016feature_values\"\005dtype\032\021\n\rfeature_shape\030\t\"\033\n\005dtype\022\004type\032\0020\001:\010\n\0062\004\001\002\003\t\"!\n\013label_dtype\022\004type\032\0020\t:\010\n\0062\004\001\002\003\t\"\027\n\014num_features\022\003int(\0010\001") </s>
<s>[INST] Instruction: Write a Python program to compute the sum of the values of a given dictionary Input: dictionary = {'A':5, 'B':6, 'C':10} [/INST] Output: def dict_sum(dict): sum = 0 for key, value in dict.items(): sum += value return sum</s>
<s>[INST] Instruction: Create a REST API in Python that can be used to delete an item from a list. Input: Not applicable [/INST] Output: from flask import Flask, request import json app = Flask(__name__) items = ["Apple", "Banana", "Orange"] @app.route('/items', methods=["GET"]) def get_items(): return json.dumps(items) @app.route('/items/<item>', methods=["DELETE"]) def delete_item(item): if item in items: items.remove(item) message = "Item successfully deleted." else: message = "Item not found." return json.dumps({"message": message})</s>