text stringlengths 37 1.41M |
|---|
from utils.binary_tree_helper import arr_to_binary_tree_helper
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def smallestFromLeaf(self, root: 'TreeNode') -> 'str':
def path_helper(cur, path, temp, level):
if cur:
while len(temp) > level:
temp.pop()
temp += [cur.val]
path_helper(cur.left, path, temp, level + 1)
path_helper(cur.right, path, temp, level + 1)
if not cur.left and not cur.right:
path.append(temp[::-1])
res = []
path_helper(root, res, [], 0)
res.sort()
ans = ""
for val in res[0]:
ans += chr(97 + val)
return ans
if __name__ == '__main__':
# begin
s = Solution()
arr = [25,1,3,1,3,0,2]
print(s.smallestFromLeaf(arr_to_binary_tree_helper(arr)))
|
class Calculator:
def add(self, num1, num2):
return num1 + num2
def subtract(self, num1, num2):
return num1 - num2
def multipy(self, num1, num2):
return num1 * num2
def divide(self, num1, num2):
if num2 == 0:
return 0
return num1 / num2
|
#Developer: Tyler Smith
#Date: 11.06.16
#Purpose: Program is intended to provide an interactive
# GUI experience for a user to have three options
# of which program they want to use on the main
# popup. The three programs that the user can use
# are the BMI calculator, Measuring unit converter,
# and the currency calculator.
from tkinter import * # Import tkinter library
from bmiApplication import * # Import GUI from bmiProgram
class bmiApp(App): # Refer to class so bmi GUI can run
pass # when user presses button
from unitApplication import * # Import GUI from unitApplication
class unitApp(unitApp): # Refer to class so unitApp GUI can run
pass # when user presses button
from currencyApplication import * # Import GUI from currencyApplication
class currencyApp(currencyApp): # Refer to class so currencyApp GUI can run
pass # when user presses button
class mainApp(Tk):
def __init__(self): # Constructor for GUI class
Tk.__init__(self) #
self.addTitle() # Put BMI Calculator on GUI
self.addButtons() # Put calculate button on GUI
# Put title on GUI
def addTitle(self):
Label(self, text = "Calculator / Converter Options", font =
("Helvetica", "16", "bold italic")).grid(columnspan = 2)
Label(self, text = "", font =
("Helvetica", "16", "bold italic")).grid(columnspan = 2)
# Put calculate button on GUI to calculate BMI and Status
def addButtons(self):
self.btnCalc = Button(self, text = 'BMI Calculator', font =
("Helvetica", "14"))
self.btnCalc.grid(row = 2, columnspan = 2) # BMI Calculator button
self.btnCalc["command"] = self.bmiTrigger
Label(self, text = "", font =
("Helvetica", "16", "bold italic")).grid(columnspan = 2) # Big Space between each button
self.btnCalc = Button(self, text = 'Measuring Unit Converter', font =
("Helvetica", "14"))
self.btnCalc.grid(row = 4, columnspan = 2) # Measuring Unit Converter button
self.btnCalc["command"] = self.unitTrigger
Label(self, text = "", font =
("Helvetica", "16", "bold italic")).grid(columnspan = 2) # Big Space between each button
self.btnCalc = Button(self, text = 'Currency Calculator', font =
("Helvetica", "14")) # Currency Calculator button
self.btnCalc.grid(row = 6, columnspan = 2)
self.btnCalc["command"] = self.currencyTrigger
Label(self, text = "", font =
("Helvetica", "16", "bold italic")).grid(columnspan = 2) # Big space after last button
def bmiTrigger(self): # When BMI button is clicked, BMI application
bmiApplicationRun = bmiApp() # will be ran and GUI will be displayed
def unitTrigger(self): # When Unit button is clicked, Unit application
unitApplicationRun = unitApp() # will be ran and GUI will be displayed
def currencyTrigger(self): # When Currency button is clicked, Currency application
currencyApplicationRun = currencyApp() # will be ran and GUI will be displayed
def main():
mainGui = mainApp() # Instantiate myGUI object to begin building GUI
mainGui.mainloop()
#Run main function
if(__name__ == "__main__"):
main()
|
#1
print('1')
print('''Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle twinkle little star,
How I wonder what you are''')
print('----------------------------------')
#2
print('2')
import sys
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)
print('----------------------------------')
#3
print('3')
from datetime import datetime
print(datetime.now())
print('----------------------------------')
#4
print('4')
r=int(input('Enter radius of circle'))
area=(3.14)*(r**2)
print('area of circle',area)
print('----------------------------------')
#5
print('5')
First_Name=input('Enter First Name')
Last_Name=input('Enter Last Name')
print(Last_Name[len(Last_Name)::-1],'',First_Name[len(First_Name)::-1])
print('----------------------------------')
#6
print('6')
num1=int(input('Enter 1st number'))
num2=int(input('Enter 2nd number'))
sum=num1+num2
print('sum',sum)
|
# Author: Pavel Baranek
def welcome_phrase():
welcome = "Welcome in the game of TicTacToe!!!"
welcome1 = welcome.center(75)
print(len(welcome1) * "*")
print(welcome1)
print(len(welcome1) * "*")
def show_rules():
rules = """
THE RULES OF THE GAME ARE:
Two players are putting the symbols of "X" and "O" on the 3x3 game plan.
To win, one of the players have to connect the line of 3 symbols in a row.
First player who connects the line wins.
(Player "X" starts the game).
THE GAME MAP GOES LIKE THIS:
- 7|8|9 -
- 4|5|6 -
- 1|2|3 -
"""
print(rules)
starter = "--> LET THE GAME BEGIN <--"
starter1 = starter.center(75)
print(len(starter1) * "*")
print(starter1)
print(len(starter1) * "*")
def game_plan(value):
print("\n")
print("\t | |")
print(f"\t {value[6]} | {value[7]} | {value[8]}")
print('\t_____|_____|_____')
print("\t | |")
print(f"\t {value[3]} | {value[4]} | {value[5]}")
print('\t_____|_____|_____')
print("\t | |")
print(f"\t {value[0]} | {value[1]} | {value[2]}")
print("\t | |")
print("\n")
win = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (6, 4, 2), (8, 4, 0))
def empty_check(value, chosen):
if value[chosen] == " ":
return True
def update_(value, player, chosen):
value[chosen] = player
def win_check(value, player):
for a, b, c in win:
if player == value[a] and player == value[b] and player == value[c]:
return True
else:
return False
def tie_check(value):
if " " not in value:
return True
def player_input(player):
while True:
print(f"Player {player} |", end = " ")
choice = input("Chosen place on game plan: ")
if choice in ("1", "2", "3", "4", "5", "6", "7", "8", "9"):
choice1 = int(choice)
return choice1 - 1
elif choice is not int:
print("Error! Choose number between 1-9!!!")
continue
else:
print("Error! Choose number between 1-9!!!")
continue
def play_game():
game = True
players = ["X", "O"]
value = [" " for empty in range(9)]
welcome_phrase()
show_rules()
game_plan(value)
while game == True:
for player in players:
while True:
chosen_place = player_input(player)
if not empty_check(value, chosen_place):
print("Choose an empty spot please!!!")
continue
break
update_(value, player, chosen_place)
game_plan(value)
if win_check(value, player) == True:
gratulation = f"Congratulations!!! Player {player} wins the game!"
gratulation1 = gratulation.center(65)
print(len(gratulation1) * "*")
print(gratulation1)
print(len(gratulation1) * "*")
game = False
break
if tie_check(value) == True:
print("It's a TIE, nobody wins! :( ")
game = False
break
if __name__ == "__main__":
play_game()
|
import numpy as np
import random
import matplotlib.pyplot as plt
"""
Perceptron Class.
Does the perceptron training with the l2 regularisation coefficient.
"""
class Perceptron():
"""
init function.
no_of_inputs = 4. - Number of varibles in data set.
threshold = 20. - Number of iterations.
weights - start as all zeros [0,0,0,0]
bias - starts as 0
"""
def __init__(self, no_of_inputs=4, threshold=20):
self.threshold = threshold #Number of iterations.
self.weights = np.zeros(no_of_inputs)
self.bias = 0
"""
train fuction.
Follow perceptron algorithm with a l2 regularisation coefficient.
"""
def train(self, training_inputs, labels, reg_co):
errors = [] #List of amount of errors per epoch.
for _ in range(self.threshold):
count = 0
training_inputs, labels = Perceptron.shuffle(self, training_inputs, labels) #Shuffle order of input data.
for inputs, label in zip(training_inputs, labels):
a = np.dot(inputs, self.weights) + self.bias #Activation function.
if((label*a) <= 0): #Checks the sign of the actication function. If it not the same as label, weight is adjusted.
count += 1
self.weights = (1 - 2 * reg_co) * self.weights + label * inputs #l2 regularisation coefficient update formula.
self.bias += label
errors.append(count/len(training_inputs)) #Total number of errors for current epoch.
return self.bias, self.weights, errors
"""
shuffle function.
Takes in data and corrisponding labels.
shuffles the order, keeping the data labels pair together.
"""
def shuffle(self, data, labels):
z = list(zip(data, labels))
random.shuffle(z) #Shuffle data, label pair.
data, labels = zip(*z)
return data, labels
"""
Enviroment Class.
Reads and formats input data.
"""
class Enviroment():
def __init__(self, file_name):
self.file_name = file_name
"""
read function.
Opens file, converts each line to a string and closes file.
Calls the sort fuction.
Returns sorted data.
"""
def read(self, file_name):
f = open(file_name, "r")
read_data = f.read().splitlines()
f.close()
return Enviroment.sort(self, read_data) #Calls sort function.
"""
sort function.
converts the read data into a list.
"""
def sort(self, data):
read_data = []
for i in data:
read_data.append(i)
return read_data
"""
formatter function.
Formats data into the appropriate format. [float,float,float,float]
Seperates the label from data and records this at the same index.
"""
def formatter(self, data):
formatted_data = []
labels = []
for i in range(len(data)):
train = []
train.append(float(data[i][:3]))
train.append(float(data[i][4:7]))
train.append(float(data[i][8:11]))
train.append(float(data[i][12:15]))
formatted_data.append(np.array(train))
labels.append((int(data[i][22]))) #Label of data
return formatted_data, labels
"""
label function.
Converts labels into binary format.
First = label which will be vs the rest.
"""
def label(self, labels, first):
for i in range(len(labels)):
if labels[i] == first:
labels[i] = 1 #postive class
else:
labels[i] = -1 #negative class
return labels
"""
Multiclass class.
This class converts the binary perceptron into a multiclass classifier.
"""
class Multiclass(Perceptron):
"""
init function.
Initialises perceptron and enviroment class.
"""
def __init__(self, file_name):
super().__init__()
self.env = Enviroment(file_name) #Calls Enviroment class.
"""
training function.
self.env.data = sorted data
self.recorded_bias = [0,0,0]
self.recorded_errors = []
self.recorded_weight = 3*4 zeros array
Trains for each occurance of the multiclass and records the invidual weights, bias and errors.
"""
def training(self, reg_co):
self.env.data = self.env.read(self.env.file_name)
self.recorded_bias = np.zeros((3))
self.recorded_errors = []
self.recorded_weight = np.zeros((3, 4))
for i in range(3): #For each 1vsrest version.
self.perceptron = Perceptron()
data, labels = self.env.formatter(self.env.data)
labels = self.env.label(labels,i+1)
bias, weight, errors = self.perceptron.train(data, labels, reg_co)
self.recorded_bias[i] += bias #Record Bias
self.recorded_errors.append(errors) #Record Errors
for k in range(len(weight)):
self.recorded_weight[i][k] += weight[k] #Record Weights
"""
test function.
Initialises enviroment with test data.
Creates an array of all the activation values using the weights and bias found in the training.
"""
def test(self, file_name):
self.env = Enviroment(file_name)
self.env.data = self.env.read(self.env.file_name)
self.confidence = np.zeros((len(self.env.data), 3))
random.shuffle(self.env.data) #Shuffle data
data, labels = self.env.formatter(self.env.data)
self.labels = labels
for i in range(3):
class_weight = np.zeros((4))
for j in range(4):
class_weight[j] += self.recorded_weight[i][j]
a = np.dot(data, class_weight) + self.recorded_bias[i]
for j in range(len(a)):
self.confidence[j][i] += a[j] #adds a to the confidence array.
return Multiclass.accuracy(self) #Call accuracy function.
"""
accuracy function.
Using the activation values it finds the maximum for each iteration.
This then becomes the prediction for that data's classification.
Then comparing these to the labels gives an accuracy as a percent.
"""
def accuracy(self):
max_values = []
result = []
acc = []
for i in range(len(self.confidence)):
max_values.append((np.argmax(self.confidence[i])+1)) #Predict class using highest activation value.
for i in range(len(max_values)):
if self.labels[i] == max_values[i]:
result.append(self.labels[i])
for i in range(1,4):
acc.append(result.count(i)/10) #Counts how many of each class were correctly labelled.
return acc
"""
regularisation class.
Class used to run the various l2 regularisation coefficient values.
Calls the multiclass class for each different coefficient value and then plots the results.
"""
class regularisation():
def __init__(self, file_name):
self.file_name = file_name
"""
best_reg function.
Calls multiclass training and testing for each coeffiecient value.
calls the plotting functions to output graphs of the data.
"""
def best_reg(self, regs):
train_errors = []
test_errors = []
for i in regs:
self.multi = Multiclass(self.file_name) #Initialises multiclass class.
self.multi.training(i) #Calls training function.
regularisation.plot_train(self, self.multi.recorded_errors) #Plots training result.
for j in range(len(self.multi.recorded_errors)):
self.multi.recorded_errors[j] = sum(self.multi.recorded_errors[j])/20
train_errors.append(sum(self.multi.recorded_errors)/3)
test = self.multi.test("test.data") #Calls test function. TEST DATA FILE NAME HERE.
regularisation.plot_test(self, test) #Plots test results.
test_errors.append(1-(sum(test)/3))
return train_errors, test_errors #Returns average values for training and testing errors.
"""
plot_train function.
Plots line graph for number of errors for each version of the 1vsrest.
"""
def plot_train(self, errors):
plt.plot(errors[0])
plt.plot(errors[1])
plt.plot(errors[2])
plt.xlim(0,20)
plt.yticks(np.arange(0, 1.1, step=0.1))
plt.xticks(np.arange(0, 21, step=5))
plt.ylabel('Errors')
plt.xlabel('Epoch')
plt.legend(["Class 1 vs Rest", "Class 2 vs Rest", "Class 3 vs Rest"], loc = 1, frameon = False)
plt.show()
"""
plot_test function.
Plots bar graph for correct labeling in the test for each class.
"""
def plot_test(self, acc):
objects = ('Class 1', 'Class 2', 'Class 3')
y_pos = np.arange(len(objects))
plt.bar(y_pos, acc, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.yticks(np.arange(0, 1.1, step=0.1))
plt.ylabel('Correct')
plt.show()
"""
Calls regularisation class and plots average percentage errors over all classes for the regularisation coefficient values.
"""
def main():
x = [0.01, 0.1, 1, 10, 100] #l2 regularisation coefficient values.
env = regularisation("train.data") #Training data file name.
train_errors, test_errors = env.best_reg(x)
plt.plot(x, train_errors)
plt.plot(x, test_errors)
plt.xscale("log")
plt.yticks(np.arange(0, 1.1, step=0.1))
plt.ylabel("Average Percentage Errors over all Classes")
plt.xlabel('Regularisation Coefficient')
plt.legend(["Training Errors", "Test Errors"], loc = 1, frameon = False)
plt.show()
if __name__ == "__main__":
main()
|
# # finding largest element
# def largest(root_node):
# if root_node.right:
# return largest(root_node.right)
# return root_node.value
# if the rightmost node in the binary search tree
# has a left subtree, then the 2nd largest element (in the overall tree)
# is the rightmost element in the subtree, or if there
# is only a left child, the left child.
def second_largest(root_node):
if root_node is None:
return None
if root_node.left and not root_node.right:
return largest(root_node.left)
if root_node.right and not root_node.right.left and not root_node.right.right:
return root_node.value
return second_largest(root_node.right)
# It'll take O(h)O(h) time (where hh is the height of the tree) and O(h)O(h) space.
# But that hh space in the call stack ↴ is avoidable. How can we get this down to constant space?
# constant space
def find_second_largest(root_node):
current = root_node
while current:
# case: current is largest and has a left subtree
# 2nd largest is the largest in that subtree
if current.left and not current.right:
return find_largest(current.left)
# case: current is parent of largest, and
# largest has no children, so
# current is 2nd largest
if current.right and \
not current.right.left and \
not current.right.right:
return current.value
current = current.right
|
import csv
import random
import math
import operator
def loadDataset(filename, split, trainingSet=[] , testSet=[]):
with open(filename, 'r') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in range(len(dataset)-1):
for y in range(4):
dataset[x][y] = float(dataset[x][y])
if random.random() < split:
trainingSet.append(dataset[x])
else:
testSet.append(dataset[x])
'''euclideanDistance'''
def euclideanDistance(instance1, instance2, length):
distance=0
for x in range(length):
distance += pow((instance1[x]-instance2[x]),2)
distance=math.sqrt(distance)
return distance
'''manhattan distance'''
def manhattan(x,y,length):
distance=0
for i in range(length):
distance += abs(x[i]-y[i])
return distance
'''chessboard distance'''
def chessboard(x,y,length):
p=[]
for i in range(length):
p.append(abs(x[i]-y[i]))
return max(p)
def getNeighbors(trainingSet, testInstance, k):
distances = []
distances1 = []
distances2 = []
distances3 = []
length = len(testInstance)-1
for x in range(len(trainingSet)):
dist1 = euclideanDistance(testInstance, trainingSet[x], length)
dist2 = manhattan(testInstance, trainingSet[x],length)
dist3 = chessboard(testInstance, trainingSet[x],length)
distances1.append((trainingSet[x], dist1))
distances2.append((trainingSet[x], dist2))
distances3.append((trainingSet[x], dist3))
distances1.sort(key=operator.itemgetter(1))
distances2.sort(key=operator.itemgetter(1))
distances3.sort(key=operator.itemgetter(1))
# print('distance', distances1,distances2,distances3)
neighbors = []
neighbors1 = []
neighbors2 = []
neighbors3 = []
for x in range(k):
neighbors1.append(distances1[x][0])
neighbors2.append(distances2[x][0])
neighbors3.append(distances3[x][0])
neighbors=[neighbors1,neighbors2,neighbors3]
return neighbors
def getResponse(neighbors):
neighbors1=neighbors[0]
neighbors2=neighbors[1]
neighbors3=neighbors[2]
classVotes1 = {}
classVotes2 = {}
classVotes3 = {}
for x in range(len(neighbors1)):
response1 = neighbors1[x][-1]
if response1 in classVotes1:
classVotes1[response1] += 1
else:
classVotes1[response1] = 1
sortedVotes1 = sorted(classVotes1.items(), key=operator.itemgetter(1), reverse=True)
for x in range(len(neighbors2)):
response2 = neighbors2[x][-1]
if response2 in classVotes2:
classVotes2[response2] += 1
else:
classVotes2[response2] = 1
sortedVotes2 = sorted(classVotes2.items(), key=operator.itemgetter(1), reverse=True)
for x in range(len(neighbors3)):
response3 = neighbors3[x][-1]
if response3 in classVotes3:
classVotes3[response3] += 1
else:
classVotes3[response3] = 1
sortedVotes3 = sorted(classVotes1.items(), key=operator.itemgetter(1), reverse=True)
sortedVotes=[sortedVotes1[0][0],sortedVotes2[0][0],sortedVotes3[0][0]]
# print(sortedVotes)
return sortedVotes
def getAccuracy(testSet, predictions):
correct = 0
for x in range(len(testSet)):
if testSet[x][-1] == predictions[x]:
correct += 1
return (correct/float(len(testSet))) * 100.0
def main():
# prepare data
trainingSet=[]
testSet=[]
split = 0.67
loadDataset('F:\data-analytics\iris.data', split, trainingSet, testSet)
print ('Train set: ' + repr(len(trainingSet)))
print ('Test set: ' + repr(len(testSet)))
# generate predictions
predictions=[]
predictions1=[]
predictions2=[]
predictions3=[]
# k = round(math.sqrt(len(trainingSet)))
k=3
print(k)
print('\n')
for x in range(len(testSet)):
neighbors = getNeighbors(trainingSet, testSet[x], k)
# print(neighbors)
result = getResponse(neighbors)
# print(result)
result1=result[0]
result2=result[1]
result3=result[2]
predictions1.append(result1)
predictions2.append(result2)
predictions3.append(result3)
print('> predicted1=' + repr(result1) + ', actual1=' + repr(testSet[x][-1]))
print('> predicted2=' + repr(result2) + ', actual2=' + repr(testSet[x][-1]))
print('> predicted3=' + repr(result3) + ', actual3=' + repr(testSet[x][-1]))
# print(predictions1)
# print(predictions2)
# print(predictions3)
accuracy1 = getAccuracy(testSet, predictions1)
accuracy2 = getAccuracy(testSet, predictions2)
accuracy3 = getAccuracy(testSet, predictions3)
print('Accuracy1: ' + repr(accuracy1) + '%')
print('Accuracy2: ' + repr(accuracy2) + '%')
print('Accuracy3: ' + repr(accuracy3) + '%')
main()
|
import pygame
## window constants, these will be adjusted upon calling start_display
display_width = 600
display_height = 600
# colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
purple = (255, 0, 255)
###################### example class #################################
# class Square:
# def __init__(self, x_pos, y_pos, width, height):
# self.mX = x_pos
# self.mY = y_pos
# self.mWidth = width
# self.mHeight = height
# self.mImage = pygame.image.load('image.png')
############################# Functions #############################
## ************ Use example class as a reference for objects ********* ##
## take in three parameters, width, height and the programs name. Returns the Display
def start_display(width, height, name):
display_width = width
display_height = height
display = pygame.display.set_mode((width,height))
pygame.display.set_caption(name)
return display
## takes text and displays is to the center of the screen in the given size
def display_message(display, text, size):
textFont = pygame.font.Font('CourierNewBold.ttf', size)
textSurface = textFont.render(text, True, purple)
textRect = textSurface.get_rect()
textRect.center = (display_width/2, display_height/2)
display.blit(textSurface, textRect)
pygame.display.update()
## returns true if the objects are touching, false otherwise (assuming the objects are both rects) images are considered rects
## both objects must have .mX and .mY and .mWidth and .mHeight data members
def collide_rect(object1, object2):
if object1.mX + object1.mWidth > object2.mX > object1.mX and object1.mY + object1.mHeight > object2.mY > object1.mY:
## top left corner of object2 is inside object1, return true
return True
if object1.mX + object1.mWidth > object2.mX + object2.mWidth > object1.mX and object1.mY + object1.mHeight > object2.mY > object1.mY:
## top right corner of object2 is inside object1, return true
return True
if object1.mX + object1.mWidth > object2.mX > object1.mX and object1.mY + object1.mHeight > object2.mY + object2.mHeight > object1.mY:
## bottom left corner of object2 is inside object1, return true
return True
if object1.mX + object1.mWidth > object2.mX + object2.mWidth > object1.mX and object1.mY + object1.mHeight > object2.mY + object2.mHeight > object1.mY:
## bottom right corner of object2 is inside object1, return true
return True
if object2.mX + object2.mWidth > object1.mX > object2.mX and object2.mY + object2.mHeight > object1.mY > object2.mY:
## top left corner of object2 is inside object1, return true
return True
if object2.mX + object2.mWidth > object1.mX + object1.mWidth > object2.mX and object2.mY + object2.mHeight > object1.mY > object2.mY:
## top right corner of object2 is inside object1, return true
return True
if object2.mX + object2.mWidth > object1.mX > object2.mX and object2.mY + object2.mHeight > object1.mY + object1.mHeight > object2.mY:
## bottom left corner of object2 is inside object1, return true
return True
if object2.mX + object2.mWidth > object1.mX + object1.mWidth > object2.mX and object2.mY + object2.mHeight > object1.mY + object1.mHeight > object2.mY:
## bottom right corner of object2 is inside object1, return true
return True
else:
return False
## will return true is the object is touching out of bounds, false otherwise
## requires object to have .mX, .mY, .mWidth, and .mHeight data members
def out_of_bounds(object1):
if object1.mX < 0:
return True
elif object1.mX > display_width - object1.mWidth:
return True
elif object1.mY < 0:
return True
elif object1.mY > display_height - object1.mHeight:
return True
else:
return False
## loads image and returns the image
def load_image(image_name):
image = pygame.image.load(image_name)
return image
## draws image onto display at x,y
def draw_image(display, x, y, image):
display.blit(image, (x, y))
return
## updates the display
def update():
pygame.display.update()
def setBackground(image_name):
image = pygame.image.load(image_name)
return image
def drawBackground(display, background):
display.blit(background, (0,0))
return
|
import sys
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
def main(args):
print("Welcome to the Factorial Calulator!")
num = -1
cont = "y"
while (cont == "y") :
while (num < 1 or num > 10) :
num = input("enter an Integer that's greater than 0, but less than 10: ")
num = int(num)
result = factorial(num)
print("the factorial of " + str(num) + " is " + str(result))
cont = input("Continue? (y/n): ")
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
import re
re.match(r'^\d{3}\-\d{3,8}$', '010-12345')
re.match(r'^\d{3}\-\d{3,8}$', '010 12345')
test = '010 12345' #
if re.match(r'\d{3}\s\d{3,8}$', test): #
print('ok')
else:
print('failed')
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m)
print(m.group(1))
re.match(r'[^0-9]',test)
if re.match(r'[^0-9a-z]',test): # ^ 取反
print('ok')
else:
print('failed')
if re.search(r'\d{3}\s\d{3,8}$', ' 010 12345'): # search只要有就行,而match必须一模一样
print('ok')
else:
print('failed')
# finddall finditer spilt sub
|
"""Find window of time when most authors were active.
For example::
>>> data = [
... ('Alice', 1901, 1950),
... ('Bob', 1920, 1960),
... ('Carol', 1908, 1945),
... ('Dave', 1951, 1960),
... ]
>>> most_active(data)
(1920, 1945)
(Alice, Bob, and Carol were all active then).
If there's more than one period, find the earliest::
>>> data = [
... ('Alice', 1901, 1950),
... ('Bob', 1920, 1960),
... ('Carol', 1908, 1945),
... ('Dave', 1951, 1960),
... ('Eve', 1955, 1985),
... ]
>>> most_active(data)
(1920, 1945)
(Alice, Bob, Carol were active 1920-1945. Bob, Dave, and Eve were active 1951-1960.
Since there's a tie, the first was returned)
"""
def most_active(bio_data):
"""Find window of time when most authors were active."""
years_dict = {}
for year in range(1900, 2000):
years_dict[year] = 0
for name, start, end in bio_data:
value = []
for year in range(start, end + 1):
years_dict[year] += 1
num_authors = years_dict.values()
max_active = max(num_authors)
max_active_period = []
for key, value in years_dict.items():
if value == max_active:
max_active_period.append(key)
start = max_active_period[0]
i = 1
for idx, year in enumerate(max_active_period):
if idx != (len(max_active_period) - 1):
if (max_active_period[i] - max_active_period[idx]) != 1:
end = max_active_period[idx]
break
i += 1
return (start, max_active_period[idx])
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. YAY!\n") |
#*********************************************#
#
# Review one Issue in Lecture 3
#
#*********************************************#
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
alist = [1,2,3]
result = [(0 if c>2 else c) for c in alist]
print("alist:\n",result)
nlist = []
for c in alist:
if c > 2 :
nlist.append(0)
else:
nlist.append(c)
print(nlist)
arr = np.array([1,2,3])
result = [(0 if c>2 else c) for c in arr]
print("arr-to-list:\n",result)
arr = np.array([[1,2,3],[2,3,4]])
result =[(0 if c > 2 else c) for t in arr for c in t]
print(result)
result = np.reshape(result,(2,3))
print(result)
print(np.where(arr > 2, 0, arr))
#*********************************************#
#
# Pandas - DataFrame
#
#*********************************************#
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
frame = DataFrame(data)
print(frame)
print(DataFrame(data, columns=['year','state','pop']))
print(DataFrame(data, columns=['year','state','pop','debt'])) # debt doesn't exist
# A column in a DataFrame can be retrieved as a Series either by dict-like notation or by attribute:
print(frame.columns)
print(frame['state'])
print(frame.state)
print(frame)
#Rows can also be retrieved by position or name by a couple of methods, such as the ix indexing field
print(frame.ix[3])
frame['debt'] = 16.5
print(frame)
# For example, the empty 'debt' column could be assigned a scalar value or an array of values
frame['debt'] = np.arange(5.)
print(frame)
# When assigning lists or arrays to a column, the value’s length must match the length of the DataFrame.
# If you assign a Series, it will be instead conformed exactly to the DataFrame’s index, inserting missing values in any holes:
val = Series([-1.2, -1.5, -1.7], index=[2, 4, 5])
frame['debt'] = val
print(frame)
#Assigning a column that doesn’t exist will create a new column.
frame['eastern'] = 1
print(frame)
frame['marks'] = frame.state == 'Ohio' # if, select target value
del frame['eastern']
print(frame)
# Index Objects
obj = Series(range(3), index=['a', 'b', 'c'])
print(obj)
# Index objects are immutable index[1] = 'd'
# Reindexing
# Calling reindex on this Series rearranges the data according to the new index,
# introducing missing values if any index values were not already present:
obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'])
print(obj2)
obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'], fill_value=0)
print(obj2)
# For ordered data like time series, it may be desirable to do some interpolation or filling of values when reindexing.
# The method option allows us to do this, using a method such as ffill which forward fills the values:
obj3 = Series(['blue', 'purple', 'yellow'], index=[0, 2, 4])
print (obj3)
obj3 = obj3.reindex(range(6), method='ffill')
print(obj3)
# ffill or pad : Fill (or carry) values forward, bfill or backfill : Fill (or carry) values backward
# With DataFrame, reindex can alter either the (row) index, columns, or both.
frame = DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'c', 'd'], columns=['Ohio', 'Texas', 'California'])
print(frame)
# When passed just a sequence, the rows are reindexed in the result:
frame2 = frame.reindex(['a', 'b', 'c', 'd'])
print(frame2)
# The columns can be reindexed using the columns keyword:
states = ['Texas', 'Utah', 'California']
frame = frame.reindex(columns=states)
print(frame)
# Both can be reindexed in one shot, though interpolation will only apply row-wise(axis 0)
frame = frame.reindex(index=['a', 'b', 'c', 'd'], method='ffill', columns=states)
print(frame)
# Dropping entries from an axis
obj = Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e'])
new_obj = obj.drop('c')
print(new_obj)
# With DataFrame, index values can be deleted from either axis:
data = DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four'])
# print(data)
# for i in data.items():
# print("items in data \n",i)
data.drop(['Colorado', 'Ohio'])
print(data)
data.drop('two', axis=1)
print(data)
# Summarizing and Computing Descriptive Statistics
print(data.describe())
print(data.sum())
print(data.sum(axis =1 ))
data.ix["ohio"] = None
print(data)
data1 = data.mean(axis=0, skipna=True)
print(data1)
#like idxmin and idxmax, return indirect statistics like the index value where the minimum or maximum values are attained:
print("idmax = \n",data.idxmax())
|
# if and else statements with loop introduction
word = ['Tokyo','Taj Mahal', 'Pertarico', 'Honalulu', 'Vancover']
new_city = 'Fremont'
for city in word:
if new_city not in word:
print('\nOh, \n\n this is a city....\n\t let me add it:\n' + new_city + '\n\t\t')
word.append(new_city)
print(word)
# if-elif-else
age =12
if age <4:
price = 0
elif age <18:
price = 5
elif age <55:
price = 10
elif age >=55:
price = 5
print("\n\nYour admissions cost is $" + str(price) + ".")
# pizza example checking two lists
available_toppings = ['mushroom', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
request_toppings = ['mushroom', 'french fries', 'extra cheese', 'creamcheese', 'olives']
for request_topping in request_toppings:
if request_topping in available_toppings:
print("\nAdding " + request_topping)
print('\nFinished making your pizza')
# Simple Dictionary
print("\n\n*******\t\tDictionary Intro\t*********\n\n")
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print( "\nYou just earned " + str(alien_0['points']) + " points!")
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
|
import math
from functools import reduce
def lcm(a, b):
return a*b//math.gcd(a, b)
print(reduce(lcm, range(1, 21))) |
class Solution(object):
def isToeplitzMatrix1(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
dic = {}
m, n = len(matrix), len(matrix[0])
for i in range(m):
for j in range(n):
if (i - j) not in dic:
dic[i - j] = matrix[i][j]
elif not matrix[i][j] == dic[i - j]:
return False
return True
def isToeplitzMatrix(self, matrix):
for i in range(len(matrix) - 1):
for j in range(len(matrix[0]) - 1):
if not matrix[i][j] == matrix[i+1][j+1]:
return False
return True
|
from collections import defaultdict
from collections import deque
class Solution:
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
row, column, square, visited = defaultdict(set), defaultdict(set), defaultdict(set), deque([])
for i in range(9):
for j in range(9):
if board[i][j] != ".":
row[i].add(board[i][j])
column[j].add(board[i][j])
square[3 * (i//3) + (j//3)].add(board[i][j])
else:
visited.append((i, j))
def dfs():
if not visited:
return True
i, j = visited[0]
for dig in ("1","2","3","4","5","6","7","8","9"):
if not (dig in row[i]) and not (dig in column[j]) and not (dig in square[3 * (i//3) + (j//3)]):
board[i][j] = dig
row[i].add(dig)
column[j].add(dig)
square[3 * (i//3) + (j//3)].add(dig)
visited.popleft()
if dfs():
return True
else:
board[i][j] = "."
row[i].remove(dig)
column[j].remove(dig)
square[3 * (i//3) + (j//3)].remove(dig)
visited.appendleft((i, j))
return False
dfs()
|
from functools import cmp_to_key
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def compare(x, y):
if int(x + y) > int(y + x):
return -1
else:
return 1
nums = sorted(list(map(str, nums)), key = cmp_to_key(compare))
res = "".join(nums)
return res if int(res) != 0 else "0"
|
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
dic_r = [{},{},{},{},{},{},{},{},{}]
dic_c = [{},{},{},{},{},{},{},{},{}]
dic_s = [{},{},{},{},{},{},{},{},{}]
for i in range(9):
for j in range(9):
if board[i][j] == ".":
continue
if (board[i][j] in dic_r[i]) or (board[i][j] in dic_c[j]) or (board[i][j] in dic_s[3 * (i//3) + j//3]):
return False
else:
dic_r[i][board[i][j]] = 1
dic_c[j][board[i][j]] = 1
dic_s[3 * (i//3) + j//3][board[i][j]] = 1
return True
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees1(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0:
return []
def generate(f, t):
if f > t:
return [None]
elif f == t:
return [TreeNode(f)]
else:
res = []
for i in range(f, t + 1):
left = generate(f, i - 1)
right = generate(i + 1, t)
for l in left:
for r in right:
node = TreeNode(i)
node.left = l
node.right = r
res.append(node)
return res
return generate(1, n)
|
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
#O(n) space complexity
def copyRandomList1(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
dic = {}
node = head
while node:
dic[node] = RandomListNode(node.label)
node = node.next
node = head
while node:
dic[node].next = dic.get(node.next)
dic[node].random = dic.get(node.random)
node = node.next
return dic.get(head)
#O(1) space cmoplexity
def copyRandomList(self, head):
if not head:
return None
#insert a node after each node in the list
cur = head
while cur:
nxt = cur.next
cur.next = RandomListNode(cur.label)
cur.next.next, cur = nxt, nxt
cur = head
#Allocate random pointers
while cur:
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next
#Seperate two lists
cur = second = head.next
while cur and cur.next:
head.next = cur.next
cur.next = cur.next.next
cur, head = cur.next, head.next
head.next = None
return second
|
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
"""
class Solution(object):
def treeToDoublyList1(self, root):
"""
:type root: Node
:rtype: Node
"""
if not root:
return root
else:
l = self.treeToDoublyList(root.left)
r = self.treeToDoublyList(root.right)
l_cur, r_cur = l, r
if l:
while l_cur.right and (not l_cur.right == l):
l_cur = l_cur.right
l_cur.right = root
root.left = l_cur
h = l
else:
h = root
if r:
while r_cur.right and (not r_cur.right == r):
r_cur = r_cur.right
root.right = r
r.left = root
t = r_cur
else:
t = root
t.right = h
h.left = t
return h
def treeToDoublyList(self, root):
if not root: return
dummy = Node(0, None, None)
prev = dummy
stack, node = [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
node.left, prev.right, prev = prev, node, node
node = node.right
dummy.right.left, prev.right = prev, dummy.right
return dummy.right
|
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
#Binary search
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
if not intervals:
return [newInterval]
l, r = 0, len(intervals) - 1
pos = -1
start, end = newInterval.start, newInterval.end
while l <= r:
mid = (l + r) / 2
if intervals[mid].start == start:
pos = mid
break
elif intervals[mid].start < start:
l = mid + 1
else:
r = mid - 1
if pos == -1:
pos = l
if pos == 0 and intervals[pos].start > end:
return [newInterval] + intervals
elif pos and intervals[pos - 1].end >= start:
pos -= 1
res = intervals[:pos]
while pos < len(intervals) and end >= intervals[pos].start:
start = min(intervals[pos].start,start)
end = max(intervals[pos].end, end)
pos += 1
res.append([start, end])
return res if pos >= len(intervals) else res + intervals[pos:]
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
#Space complexity:o(n)
def detectCycle1(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
node, dic = head, {}
while node:
if node in dic:
return node
dic[node] = 1
node = node.next
return None
#Method2: two pointers
def detectCycle(self, head):
if not head:
return None
fast, slow, flag = head, head, False
while fast.next and fast.next.next and slow.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
flag = True
break
slow = head
while flag:
if fast == slow:
return fast
fast = fast.next
slow = slow.next
return None
|
class Solution:
def findMin1(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
t = nums[0]
while nums[0] > nums[-1]:
t = nums[-1]
nums = nums[:-1]
return t
def findMin2(self, nums):
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return min(nums)
mid = len(nums) // 2
if nums[mid - 1] > nums[mid] and nums[mid + 1] > nums[mid]:
return nums[mid]
elif nums[mid] > nums[0] and nums[mid] > nums[-1]:
return self.findMin(nums[mid + 1:])
elif nums[mid] < nums[0] and nums[mid] < nums[-1]:
return self.findMin(nums[:mid])
else:
return nums[0]
def findMin(self, nums):
l = len(nums)
start, end = 0, l - 1
if nums[start] <= nums[end]:
return nums[start]
while start <= end:
mid = (start + end) // 2
if nums[mid - 1] > nums[mid] < nums[(mid + 1) % l]:
return nums[mid]
elif nums[mid] <= nums[end]:
end = mid - 1
else:
start = mid + 1
|
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
re = str(x)[::-1]
while re[0] == '0' and len(re) > 1:
re = re[1:]
if re[-1] == '-':
re = '-' + re[:-1]
re = int(re)
return 0 if x >= 2**31 or x < -2**31 or re >= 2**31 or re < -2**31 else re
|
import functools
class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0:
return "0"
is_positive = (numerator > 0) is (denominator > 0)
numerator, denominator = abs(numerator), abs(denominator)
unit, remainder = divmod(numerator, denominator)
if remainder == 0:
return str(unit) if is_positive else "-" + str(unit)
res = [str(unit), "."]
dic = {}
while not remainder == 0:
if remainder in dic:
res.insert(dic[remainder],"(")
res.append(")")
break
dic[remainder] = len(res)
unit, remainder = divmod(remainder * 10, denominator)
res.append(str(unit))
res = functools.reduce(lambda x,y: x + y, res)
return res if is_positive else "-" + res
|
class Node:
def __init__(self, val):
self.next = None
self.prev = None
self.val = val
self.key = None
class LRUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.size = 0
self.hash = {}
self.last = Node(-1)
self.first = Node(-1)
self.last.next = self.first
self.first.prev = self.last
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.hash:
node = self.hash[key]
self._remove(node)
self._insert(node)
return node.val
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if not key in self.hash:
node = Node(value)
node.key = key
self.hash[key] = node
self.size += 1
self._insert(node)
if self.size > self.capacity:
self.hash.pop(self.last.next.key)
self._remove(self.last.next)
self.size -= 1
elif not value == self.hash[key].val:
node = self.hash[key]
node.val = value
self._remove(node)
self._insert(node)
def _remove(self, node):
pre, nxt = node.prev, node.next
pre.next = nxt
nxt.prev = pre
def _insert(self, node):
orig = self.first.prev
orig.next = node
node.prev = orig
node.next = self.first
self.first.prev = node
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
|
price = float(input("Enter the price: "))
percentage = int(input("Enter the tip percentage: "))
def percent_to_decimal(x):
return x/100
decimal = percent_to_decimal(percentage)
def tip(y, z):
return y * z
tip_amount = tip(price, decimal)
print(tip_amount)
|
# DICTIONARIES
airport_code = "IAH"
airport_name = "Intercontinental Airport"
# Dictionary = {Key: Value}
# creating a dictionary
airport = {"IAH": "Intercontinental Airport" }
# access value from a dictionary
name = airport["IAH"]
print(name)
# Car -- make and model
car = {"make": "Honda", "model": "Accord", "noOfCylinders": 4, "isElectric": False}
print(car["model"])
# empty dictionary
user = {}
user["first_name"] = "John"
user["last_name"] = "Doe"
user["middle_name"] = ""
print(user["middle_name"])
print(user)
# ACTIVITY 1
first_name = input("Enter first name: ")
last_name = input("Enter last name: ")
#street = input("Enter street: ")
#city = input("Enter city: ")
home_address = {"street": "1200 Richmond Ave", "city": "Houston"}
vacation_home_address = {"street": "5533 Stiener Ranch", "city": "Austin"}
# array containing two addresses (array of dictionaries)
addresses = [home_address, vacation_home_address]
user = {"first_name": first_name, "last_name": last_name, "addresses": addresses}
#print("My name is " + user["first_name"] + " " + user["last_name"])
#print(f"My name is {user['first_name']}, {user['last_name']}")
print(user)
reviews = [{"title": "Good product", "rating": 5},{"title": "OK product", "rating": 3},{"title": "Great product", "rating": 4}]
product = {"title": "iPhone 12 Plus", "brand": "Apple", "color": "RED", "reviews": reviews}
# ACTIVITY NESTED JSON STRUCTURE
bank_user = {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"zipcode": "92998-3874",
"geo": {
"lat": "-37",
"lng": "81.0"
}
},
"phone": "1-770-736-8031 x56442"
}
# ITERATING THROUGH THE DICTIONARY
print("ITERATING OVER bank_user DICTIONARY")
print("OPTION 1")
# OPTION 1
for key in bank_user:
print(bank_user[key])
print("OPTION 2")
# OPTION 2
for value in bank_user.values():
print(value)
# OPTION 3
print("OPTION 3")
for key, value in bank_user.items():
print(key)
print(value)
# DELETING FROM A DICTIONARY
print("DELETING FROM A DICTIONARY")
electric_car = {"make": "TESLA", "model": "Model S"}
print(electric_car)
del electric_car["model"]
print(electric_car)
|
total = float(input("Enter the total: "))
tip_percentage = int(input("Enter your tip percentage: "))
def decimal(x):
return x/100
tip_decimal = decimal(tip_percentage)
def tip_calc(y, z):
return y * z
tip = tip_calc(total, tip_decimal)
def combine(a, b):
return a + b
total_amnt = combine(total, tip)
print(total_amnt)
|
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LL:
def __init__(self):
self.head = None
def insert(self, value):
n = Node(value)
print ('n.val', n.val)
if self.head == None:
print ('list empty')
self.head = n
self.current = self.head
else:
while(self.current.next == None):
print('I am here')
self.current.next= n
self.current = self.current.next
return
self.current = self.current.next
def printll(self):
self.current= self.head
while (self.current):
print (self.current.val)
self.current = self.current.next
L = LL()
L.insert(12)
L.insert(13)
L.insert(15)
L.insert(16)
L.insert(18)
L.insert(22)
L.printll()
|
# TODO
# Given a 10 character string with F, B, L, R, use binary space partitioning
# to find which of the rows from 1 to 128 on a plane a code corresponds to
# e.g FBFBBFFRLR:
# 0) Start with the whole range, 0 to 127
# 1) F means lower half, 0 thru 63
# 2) B means upper half, 32 thru 63
# 3) F means lower half, meaning 32 thru 47
# 4) B means upper half, meaning 40 thru 47
# 5) B Keeps 44 thru 47
# 6) F keeps 44 thru 45
# 7) final F keeps 44
# Last 3 characters specify list from 0 to 7
# R keeps upper half, 4 thru 7
# L keeps lower half, 4 thru 5
# R keeps 5
# This would return 44, 5
# Also return seat ID which is row * 8 + column
# My code was messy, and tried to use lists - I cleaned it up by borrowing from
# https://dev.to/qviper/advent-of-code-2020-python-solution-day-5-117d
# Thanks Viper!
# First, let's parse inputs into a list of strings
inputfile = open('input5', 'r')
data = [x.strip() for x in inputfile.readlines()]
# Helper functions to split a list in half and return first or second half
# Deprecated, used a different solution
def getFirstHalf(inlist):
length = len(inlist)
midpoint = (length // 2)
return inlist[:midpoint]
def getSecondHalf(inlist):
length = len(inlist)
midpoint = (length // 2)
return inlist[midpoint:]
def getBoardingPass(inputstring):
# This might be a messy way of doing it, but let's make a list of all numbers btw seatmin and seatmax
# and keep splitting that list
row,col = 0,0
parseline = inputstring[:7]
start = 0
end = 127
for n in parseline:
if n == "F":
end = int((start+end+1)/2)-1
#print(end)
elif n == "B":
start = int((start+end+1)/2)
row = start
parseline = inputstring[7:]
start = 0
end = 7
for n in parseline:
if n == "L":
end = int((start+end+1)/2) -1
elif n == "R":
start = int((start+end+1)/2)
col = start
# print(rowList)
sid = row*8 + col
# ID = (valList[0] * 8 + int(rowList[0]))
# boardingPass.append(ID)
return row,col,sid
def getBoardingPassList(datalist):
bpList = []
for n in datalist:
bpList.append(getBoardingPass(n))
return bpList
BPList = getBoardingPassList(data)
#BFFFBFFLRL
# 0 127
# 63 127 B
# 63 95 F
# 63 79 F
# 63 71 F
# 67 71 B
# 67 69 F
# 68 69 F
# 68
#for n in BPList:
# (print(n))
BPList.sort()
#print(len(BPList))
#First solution: 935
#second solution: 743
#Second problem: Find your seat
#Find the missing boarding pass - seats at front and back dont exist
#I.E seats where the first value is 0 or 127
seat_ids = []
for n in BPList:
seat_ids.append(n[2])
solution = [seat for seat in range(min(seat_ids),max(seat_ids)) if seat not in seat_ids][0]
print(solution)
|
while True:
# get sentence from user
original = input("What would you like to translate?: ").strip().lower()
# split sentence into individual words
words = original.split()
# translate each word (loop through each word and convert)
new_words = []
# if word starts with vowel, add "yay"
for word in words:
if word[0] in "aeiou":
new_word = word + "yay"
new_words.append(new_word)
# otherwise, move consonents to end of word and add "ay"
else:
vowel_pos = 0
for letter in word:
if letter not in "aeiou":
vowel_pos = vowel_pos + 1
else:
break
cons = word[0:vowel_pos]
the_rest = word[vowel_pos:]
new_word = the_rest + cons + "ay"
new_words.append(new_word)
# string words back into sentence
output = " ".join(new_words)
# print translated sentence
print(output.capitalize())
|
string_of_words = input('Введите несколько слова через пробел: ')
entered_words = string_of_words.split(' ')
for ind, el in enumerate(entered_words, 1):
if len(el) > 10:
el = el[0:10]
print(f"{ind}. {el}") |
"""
题目:随机生成校验码
解析:
1. python pillow库的使用
2. 随机数的使用
步骤:
1. 导入庫函数
2. 定义图片颜色
3. 定义字体颜色
4. 定义随机字体的生成
5. 设置画布
6. 设置画笔
7. 在画布上画背景和字体
"""
# 导入庫函数
import os
import string
import random
from PIL import Image, ImageFont, ImageDraw, ImageFilter
# 定义背景颜色
def ran_color():
return (random.randint(64, 255),
random.randint(64, 255),
random.randint(64, 255))
# 定义字体颜色
def font_color():
return (random.randint(32, 127),
random.randint(32, 127),
random.randint(32, 127))
# 定义随机生成的字母数字
def rnd_font():
s = string.ascii_letters + string.digits
r = random.sample(s, 4)
return r
# 切换到当前目录
os.chdir(r"/home/boni/Desktop/practice_010/")
# 定义画布
img = Image.new('RGB', (240, 60), (255, 255, 255))
# 定义验证码的字体
font = ImageFont.truetype(r"/home/boni/Downloads/pycharm-community-2019.2.3/jbr/lib/fonts/DroidSans-Bold.ttf", 40)
# 定义画笔
draw = ImageDraw.Draw(img)
# 用画笔在画布上画出背景色(每一个点为一个像素并随机附上颜色)
for x in range(240):
for y in range(60):
draw.point((x, y), fill=ran_color())
# 得到要画在画布上的字符
print(rnd_font)
# 将字符序列化,画在画布上,并填充颜色
for i, f in enumerate(rnd_font()):
draw.text((60*i+10, 10), f, font=font, fill=font_color())
# 对生成的校验码图片进行模糊处理
img = img.filter(ImageFilter.BLUR)
# 显示生成的校验码
img.show()
# 保存为jpeg格式
img.save('010.jpg', 'jpeg')
|
#Library - Harish
#June 2021
#function
def greet():
print("Good Morning User!")
#function with return tuple type
def check_vowel(arg):
vowel ="aeiou"
l1 = list()
for ch in arg:
if ch in vowel:
l1.append(ch)
print("Vowel found :", end=" ")
for i in range(len(l1)):
print(l1[i], end=" ")
#passing dict as an argument
def printDict(arg):
print("\nDictionary Data as follow: ", end=" ")
for k, v in arg.items():
print(k, v)
greet()
check_vowel('welcome user') |
# Create open list
# Create closed list
# Define Maze
# Define Start and End node
# Add Start to Open_list
# Current = Start
# While(Open_list==0)
# N_up: Check if it is obstacle or
# How to select current?
# # importing the required module
import matplotlib.pyplot as plt
import numpy as np
def main():
# maze = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] )
maze = np.array( [[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] )
start = (0,0)
end = (0,len(maze[0])-1)
# end = (len(maze)-1,len(maze[0])-1)
# end = (9,8)
a = len(maze) + 2
b = len(maze[0]) + 2
maze2 = np.ones((a,b))
for i in range (1,a-1):
for j in range (1,b-1):
maze2[i][j] = maze[i-1][j-1]
fig= plt.figure(figsize=(5.6,5.7))
for i in range (len(maze2)):
for j in range (len(maze2[0])):
a1 = maze2[i][j]
if(a1==0):
# plt.plot(i, j,'rs', fillstyle='none', markersize=27)
plt.plot(j-1, a-i,'rs', fillstyle='none', markersize=27)
else:
# plt.plot(i, j,'bs', fillstyle='full', markersize=25)
plt.plot(j-1, a-i,'bs', fillstyle='full', markersize=25)
# plt.plot(start[0]+1, start[1]+1,'rs', fillstyle='full', markersize=27)
# plt.plot(end[0]+1, end[1]+1,'gs', fillstyle='full', markersize=27)
plt.plot(start[1]+1-1, a-start[0]-1,'rs', fillstyle='full', markersize=27)
plt.plot(end[1]+1-1, a-end[0]-1,'gs', fillstyle='full', markersize=27)
start2 = (start[0]+1, start[1]+1)
end2 = (end[0]+1, end[1]+1)
# res = maze2[::-1]
# maze2 = res
# maze2 = np.transpose(maze2)
# print(maze2)
# print(maze2[end2[0]][end2[1]])
# input()
# DONE flag = "initial";
# DONE Add start to open_list
# DONE current = [0,start2[0],start2[1]]
# DONE counter = 1;
# DONE explored matrix; where obstacles are = -2, rest are -1.
# DONE While(open!= empty)
# DONE if(neighbour_up != obstacle && neighbor_up is not explored yet)
# DONE Calculate f+g // f = current[0]+1// g = abs(end2[0]-n_up[0])+ abs(end2[1]-n_up[1])
# DONE add n_up to open_list
# DONE if(neighbour_left != obstacle && neighbor_left is not explored yet)
# DONE Calculate f+g // f = current[0]+1// g = abs(end2[0]-n_up[0])+ abs(end2[1]-n_up[1])
# DONE add n_left to open_list
# DONE if(neighbour_down != obstacle && neighbor_down is not explored yet)
# DONE Calculate f+g // f = current[0]+1// g = abs(end2[0]-n_up[0])+ abs(end2[1]-n_up[1])
# DONE add n_down to open_list
# DONE if(neighbour_right != obstacle && neighbor_right is not explored yet)
# DONE Calculate f+g // f = current[0]+1// g = abs(end2[0]-n_up[0])+ abs(end2[1]-n_up[1])
# DONE add n_right to open_list
# DONE Add current to closed list
# DONE Remove current from open list
# DONE Update explored[current] = counter;
# DONE sort open list.
# DONE if open_list == empty; set flag = "not found"; break;
# DONE else assign current as first element of open list.
# DONE highlight current node.
# DONE print the current node.
# DONE if current == end; flag = found; break;
# DONE print(flag)
# DONE print(explored_matrix)
flag = "initial"
open_list = [[0,start2[0],start2[1],0]]
closed_list = []
current = open_list[0]
counter = 1
a = len(maze2)
b = len(maze2[0])
explored_matrix = np.ones((a,b)) # Obstacles as -2, Unexplored at -1, Explored at numbers>=0, If it has been added to the open list, then -3.
for i in range (len(explored_matrix)):
for j in range (len(explored_matrix[0])):
q = maze2[i][j]
if(q==1):
explored_matrix[i][j] = -2
else:
explored_matrix[i][j] = -1
# print(maze2)
# print(explored_matrix)
# input()
while(len(open_list)!=0):
x = current[1]
y = current[2]
plt.plot(y-1, a-x,'yo', fillstyle='full', markersize=22)
#Neighbor Up
x = current[1]
y = current[2]+1
if(explored_matrix[x][y]== -1): # Checking if this neighboring node is not obstacle or already explored.
Heuristic = abs(end2[0]-x)+ abs(end2[1]-y) #Manhattan distance
Cost = current[3]+1
g = Cost + Heuristic
open_list.append([g,x,y,Cost])
explored_matrix[x][y]=-3
plt.plot(y-1, a-x,'cx', fillstyle='full', markersize=22)
plt.pause(.1)
#Neighbor Right
x = current[1]+1
y = current[2]
if(explored_matrix[x][y]== -1): # Checking if this neighboring node is not obstacle or already explored.
Heuristic = abs(end2[0]-x)+ abs(end2[1]-y) #Manhattan distance
Cost = current[3]+1
g = Cost + Heuristic
open_list.append([g,x,y,Cost])
explored_matrix[x][y]=-3
plt.plot(y-1, a-x,'cx', fillstyle='full', markersize=22)
plt.pause(.1)
#Neighbor Down
x = current[1]
y = current[2]-1
if(explored_matrix[x][y]== -1): # Checking if this neighboring node is not obstacle or already explored.
Heuristic = abs(end2[0]-x)+ abs(end2[1]-y) #Manhattan distance
Cost = current[3]+1
g = Cost + Heuristic
open_list.append([g,x,y,Cost])
explored_matrix[x][y]=-3
plt.plot(y-1, a-x,'cx', fillstyle='full', markersize=22)
plt.pause(.1)
#Neighbor Left
x = current[1]-1
y = current[2]
if(explored_matrix[x][y]== -1): # Checking if this neighboring node is not obstacle or already explored.
Heuristic = abs(end2[0]-x)+ abs(end2[1]-y) #Manhattan distance
Cost = current[3]+1
g = Cost + Heuristic
open_list.append([g,x,y,Cost])
explored_matrix[x][y]=-3
plt.plot(y-1, a-x,'cx', fillstyle='full', markersize=22)
plt.pause(.1)
open_list.remove(current)
closed_list.append(current)
x = current[1]
y = current[2]
explored_matrix[x][y]=counter
counter += 1
if ( len(open_list)==0 ):
flag = "Goal not found"
break
else:
# open_list.sort()
plt.pause(0.1)
# plt.plot(x, y,'yo', fillstyle='full', markersize=22)
plt.plot(y-1, a-x,'yo', fillstyle='full', markersize=22)
# plt.pause(0.1)
# print(x," ",y)
current = open_list[-1]
if current[1]==end2[0] and current[2]==end2[1]:
plt.plot(current[2]-1, a-current[1],'yo', fillstyle='full', markersize=22)
flag = "Goal found"
print(explored_matrix)
plt.pause(2)
break
# print(open_list)
# print(closed_list)
# input()
# print(explored_matrix)
# print(current)
# input()
# end of while loop
print(flag)
print(explored_matrix)
if flag=="Goal found":
path = []
reach_goal = 0
path.append(current)
node = path[-1]
x = node[1]
y = current[2]
plt.plot(y-1, a-x,'cx', fillstyle='full', markersize=22)
plt.pause(.1)
#While checking neighbors, also check goal.
while(reach_goal== 0):
#find nearest neighbor with least calues explored_matrix value that is greater than 0.
# add that neighbot to path.
#if that neighbot == start:
# plot and break;
neighbors = []
#Neighbor Up
# print("Neighbour Up")
x_neighbor = x
y_neighbor = y+1
score = explored_matrix[x_neighbor][y_neighbor]
# print(x_neighbor," ",y_neighbor," ",score)
if(score>0):
neighbors.append([score,x_neighbor,y_neighbor] )
#Neighbor Right
# print("Neighbour Right")
x_neighbor = x+1
y_neighbor = y
score = explored_matrix[x_neighbor][y_neighbor]
# print(x_neighbor," ",y_neighbor," ",score)
if(score>0):
neighbors.append([score,x_neighbor,y_neighbor] )
#Neighbor Down
# print("Neighbour Down")
x_neighbor = x
y_neighbor = y-1
score = explored_matrix[x_neighbor][y_neighbor]
# print(x_neighbor," ",y_neighbor," ",score)
if(score>0):
neighbors.append([score,x_neighbor,y_neighbor] )
#Neighbor Left
# print("Neighbour Left")
x_neighbor = x-1
y_neighbor = y
score = explored_matrix[x_neighbor][y_neighbor]
# print(x_neighbor," ",y_neighbor," ",score)
if(score>0):
neighbors.append([score,x_neighbor,y_neighbor] )
neighbors.sort()
# print(neighbors)
if(len(neighbors)==0):
print("Path not found")
break
prev = node
node = neighbors[0]
x = node[1]
y = node[2]
x_prev = prev[1]
y_prev = prev[2]
# plt.plot(y-1, a-x,'cx', fillstyle='full', markersize=22)
plt.plot([y_prev-1, y -1],[a - x_prev,a-x],'go-',linewidth=2)
plt.pause(.1)
# print("here")
if(node[1]==start2[0] and node[2]==start2[1]):
reach_goal = 1
x = node[1]
y = node[2]
plt.plot(y-1, a-x,'cx', fillstyle='full', markersize=22)
plt.pause(5)
break
# # naming the axes
# plt.xlabel('x - axis')
# plt.ylabel('y - axis')
# # giving a title to my graph
# plt.title('My first graph!')
# # Setting axes limits
# plt.ylim(-1,11)
# plt.xlim(-1,11)
# # function to show the plot
# # plt.show()
# for i in range (len(maze2)):
# for j in range (len(maze2[0])):
# plt.plot(j, i,'ys', fillstyle='full', markersize=27)
# plt.pause(0.1)
# path = astar(maze, start, end)
# print(path)
if __name__ == '__main__':
main()
|
def add_overflow(numberA, numberB, base):
temp = ''
for i in range(base):
temp += '1'
temp = int(temp, 2)
comA = format(numberA & temp, '0' + str(base) + 'b')
comB = format(numberB & temp, '0' + str(base) + 'b')
strA = str(comA)
strB = str(comB)
plus = 0
count = base
result = ''
for i in range(base):
a = int(strA[count - i - 1])
b = int(strB[count - i - 1])
temp = (plus + a + b) % 2
plus = int((plus + a + b) / 2)
result = str(temp) + result
max = 2 ** (base - 1) - 1
min = -2 ** (base - 1)
out = numberA + numberB
if out > max or out < min:
print(strA + ' + ' + strB + ' = ' + result + ' overflow')
else:
print(strA + ' + ' + strB + ' = ' + result)
if __name__ == '__main__':
add_overflow(1, 1, 2)
|
def fib(n):
if n < 3:
return 1
else:
output=fib(n-2)+fib(n-1)
print(str(output)+' ')
return output
if __name__ == "__main__":
print(str(fib(23)))
# a = 1
# b = 1
# c = 0
# for i in range(23):
# print(a)
# c = a + b
# a = b
# b = c
|
from get_name import get_name
print("Enter 'q' at any time to quit.")
while True:
first_name = input("\nPlease enter your first name:")
if first_name == "q":
break
last_name = input("Please give me a last name:")
if last_name == "q":
break
name = get_name(first_name,last_name)
print("\tNeatly formatted name: " + name + '.')
|
#斐波那契数列递归计算f(n)的值
def fib(n):
if n ==0:
return 0
elif n ==1:
return 1
else:
return fib(n-1)+fib(n-2)
n = int(input(":"))
fib(n)
print(fib(n))
#我不知道在Leetcode怎么回事提交就一直显示fib没有定义
|
#在闭区间范围内统计奇数数目
class Solution:
def countOdds(self, low: int, high: int) -> int:
result = []
for x in range(low,high+1):
if x%2 == 0:
continue
else :
result.append(x)
return len(result)
low = int(input('please enter low value:'))
high = int(input('please enter high value:'))
count = Solution()
num_odd_count = count.countOdds(low,high)
print("count odds is: ",num_odd_count)
|
class Queue_Error(Exception):
def Queue_Overflow(self):
print('Queue overflow')
def Queue_Undeflow(self):
print('Queue underflow')
'''
Queue Dict: using this method will leave a empty space, because to verify the fullness of the queue
we use this condition: q.head == q.tail+1, but at this time q.tail have no data to input, so it is a empty space
to avoid this problem, we let the q.head = q.tail = 0 not '1', to make the length of Queue is 'n'
'''
class Queue_Dict():
def __init__(self,n):
self.QueueLength = n
self.head = 0
self.tail = 0
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, item):
return self.__dict__[item]
def isQueueEmpty(self):
if self.head == self.tail:
return True
else:
return False
def isQueueFull(self):
if self.head == self.tail + 1 or (self.head == 0 and self.tail == self.QueueLength):
return True
else:
return False
def EnQueue(self,x):
try:
if self.isQueueFull():
raise Queue_Error
else:
self[self.tail] = x
if self.tail == self.QueueLength:
self.tail = 0
else:
self.tail = self.tail + 1
except Queue_Error as e:
e.Queue_Overflow()
def DeQueue(self):
try:
if self.isQueueEmpty():
raise Queue_Error
else:
x = self[self.head]
if self.head == self.QueueLength:
self.head = 0
else:
self.head = self.head + 1
return x
except Queue_Error as e:
e.Queue_Undeflow()
class Queue_List():
def __init__(self,n):
self.QueueLength = n
self.head = 0
self.tail = 0
self.DataList = [0]*(n+1)
def isQueueEmpty(self):
if self.head == self.tail:
return True
else:
return False
def isQueueFull(self):
if self.head == self.tail + 1 or (self.head == 0 and self.tail == self.QueueLength):
return True
else:
return False
def EnQueue(self,x):
try:
if self.isQueueFull():
raise Queue_Error
else:
self.DataList[self.tail] = x
if self.tail == self.QueueLength:
self.tail = 0
else:
self.tail = self.tail + 1
except Queue_Error as e:
e.Queue_Overflow()
def DeQueue(self):
try:
if self.isQueueEmpty():
raise Queue_Error
else:
x = self.DataList[self.head]
if self.head == self.QueueLength:
self.head = 0
else:
self.head = self.head + 1
return x
except Queue_Error as e:
e.Queue_Undeflow()
class Double_End_Queue():
def __init__(self,n):
self.QueueLength = n
self.head = 0
self.tail = 0
self.DataList = [0] * (n+2)
def isQueueEmpty(self):
if self.head == self.tail:
return True
else:
return False
def isQueueFull(self):
if self.head == self.tail + 1 or (self.head == 0 and self.tail == self.QueueLength + 1):
return True
else:
return False
def Head_EnQueue(self,x):
try:
if self.isQueueFull():
raise Queue_Error
else:
self.DataList[self.head] = x
if self.head == 0:
self.head = self.QueueLength + 1
else:
self.head = self.head - 1
except Queue_Error as e:
e.Queue_Overflow()
def Head_DeQueue(self):
try:
if self.isQueueEmpty():
raise Queue_Error
else:
if self.head == self.QueueLength + 1:
self.head = 0
else:
self.head = self.head + 1
x = self.DataList[self.head]
return x
except Queue_Error as e:
e.Queue_Undeflow()
def Tail_EnQueue(self,x):
try:
if self.isQueueFull():
raise Queue_Error
else:
self.DataList[self.tail] = x
if self.tail == self.QueueLength + 1:
self.tail = 0
else:
self.tail = self.tail - 1
except Queue_Error as e:
e.Queue_Overflow()
def Tail_DeQueue(self):
try:
if self.isQueueEmpty():
raise Queue_Error
else:
if self.tail == 0:
self.tail = self.QueueLength + 1
else:
self.tail = self.tail -1
x = self.DataList[self.tail]
return x
except Queue_Error as e:
e.Queue_Undeflow()
class Queue_comesfrom_Stack():
pass
|
class Node():
def __init__(self,data):
self.data = data
self.next = None
class Link_Error(Exception):
def Not_Found(self,data):
print('%d not found' % data)
class Single_Link_List():
def __init__(self):
self.head = None
self.temp = None
self.Lenght = 0
def Insert_Link_Tail(self,data):
node = Node(data)
if self.head == None:
self.head = node
self.temp = node
else:
self.temp.next = node
self.temp = node
self.Lenght = self.Lenght + 1
def Insert_Link_Head(self,data):
node = Node(data)
node.next = self.head
self.head = node
def Delete_Link(self, data):
temp1 = temp2 = self.head
while temp1 != None and temp1.data != data:
temp2 = temp1
temp1 = temp1.next
if temp1 != None:
if temp2 != temp1:
temp2.next = temp1.next
else:
self.head = temp1.next
else:
print('%d is not found' % data)
def Search_Link(self,data):
self.temp = self.head
while self.temp != None and self.temp.data != data:
self.temp = self.temp.next
if self.temp != None:
return self.temp.data
else:
return None
def Print_Link(self):
self.temp = self.head
while self.temp != None:
data = self.temp.data
self.temp = self.temp.next
print(data)
# test
L = Single_Link_List()
for i in range(1,6):
L.Insert_Link_Head(i)
L.Print_Link()
print(L.Search_Link(0))
L.Delete_Link(3)
L.Print_Link() |
import time as t
from os import path
def createFile(dest):
'''
the script creates a text fileat the passed in location
names file based on date
'''
date=t.localtime(t.time())
##FileName = Month_Day_Year
name='%d_%d_%d.txt'%(date[1],date[2],(date[0]%100))
if not (path.isfile(dest + name)):
f=open(dest + name,'w')
f.write('\n'*30)
f.close()
if __name__=='__main__':
destination='C:\\Users\
\\arindam das modak\\Desktop\\python scripting\\'
createFile(destination)
raw_input("Done")
|
'''
We are given a binary tree (with root node root), a target node, and an integer value K.
Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
Output: [7,4,1]
Explanation:
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.
Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.
Note:
The given tree is non-empty.
Each node in the tree has unique values 0 <= node.val <= 500.
The target node is a node in the tree.
0 <= K <= 1000.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
"""
# search below target node
vals = []
queue = deque([(target, 0)])
while queue:
node, dist = queue.pop()
if dist == K:
vals.append(node.val)
elif dist < K:
if node.left:
queue.append((node.left, dist + 1))
if node.right:
queue.append((node.right, dist + 1))
else:
continue
visited = deque([])
# search above target node
queue.append((root, 0, None))
lookup = {}
target_dist=None
while queue:
(node, dist, parent) = queue.popleft()
if target_dist is not None and dist > target_dist:
break
if node == root:
lookup[node] = 0
if node == target:
target_dist=dist
lookup[node] = dist
lookup[target] = 0
else:
if node.left:
queue.append((node.left, dist + 1, node))
if node.right:
queue.append((node.right, dist + 1, node))
visited.append((node, dist, parent))
while visited:
(node, dist, parent) = visited.popleft()
if parent in lookup:
if lookup[parent] + dist == K:
vals.append(node.val)
else:
queue.append((node, dist, parent))
return vals
|
from unittest import TestCase
import ddt
class Solution:
def permuteUnique(self, nums):
ans=[]
nums.sort()
visited=set()
def DFS(perm, other_nums):
if not other_nums:
visited.add(''.join(perm))
ans.append(perm)
return
for j in range(len(other_nums)):
DFS(perm+[other_nums[j]], other_nums[:j] + other_nums[j + 1:])
for i in range(len(nums)):
if nums[i] in visited:
continue
else:
visited.add(nums[i])
DFS([nums[i]], nums[:i]+nums[i+1:])
return ans
@ddt.ddt
class LeetCodeTest(TestCase):
def setUp(self):
self.solution = Solution()
@ddt.unpack
@ddt.data(
([[1, 1, 2]], [[1, 1, 2], [1, 2, 1], [2, 1, 1]]))
def test_solution(self, args, output):
response = self.solution.permuteUnique(*args)
self.assertEqual(response, output, "\n\nexpected: {} \n actual: {}\n".format(output, response))
|
'''
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
You may assume k is always valid, 1 <=
k <= number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
'''
# class MySolution(object):
# def topKFrequent(self, nums, k):
# """
# :type nums: List[int]
# :type k: int
# :rtype: List[int]
# """
# counts = {}
# unums = set(nums)
# for unum in unums:
# counts[unum] = nums.count(unum)
#
# def foo():
# unum = max(unums, key=lambda unum: counts[unum])
# unums.remove(unum)
# return unum
#
# return [foo() for i in range(k)]
class Solution(object):
def topKFrequent(self, nums, k):
def heapify(heap, i, n):
l = i * 2 + 1
r = i * 2 + 2
maxidx = i
if l < n and heap[l][0] > heap[i][0]:
maxidx = l
if r < n and heap[r][0] > heap[maxidx][0]:
maxidx = r
if maxidx != i:
heap[maxidx], heap[i] = heap[i], heap[maxidx]
heapify(heap, maxidx, n)
counter = dict()
for i in nums:
counter[i] = counter.get(i, 0) + 1
heap = []
for num in counter:
heap.append((counter[num], num))
for i in range(len(heap) // 2 - 1, -1, -1):
heapify(heap, i, len(heap))
res = []
for i in range(1, k + 1):
res.append(heap[0][1])
heap[0] = heap[-i]
heapify(heap, 0, len(heap) - i)
print(heap)
return res
for nums, k in [
([1,1,1,2,2,3], 2)
]:
sol = Solution().topKFrequent(nums, k)
print(sol) |
from collections import defaultdict
from unittest import TestCase
import ddt
'''
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character '.'.
A sudoku puzzle...
...and its solution numbers marked in red.
Note:
The given board contain only digits 1-9 and the character '.'.
You may assume that the given Sudoku puzzle will have a single unique solution.
The given board size is always 9x9.
'''
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
self.board = board
self.rowMap = defaultdict(lambda: set([]))
self.colMap = defaultdict(lambda: set([]))
self.boxMap = defaultdict(lambda: set([]))
def next_cell():
for i in range(9):
for j in range(9):
if self.board[i][j] == '.':
return (i, j)
return (-1, -1)
def assign_box(i, j):
if 0 <= i < 3:
if 0 <= j < 3:
box = 1
elif 3 <= j < 6:
box = 2
else:
box = 3
elif 3 <= i < 6:
if 0 <= j < 3:
box = 4
elif 3 <= j < 6:
box = 5
else:
box = 6
else:
if 0 <= j < 3:
box = 7
elif 3 <= j < 6:
box = 8
else:
box = 9
return box
def val_remove(i, j, c):
self.board[i][j] = '.'
self.rowMap[i].remove(c)
self.colMap[j].remove(c)
self.boxMap[assign_box(i, j)].remove(c)
def val_add(i, j, c):
self.board[i][j] = c
self.rowMap[i].add(c)
self.colMap[j].add(c)
self.boxMap[assign_box(i, j)].add(self.board[i][j])
def is_valid(i, j, c):
if (c in self.colMap[j] or
c in self.rowMap[i] or
c in self.boxMap[assign_box(i, j)]):
return False
else:
return True
def backtrack():
(i, j) = next_cell()
if (i, j) == (-1, -1):
return True
for c in [str(num) for num in range(1, 10)]:
if is_valid(i, j, c):
val_add(i, j, c)
if backtrack():
return True
val_remove(i, j, c)
else:
continue
return False
for i in range(9):
for j in range(9):
if self.board[i][j] != '.':
val_add(i, j, self.board[i][j])
backtrack()
return self.board
@ddt.ddt
class LeetCodeTest(TestCase):
def setUp(self):
self.solution = Solution()
@ddt.unpack
@ddt.data(
([
[["5", "3", ".", ".", "7", ".", ".", ".", "."], ["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."], ["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"], ["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."], [".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"]]
], [["5", "3", "4", "6", "7", "8", "9", "1", "2"], ["6", "7", "2", "1", "9", "5", "3", "4", "8"],
["1", "9", "8", "3", "4", "2", "5", "6", "7"], ["8", "5", "9", "7", "6", "1", "4", "2", "3"],
["4", "2", "6", "8", "5", "3", "7", "9", "1"], ["7", "1", "3", "9", "2", "4", "8", "5", "6"],
["9", "6", "1", "5", "3", "7", "2", "8", "4"], ["2", "8", "7", "4", "1", "9", "6", "3", "5"],
["3", "4", "5", "2", "8", "6", "1", "7", "9"]]),
)
def test_solution(self, args, output):
response = self.solution.solveSudoku(*args)
self.assertEqual(response, output, "\n\nexpected: {} \n actual: {}\n".format(output, response))
|
from unittest import TestCase
import ddt
'''
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
'''
class Solution(object):
def correct_threeSumClosest(self, nums, target):
nums.sort()
res = sum(nums[:3])
for i in xrange(len(nums)):
l, r = i + 1, len(nums) - 1
while l < r:
s = sum((nums[i], nums[l], nums[r]))
if abs(s - target) < abs(res - target):
res = s
if s < target:
l += 1
elif s > target:
r -= 1
else: # break early
return res
return res
def my_threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
diff = target
sol = sum(nums[:3])
for a in range(len(nums) - 2):
b, c = a + 1, len(nums) - 1
while b < c:
s = nums[a] + nums[b] + nums[c]
if abs(s - target) < diff:
diff = s - target
sol = s
if s == target:
return target
elif s < target:
b += 1
else:
c -= 1
return sol
@ddt.ddt
class LeetCodeTest(TestCase):
def setUp(self):
self.solution = Solution()
@ddt.unpack
@ddt.data(
([[-1, 2, 1, -4], 1], 2),
)
def test_solution(self, args, output):
response = self.solution.correct_threeSumClosest(*args)
self.assertEqual(response, output, "\n\nexpected: {} \n actual: {}\n".format(output, response))
|
from unittest import TestCase
import ddt
'''
Single Number
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
'''
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
hm = {}
for num in nums:
hm[num] = hm.get(num,0)+1
for k, v in hm.items():
if v == 1:
return k
@ddt.ddt
class LeetCodeTest(TestCase):
def setUp(self):
self.solution = Solution()
@ddt.unpack
@ddt.data(
([[2, 2, 1]], 1),
([[4, 1, 2, 1, 2]], 4),
)
def test_solution(self, args, output):
response = self.solution.singleNumber(*args)
self.assertEqual(response, output, "expected: {} \n actual: {}\n".format(output, response))
|
from unittest import TestCase
import ddt
'''
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[1, 5, 9],
[6, 7, 9],
[8, 15, 15]
],
k = 8,
return 13.
'''
from heapq import *
class Solution:
def find_Kth_smallest(matrix, k):
minHeap = []
for i in range(min(k, len(matrix))):
heappush(minHeap, (matrix[i][0], 0, matrix[i]))
numberCount, number = 0, 0
while minHeap:
number, i, row = heappop(minHeap)
numberCount += 1
if numberCount == k:
break
if len(row) > i + 1:
heappush(minHeap, (row[i + 1], i + 1, row))
return number
@ddt.ddt
class LeetCodeTest(TestCase):
def setUp(self):
self.solution = Solution()
@ddt.unpack
@ddt.data(
([[[1, 5, 9], [10, 11, 13], [12, 13, 15]], 8], 13))
def test_solution(self, args, output):
response = self.solution.kthSmallest(*args)
self.assertEqual(response, output, "\n\nexpected: {} \n actual: {}\n".format(output, response))
|
class WordList:
def __init__(self, word_list_path):
self.word_list_path = word_list_path
self.word_list = []
self.__read_word_list()
def __read_word_list(self):
with open(self.word_list_path, 'r') as file:
for line in file:
if line:
l = line.strip()
if not l.startswith('#'):
self.word_list.append(l)
|
#! /usr/bin/env python3
# we will store the current largest number here
matched = "Well done, Friend! You are free now."
# input the first value
number = int(input("Enter the magic number: "))
while number != 777:
# is number larger than largest_number?
if number == matched:
# yes, update largest_number
matched = number
number = int(input("Ha ha! You're stuck in my loop! Try again! "))
print(matched)# we will store the current largest number here
matched = "Well done, Friend! You are free now."
# input the first value
number = int(input("Enter the magic number: "))
while number != 777:
# is number larger than largest_number?
if number == matched:
# yes, update largest_number
matched = number
number = int(input("Ha ha! You're stuck in my loop! Try again "))
print(matched)
|
# this class implements an iterator
# python needs to be told when to stop iterating, this is done by raising StopIteration exception
class ReverseString():
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.data[self.index]
def main():
foo = ReverseString('foobar')
for c in foo:
print(c)
if __name__ == "__main__":
main()
|
import math
from World.node import *
import sys
def dir_dist(node1, node2):
"""
Calculates the direct distance bewteen each points
"""
return math.sqrt(math.pow(node1.x - node2.x, 2) +
math.pow(node1.y - node2.y, 2))
def shortest_dist(agent_pos, containers_pos, cont_goals):
"""
Calculates a heuristic for the Planning Astar algorithm. h = distance from
agent to nearest container + distance from containers to their goal location
"""
dist = sys.maxsize
counter = 0
#heuristic for agent to nearest container
for pos_num, pos in enumerate(containers_pos):
if dir_dist(agent_pos, pos) < dist:
if pos != cont_goals[pos_num]:
dist = dir_dist(agent_pos, pos)
else:
counter += 1
if counter == len(containers_pos):
dist = 0
#heuristic from each container to its goal location
for pos_num, pos in enumerate(containers_pos):
dist += dir_dist(pos, cont_goals[pos_num])
#print(str(dist))
return dist
def container_dist(agent_pos, containers_pos, cont_goals):
dist = 0
#heuristic from each container to its goal location
for pos_num, pos in enumerate(containers_pos):
dist += dir_dist(pos, cont_goals[pos_num])
#print(str(dist))
return dist
|
# https://leetcode.com/problems/search-a-2d-matrix
class Solution(object):
# Time complexity: O(logM + LogN)
# Space complexity: O(1)
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0] : return False
m = len(matrix)
n = len(matrix[0])
left, right = 0, m - 1
while left <= right:
mid = left + (right - left) // 2
if matrix[mid][0] == target:
return True
elif matrix[mid][0] < target:
left = mid + 1
else:
right = mid - 1
row = min(left, right)
left, right = 0, n - 1
while left <= right:
mid = left + (right - left) // 2
if matrix[row][mid] == target:
return True
elif matrix[row][mid] < target:
left = mid + 1
else:
right = mid - 1
return False
|
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if (len(s) != len(t)):
return False
else:
return collections.Counter(s) == collections.Counter(t)
# Time complexity: O(N)
# Space complexity: O(1)
def isAnagram1(self, s, t)
dic = collections.defaultdict(int)
for item in s: dic[item] += 1
for item in t: dic[item] -= 1
return all(x == 0 for x in dic.values())
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
def dfs(curr):
if not curr: return False
l = dfs(curr.left)
r = dfs(curr.right)
if (l is True and r is True) or ((curr.val == p.val or curr.val == q.val) and (l is True or r is True)):
self._comm = curr
if l is True or r is True or (curr.val == p.val or curr.val == q.val):
return True
dfs(root)
return self._comm
"""
node1 = TreeNode(3)
node2 = TreeNode(5)
node3 = TreeNode(1)
node4 = TreeNode(6)
node5 = TreeNode(2)
node6 = TreeNode(0)
node7 = TreeNode(8)
node8 = TreeNode(7)
node9 = TreeNode(4)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.left = node7
node3.right = node8
node5.left = node8
node5.right= node9
obj = Solution()
common = obj.lowestCommonAncestor(node1, node2, node3)
print("lowest common ancestor:{}".format(common.val))
"""
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 6 17:00:07 2020
@author: conpucter
"""
'''
this task is not done yet
this search doesn't work with extreme numbers like 0 and 73
'''
array = [0, 1, 21, 33, 45, 45, 61, 71, 72, 73]
target = 71
def array_keeper(array):
print("array keeper i\'m calling you")
def binary_search(array, target):
count = 0
a = 0
b = len(array) - 1
while 1 == 1:
position = (a + b)//2
print(a, b, position)
if array[position] > target:
#print("number is larger than target")
b -= position
elif array[position] < target:
#print("number is smaller than target")
a += position
else:
print(position)
break
count += 1
if count == len(array):
#kind of protection...
print("ERROR: there\'s no such number or the array isn\'t sorted")
break
binary_search(array, target)
|
"""
CP1404/CP5632 Practical
Demos of various os module examples
"""
import shutil
import os
def main():
"""Demo os module functions."""
print("Starting directory is: {}".format(os.getcwd()))
# Change to desired directory
os.chdir('Lyrics/Christmas')
# Loop through each file in the (current) directory
for filename in os.listdir('.'):
# Ignore directories, just process files
if os.path.isdir(filename):
continue
new_name = get_fixed_filename(filename)
print("Renaming {} to {}".format(filename, new_name))
def get_fixed_filename(filename):
"""Return a 'fixed' version of filename."""
new_name = filename.capitalize()
new_name = filename.replace(" ", "_").replace(".TXT", ".txt")
list(enumerate(new_name))
str = '_'
for i, char in enumerate(new_name):
if new_name[i].islower() and new_name[i+1].isupper():
str.join()
return new_name
main()
# demo_walk() |
import random
def main():
score = int(input('Enter your score: '))
result=get_result(score)
random_score = random.randint(0, 100)
print('Random score:',random_score)
result = get_result(random_score)
def get_result(score):
if score<50:
print('Your result is Fail')
elif score>=50 and score<=64:
print('Your result is Pass')
elif score>=65 and score<=74:
print('Your result is Pass with Credit')
elif score>=75 and score<=84:
print('Your result is Pass with Distinction')
elif score>=85 and score<=100:
print('Your result is Pass with High Distinction')
main() |
FILENAME = "subject_data.txt"
def main():
data = get_data()
print(data)
print(get_details())
def get_data():
"""Read data from file formatted like: subject,lecturer,number of students."""
input_file = open(FILENAME)
list = []
for line in input_file:
line = line.strip() # Remove the \n
parts = line.split(',') # Separate the data into its parts
parts[2] = int(parts[2]) # Make the number an integer (ignore PyCharm's warning)
list.append(parts)
input_file.close()
print(list)
def get_details():
input_file = open(FILENAME)
list = []
for line in input_file:
line = line.strip() # Remove the \n
parts = line.split(',') # Separate the data into its parts
parts[2] = int(parts[2]) # Make the number an integer (ignore PyCharm's warning)
list.append(parts)
subject = parts[0]
name = parts[1]
num = parts[2]
print('{} is taught by {:<12} and has {:3} students'.format(subject,name,num))
input_file.close()
main() |
import unittest
from problem import is_valid_credit_card
def test_with_valid_credit_cards():
numbers = [
49927398716,
378282246310005, # AMEX
6011111111111117, # DISCOVER
5555555555554444, # MASTERCARD
4111111111111111 # VISA
]
for number in numbers:
assert is_valid_credit_card(number) == True
def test_with_negative_credit_card():
number = -49927398716
assert is_valid_credit_card(number) == False
|
def validate_palindrom_using_for_loop(string):
n = len(string)
start = 0
end = n-1
for i in xrange(n/2):
if not(string[start].isalnum()):
start += 1
continue
elif not(string[end].isalnum()):
end -= 1
continue
elif(string[start] != string[end]):
print "not palindrom"
return
print "palindrom"
return
if __name__ == "__main__":
print "Enter your shring :"
inp = raw_input()
validate_palindrom_using_for_loop(inp)
|
# Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Python
def max(num1,num2):
''' takes two numbers and return maximum of them'''
if num1 > num2:
return num1
return num2
if __name__ == "__main__":
inputs = raw_input("Enter space saperated 2 numbers: ").split()
if len(inputs) != 2:
inputs.append(input())
try:
print max(float(inputs[0]),float(inputs[1]))
except ValueError:
print "Invalid numbers"
|
# Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"ar"} and use it to translate your Christmas cards from English into Swedish. Use the higher order function map() to write a function translate() that takes a list of English words and returns a list of Swedish words.
def translate(word_list):
base_dict = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"ar"}
res = []
return map(lambda y:base_dict[y] ,filter(lambda x: base_dict.has_key(x), word_list))
if __name__ == "__main__":
print translate(["happy","new","year"])
|
def check_palindrom_using_inbuilt_functions(input_string):
inp = list(input_string)
rev = list(input_string)
rev.reverse()
if inp == rev:
print "palindrom"
else:
print "not palindrom"
def validate_palindrom_using_for_loop(string):
n = len(string)
for i in xrange(n/2):
if(string[i] != string[n-i-1]):
print "not palindrom"
return
print "palindrom"
if __name__ == "__main__":
print "Enter your shring :"
inp = raw_input()
check_palindrom_using_inbuilt_functions(inp)
validate_palindrom_using_for_loop(inp)
|
#A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: The quick brown fox jumps over the lazy dog. Your task here is to write a function to check a sentence to see if it is a pangram or not.
def pangram(string):
result = "Pangram"
all_char = [x for x in range(ord('a'),ord('z')+1)]
for char in all_char:
if chr(char) not in string:
result = "Not a Pangram"
break
return result
if __name__ == "__main__":
string = "The quick brown fox jumps over the lazy dog"
print string,"::\t",pangram(string)
|
# Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.
def is_vowel(character):
vowels = "aeiou"
return character.lower() in vowels
if __name__ == "__main__":
char = raw_input("Enter single character: ")
print is_vowel(char)
|
class Father:
def __init__(self):
print("__init__() of Father ")
self.name = "Gaurav"
class Mother:
def __init__(self):
print("__init__ of Mother ")
self.name = "Maity"
# Order of 'Mother' and 'Father' decides whose members are accessed if they have same member names
# Whichever class-name comes first has its attributes accessed
class Child(Mother, Father):
# It is called as soon as the object of 'Child' class is created
def __init__(self):
super().__init__()
def printName(self):
print(self.name)
obj1 = Child()
obj1.printName()
|
import math
class Point:
def __init__(self, p1, p2):
self.__p1 = p1
self.__p2 = p2
def __str__(self):
return "A message from point (" + str(self.__p1) + "," + str(self.__p2) + ")"
# Overloading '+' operator, __add__() is fixed
def __add__(self, point_object):
return Point(self.__p1 + point_object.__p1, self.__p2 + point_object.__p2)
# Overloading '<' operator
def __lt__(self, point_object):
return math.sqrt(self.__p1**2 + self.__p2**2) < math.sqrt(point_object.__p1**2 + point_object.__p2**2)
s1 = Point(2,5)
s2 = Point(6, 1)
p3 = s1 + s2
print(f"{p3}")
|
class BTNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def BTInput():
n = int(input())
if n == -1:
return None
new_node = BTNode(n)
new_node.left = BTInput()
new_node.right = BTInput()
return new_node
def BTPrint(root):
if root == None:
return
print(f"{root.data}", end = ': ')
if root.left != None:
print(f"{root.left.data}", end = ', ')
if root.right != None:
print(f"{root.right.data}", end = ' ')
print()
BTPrint(root.left)
BTPrint(root.right)
# Function prints sum of data in all the nodes
def BTSumOfNodes(root):
if root == None:
return 0
left_sum = BTSumOfNodes(root.left)
right_sum = BTSumOfNodes(root.right)
return root.data + left_sum + right_sum
root = BTInput()
BTPrint(root)
sum = BTSumOfNodes(root)
print(f"Sum of data in all the nodes of the Binary Tree : {sum}")
|
class BTNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def BTInput():
n = int(input())
if n == -1:
return None
new_node = BTNode(n)
new_node.left = BTInput()
new_node.right = BTInput()
return new_node
def BTPrint(root):
if root == None:
return
print(f"{root.data}", end = ': ')
if root.left != None:
print(f"{root.left.data}", end = ', ')
if root.right != None:
print(f"{root.right.data}", end = ' ')
print()
BTPrint(root.left)
BTPrint(root.right)
# preorder traversal - Root, left, right
def BTPreorder(root):
if root == None:
return
print(f"{root.data}", end = ' ')
BTPreorder(root.left)
BTPreorder(root.right)
# postorder traversal
def BTPostorder(root):
if root == None:
return
BTPostorder(root.left)
BTPostorder(root.right)
print(f"{root.data}", end = ' ')
# inorder traversal
def BTInorder(root):
if root == None:
return
BTInorder(root.left)
print(f"{root.data}", end = ' ')
BTInorder(root.right)
root = BTInput()
BTPrint(root)
print("Preorder ", end = ': ')
BTPreorder(root)
print()
print("Inorder ", end = ': ')
BTInorder(root)
print()
print("Postorder", end = ': ')
BTPostorder(root)
print()
|
c = "#"
s = input("Enter a string containing duplicates : ")
def DelimitDuplicate(s, si):
# Base case when si reached the end of string
if si >= len(s)-1:
return s
if s[si] == s[si + 1]:
modified_string = s[:si+1] + c + s[si+1:]
return DelimitDuplicate(modified_string, si + 1)
else:
return DelimitDuplicate(s, si + 1)
new_str = DelimitDuplicate(s, 0)
print(new_str)
|
class BTnode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def BTinput():
new_node = int(input("-> "))
if new_node == -1:
return
else:
root = BTnode(new_node)
root.left = BTinput()
root.right = BTinput()
return root
def BSTinput(l):
if len(l) == 0:
return None
mid_index = len(l)//2
root = BTnode( l[mid_index] )
root.left = BSTinput( l[:mid_index] )
root.right = BSTinput( l[mid_index+1:] )
return root
def BTPrint(root):
if root == None:
return
print(f"{root.data}", end = ': ')
if root.left != None:
print(f"{root.left.data}", end = ', ')
if root.right != None:
print(f"{root.right.data}", end = ' ')
print()
BTPrint(root.left)
BTPrint(root.right)
def BTfindMax(root):
if root == None:
return INT_MIN
left_max = BTfindMax(root.left)
right_max = BTfindMax(root.right)
return max(left_max, right_max, root.data)
def BTfindMin(root):
if root == None:
return INT_MAX
left_min = BTfindMin(root.left)
right_min = BTfindMin(root.right)
return min(left_min, right_min, root.data)
def BSTcheck(root):
if root == None:
return True
max_left_subtree = BTfindMax(root.left)
min_right_subtree = BTfindMin(root.right)
if (max_left_subtree > root.data) or (min_right_subtree < root.data):
return False
is_left_BST = BSTcheck(root.left)
is_right_BST = BSTcheck(root.right)
return is_left_BST and is_right_BST
INT_MAX = 2147483647
INT_MIN = -2147483648
#print("Enter a list of integers (space separated): ", end = ' ')
#input_list = [int(i) for i in input().split()]
#input_list.sort()
#root = BSTinput(input_list)
root = BTinput()
BTPrint(root)
isBST = BSTcheck(root)
if isBST is True:
print("A BST")
else:
print("Not a BST")
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
def print_list(self, head):
ptr = head
while ptr is not None:
print(f"{ptr.data}->", end = ' ')
ptr = ptr.next
print("None")
def length(self, head):
ptr = head
count = 0
while ptr is not None:
count += 1
ptr = ptr.next
return count
def print_ith_node(self, head, i):
ptr = head
count = 0
while ptr is not None:
count += 1
if count == i:
return ptr.data
ptr = ptr.next
return -1
def insert(self, head, n, i):
ptr = head
new_node = Node(n)
# insert at the beginning
if i == 1:
new_node.next = head.next
head = new_node
return head
for j in range(1, i):
if j == i-1:
new_node.next = ptr.next
ptr.next = new_node
return head
else:
ptr = ptr.next
def GetList():
# Getting list elements from user
input_list = [int(i) for i in input("Enter the list -> ").split()]
head = None
tail = None
for n in input_list:
# Create a node and link its 'next'
new_node = Node(n)
# If it is the first element of input list
if head is None:
tail = head = new_node
continue
# If it is not the first element in the list
tail.next = new_node
tail = new_node
return head
head = GetList()
#head.print_list(head)
#size = head.length(head)
#print(f"List has : {size} elements")
#i = int(input("Enter the index (starting from 1) you want to query: "))
#result = head.print_ith_node(head, i)
#print(f"list[i] : {result}")
head.print_list(head)
head = head.insert(head, 200, 2)
head.print_list(head)
|
import sys
sys.setrecursionlimit(5000)
n = int(input("Enter the number to search : "))
user_input = input("Enter the list (space separated) : ")
input_list = [int(i) for i in user_input.strip().split(' ')]
# Recursive approach
def FindNumber(index):
if input_list[index] == n:
print(f"{n} found at index : {index}")
return
if index < 0:
print(f"{n} NOT found in list !")
return False
FindNumber(index - 1)
FindNumber(len(input_list) - 1)
|
# Implementing graphs using adjacency matrix
class Graph:
def __init__(self, nVertices):
self.nVertices = nVertices
self.adjMatrix = [[0 for i in range(nVertices)] for j in range(nVertices)]
def addEdge(self, v1, v2):
if (v1 > self.nVertices - 1) or (v1 < 0) or (v2 > self.nVertices - 1) or (v2 < 0):
return False
self.adjMatrix[v1][v2] = 1
self.adjMatrix[v2][v1] = 1
def bfs(self):
import queue
q = queue.Queue()
visited = [False for x in range(self.nVertices)]
q.put(0)
q.put(None)
visited[0] = True
while not q.empty():
i = q.get()
if i is not None:
print(i, end = ' ')
else:
print()
if q.empty():
break
q.put(None)
continue
for j in range(self.nVertices):
if self.adjMatrix[i][j] == 1 and visited[j] == False:
q.put(j)
visited[j] = True
# Returns a list of path from v1->v2, if path doesn't exist, returns None
def __getPathHelper(self, v1, v2, visited, l):
if self.adjMatrix[v1][v2] == 1:
l.append(v2)
l.append(v1)
return l
visited[v1] = True
for c in range(self.nVertices):
if self.adjMatrix[v1][c] == 1 and visited[c] == False:
ans = self.__getPathHelper(c, v2, visited, l)
if ans is not None:
l.append(v1)
return l
return None
def getPath(self, v1, v2):
visited = [False for i in range(self.nVertices)]
# v1 should store the smaller value
if v1 > v2:
v1, v2 = v2, v1
List = list()
for i in range(self.nVertices):
if visited[i] == False:
result = self.__getPathHelper(v1, v2, visited, List)
if result is not None:
break
return result
def removeEdge(self, v1, v2):
if (v1 > self.nVertices - 1) or (v1 < 0) or (v2 > self.nVertices - 1) or (v2 < 0):
return False
if self.adjMatrix[v1][v2] == 0 and self.adjMatrix[v2][v1] == 0:
return
self.adjMatrix[v1][v2] = 0
self.adjMatrxi[v2][v1] = 0
def __str__(self):
return str(self.adjMatrix)
g = Graph(8)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 3)
g.addEdge(1, 4)
g.addEdge(2, 6)
g.addEdge(4, 5)
g.addEdge(5, 6)
v1 = 0
v2 = 6
result = g.getPath(v2, v1)
if result == None:
print(f"Path from {v1} -> {v2}: {result}")
else:
print(f"Path from {v1} -> {v2}: {result}")
g.bfs()
|
input_string = input("Enter the string : ")
c = input("Enter the character to be replaced : ")
r = input(f"Enter the character which replaces {c} : ")
new_list = list(input_string)
for index in range(0, len(new_list)):
if new_list[index] == c:
new_list[index] = r
result_string = ''.join(new_list)
print(result_string)
def ReplaceChar(s, c1, r1):
if (len(s) == 0):
return s
substring = ReplaceChar(s[1:], c1, r1)
if s[0] == c1:
return r1 + substring
else:
return s[0] + substring
modified_string = ReplaceChar(input_string, c, r)
print(modified_string)
|
import queue
class TreeNode:
def __init__(self, data):
self.data = data
self.children = list()
def levelWiseInput():
q = queue.Queue()
n = int(input("Enter the root node : "))
root = TreeNode(n)
q.put(root)
while not q.empty():
node = q.get()
print(f"How many children does {node.data} have ?", end = ' ')
num_children = int(input())
for i in range(0, num_children):
data = int(input("Enter the value of child: "))
new_node = TreeNode(data)
node.children.append(new_node)
q.put(new_node)
return root
def printLevelWise(root):
if root == None:
return -1
q = queue.Queue()
q.put(root)
q.put(None)
while not q.empty():
node = q.get()
if node != None:
for i in node.children:
q.put(i)
print(f"{node.data}", end = ' ')
else:
if not q.empty():
q.put(None)
print()
def printTree(root):
if root == None:
return
print(f"{root.data}", end = ': ')
for child in root.children:
print(f"{child.data}", end = ' ')
print()
for child in root.children:
printTree(child)
root = levelWiseInput()
print()
printTree(root)
print()
printLevelWise(root)
print()
|
import sys
def lcs(str1, str2, i, j, dp):
if (i > len(str1) - 1) or j > (len(str2) - 1):
return 0
# If the ith and jth elements of str1 and st2 respectively, are same
if str1[i] == str2[j]:
if dp[i+1][j+1] == None:
smallans = lcs(str1, str2, i+1, j+1, dp)
dp[i+1][j+1] = smallans
ans = 1 + smallans
else:
ans = 1 + dp[i+1][j+1]
# If the ith and jth elements of str1 and str2 respectively, aren't same
else:
if dp[i+1][j] == None:
a2 = lcs(str1, str2, i+1, j, dp)
dp[i+1][j] = a2
else:
a2 = dp[i+1][j]
if dp[i][j+1] == None:
a3 = lcs(str1, str2, i, j+1, dp)
dp[i][j+1] = a3
else:
a3 = dp[i][j+1]
ans = max(a2, a3)
return ans
string1 = input("Enter 1st string: ")
string2 = input("Enter 2nd string: ")
dp = [[None for j in range(len(string2) + 1)] for i in range(len(string1) + 1)]
result = lcs(string1, string2, 0, 0, dp)
print(f"Longest common subsequence has length: {result}")
|
def printSumToK(l, i, k, subl):
if i == len(l):
return
if k == 0:
for j in subl:
print(j, end = ' ')
print()
# including l[i]
printSumToK(l, i+1, k-l[i], subl + [l[i]])
# excluding l[i]
printSumToK(l, i+1, k, subl)
array = [int(j) for j in input("Enter an array of integers: ").split()]
total_sum = int(input("Enter the value of k: "))
printSumToK(array, 0, total_sum, [])
|
import numpy as np
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Load the dataset
titanic = sns.load_dataset('titanic')
#print(titanic.head())
#visualise the count of survivors
sns.countplot(data = titanic, x = titanic['sex']) #There is an overwhelming likelihood that you will die if you are a man.
#What are the data types?
print(titanic.dtypes)
#Drop the datasets that we do not need
titanic = titanic.drop(['deck', 'embark_town', 'alive', 'class', 'who', 'alone', 'adult_male'], axis=1)
#remove the rows with missing values
titanic = titanic.dropna(subset = ['embarked', 'age'])
#We need to get all columns to a number datatype
#Male and Female, 1 and 0 respectively
#Change the embarked cities to numbers too
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
titanic.iloc[:,2] = labelencoder.fit_transform(titanic.iloc[:,2].values)
titanic.iloc[:,7] = labelencoder.fit_transform(titanic.iloc[:,7].values)
#Split the data into independent 'x' and dependent 'y'
X = titanic.iloc[:,1:8].values
Y = titanic.iloc[:,0].values
#Create the training sets
#split the dataset into 80% training and 20% testing
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size=0.2, random_state=0)
#Scale the data (for future prediction)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.fit_transform(X_test)
#create a function with many machine learning models
def models(X_train, Y_train):
#use logistic regresion
from sklearn.linear_model import LogisticRegression
log = LogisticRegression(random_state = 0)
log.fit(X_train, Y_train)
#Use KNeighbours
from sklearn.neighbors import KNeighborsClassifier
kmn = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)
kmn.fit(X_train, Y_train)
#use SV > linear Kernel
from sklearn.svm import SVC
svc_lin = SVC(kernel = 'linear', random_state = 0)
svc_lin.fit(X_train, Y_train)
#Use SVC > RBF kernel
from sklearn.svm import SVC
svc_rbf = SVC(kernel = 'rbf', random_state = 0)
svc_rbf.fit(X_train, Y_train)
#Use GuassianNB
from sklearn.naive_bayes import GaussianNB
gauss = GaussianNB()
gauss.fit(X_train, Y_train)
#Use decision tree classifier
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)
tree.fit(X_train, Y_train)
#Use Random forest
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)
forest.fit(X_train, Y_train)
#Print the training accuracy for each model
print('[0]Logistic Regression Training Accuracy:', log.score(X_train, Y_train))
print('[1]K Neigbours Regression Training Accuracy:', kmn.score(X_train, Y_train))
print('[2]SVC Linear Kernel Training Accuracy:', svc_lin.score(X_train, Y_train))
print('[3]SVC RBF Training Accuracy:', svc_rbf.score(X_train, Y_train))
print('[4]GuassinNB Training Accuracy:', gauss.score(X_train, Y_train))
print('[5]Decision Tree Regression Training Accuracy:', tree.score(X_train, Y_train))
print('[6]Random Forest Regression Training Accuracy:', forest.score(X_train, Y_train))
return log, kmn, svc_lin, svc_rbf, gauss, tree, forest
#Return the final models
model = models(X_train, Y_train)
#Show the confusion matric and accuracy for all of the models on the test data
#This will show that Random Forest Regression Training Accuracy is the best! :)
from sklearn.metrics import confusion_matrix
for i in range(len(model)):
cm = confusion_matrix(Y_test, model[i].predict(X_test))
#Extract TN, FP, FN, TP
TN, FP, FN, TP = confusion_matrix(Y_test, model[i].predict(X_test)).ravel()
test_score = (TP + TN)/ (TP+TN+FN+FP)
print(cm)
print('Model[{}] Testing Accuracy = "{}"'.format(i, test_score))
#Get feature importance, age is the most importance for prediction, embarked is the worst
#probably what you would expect!
forest = model[6]
importances = pd.DataFrame({'feature': titanic.iloc[:,1:8].columns, 'importance': np.round(forest.feature_importances_, 3)})
importances = importances.sort_values('importance', ascending =False).set_index('feature')
print(importances)
#Visualise the importnaces
print(importances.plot.bar())
#Print the prediction of the random forest classifier
pred = model[6].predict(X_test)
print(pred)
print()
#print the actual values > What are the differences?
print(Y_test)
#Would you survive? Create a list of your values.
#In this order
#pclass int64
#sex int64
#age float64
#sibsp int64
#parch int64
#fare float64
#embarked int64
my_survival = [[3, 1, 21, 0, 0, 0, 1]]
#You need to scale it like you did with the orginal data
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
my_survival_scaled = sc.fit_transform(my_survival)
#print prediction of your survival using random forest classifier (the best model)
pred = model[6].predict(my_survival_scaled)
print(pred)
if pred == 0:
print('Oh No! You didnt make it')
else:
print('nice! You survived!')
|
from Maze import *
import random
import turtle
import unittest
class testMaze(unittest.TestCase):
"""
This class inherits from a class called TestCase which is
defined in the unittest module.
When you inherit from a class, you get all the methods that are
defined in that class for free.
Since this is a TestCase class, calling unittest.main() will automatically
run any of the funtions that start with the word 'test'
"""
def setUp(self):
"""
this will check to see if we have a maze class but as soon
as setUp is run, we will see a failure so we really don't need
to do anything here
"""
self.m=Maze()
def testMazeExists(self):
"""
this will check to see if we have a maze class but as soon
as setUp is run, we will see a failure so we really don't
need to do anything here
"""
pass
def testScreenExists(self):
assert type(self.m.s) == turtle._Screen
def testTurtleExists(self):
assert type(self.m.t) == turtle._Turtle
unittest.main()
|
class Graph:
def __init__(self):
self._adjacency_dict = {}
def add_vertex(self, value):
vertex = Vertex(value)
self._adjacency_dict[vertex] = []
return vertex
def add_edge(self, start_vertex, end_vertex, weight =1):
if start_vertex not in self._adjacency_dict:
raise KeyError('Start Vertex not in Graph')
if end_vertex not in self._adjacency_dict:
raise KeyError('End Vertex not in Graph')
edge = Edge(end_vertex, weight)
adjacencies = self._adjacency_dict[start_vertex]
adjacencies.append(edge)
def get_vertices(self):
"""
Returns all the nodes in the graph as a collection (set, list, or similar)
"""
output = []
def get_neighbor(self, vertex):
"""
Returns a collection of edges connected tothe given node
Takes in a given node
Include the weight of the connection in the returned collection"""
output = []
if vertex in self._adjacency_dict:
for neighbor in self._adjacency_dict[vertex]:
output.append([neighbor.vetex.value, neighbor.weight])
return output
def size(self):
return len(self._adjacency_dict)
class Vertex:
"""
This is equivalent to node
"""
def __init__(self, value):
self.value = value
class Edge:
def __init__(self, vertex, weight=1):
self.vertex = vertex
self.weight = weight
if __name__ == "__main":
trip = Graph
|
"""Helper functions for plotting."""
import matplotlib.pyplot as plt
import numpy as np
def plot_x_vs_y(dataset, model):
"""Plots x vs y. Do not have to change this function.
Args:
dataset(list): processed dataset, from data_tools.
model(LinearRegression): Linear regression model.
"""
plt.scatter(dataset[0], dataset[1])
x_tick = np.arange(np.min(dataset[0]), np.max(dataset[0]), 0.001)
y_tick = model.w[0] * x_tick + model.w[1]
plt.plot(x_tick, y_tick, 'r')
plt.savefig('xy_plot.png') |
#Question no 20
'''
Represent a small bilingual lexicon as a Python dictionary in the following fashion
{ "merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år" }
and use it to translate your Christmas cards from English into Swedish. That is, write a function `translate()`
that takes a list of English words and returns a list of Swedish words.
'''
#Code
def translate(s):
dic={ "merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år" }
a=(s.split(" "))
is_valid=True
l=[]
for i in a:
if i in dic:
l.append(dic[i])
else:
is_valid=False
print(i,"is not valid word")
break
if is_valid==True:
for lan in l:
print(lan,end=" ")
|
#Question no 15
'''
Write a function find_longest_word() that takes a list of words
and returns the length of the longest one.
'''
def longest(lstofwords):
listofnumber=[]
for i in lstofwords:
listofnumber.append(len(i))
listofnumber.sort()
print("Length of longest word in list is : ",listofnumber[-1])
|
"""
Reads in a .csv file and outputs each case.
To run this: `python analysis_0.py yourfile.csv`
"""
import csv
import sys
filename = sys.argv[1]
with open(filename, 'r') as f:
data = csv.reader(f)
for case in data:
print(case)
|
import string
def read_file(filename):
""" Return the contents of a file as a sring """
return open(filename).read()
if __name__ == '__main__':
s = read_file('book_section.txt')
t = s.split(' ')
for word in t:
word = word.replace(' ', '')
word = word.translate(string.maketrans("",""), string.punctuation + string.whitespace)
if word != '':
print word.lower(),
|
'''
Exercise 2.3:
Assume that we execute the following assignment statements:
width = 17
height = 12.0
delimiter = '.'
For each of the following expressions, write the value of the expression and the type (of the value of the expression).
width/2
width/2.0
height/3
1 + 2 * 5
delimiter * 5
Use the Python interpreter to check your answers.
'''
width = 17
height = 12.0
delimiter = '.'
print 'width/2 = ' + str(width/2)
print 'width/2.0 = ' + str(width/2.0)
print 'height/3 = ' + str(height/3)
print '1+2*5 = ' + str(1 + 2 * 5)
print 'delimiter*5' + str(delimiter * 5)
|
'''
Exercise 1.8 if you run a 10km race in 43 minutes and 30 seconds, what is your
average time per mile. what is your average speed in mile per hour.
There are 1.61 km in a mile.
'''
distance_in_km = 10
time_in_min = 43+(30.0/60)
distance_in_miles = distance_in_km/1.61
time_in_hrs=time_in_min/60
avg_time_per_mile=time_in_hrs/distance_in_miles
avg_speed = distance_in_miles/time_in_hrs
print("avg time per mile " + str(avg_time_per_mile))
print("avg speed " + str(avg_speed) )
print("distance in miles " + str(distance_in_miles))
|
'''
You have a histogram. Try to find size of the biggest rectangle you can build out of the histogram bars:)
'''
def largest_histogram(histogram):
maximum=max(histogram)
local_max=0
q=len(histogram)
for i in range(1,maximum+1):
macks=0
for i1 in range(0,q):
if ((histogram[i1-1]<i)and (i1>0)):
macks=0
if histogram[i1]>=i:
macks+=1
if (macks*i)>local_max:
local_max=i*macks
return local_max
|
def quickSort(A,p,r):
if(p<r and r>=0):
#partition() : use r as a pivot, modifying array as below order. and return pivot index
# (elements lower than pivot) - (pivot) - (elements higher than pivot)
q=partition(A,p,r)
#execute quickSort() recursively
quickSort(A,p,q-1)
quickSort(A,q+1,r)
def partition(A,p,r):
pivot=A[r] #use last element in A[] as pivot
# index of last element which is lower than pivot.
# setting this value as "first start index - 1" because this time no lower value found yet
lastLower=p-1
#comparing elements in A[] with pivot
for i in range(p,r,1):
if (A[i] <= pivot):
lastLower=lastLower+1
(A[lastLower], A[i])=(A[i],A[lastLower])
lastLower = lastLower + 1
(A[lastLower], A[r]) = (A[r], A[lastLower])
return lastLower
# array to be sorted
arr=[4,-99,0,-99,45,3,7,6,55,1,91838,1,1,-978]
# check before status of arr
print(arr)
last=len(arr)
quickSort(arr,0,last-1)
# check after status of arr
print(arr)
|
import stack_practice
def reverse(str):
length = len(str)
reversed = ''
for i in range(length-1,-1,-1):
ch = str[i]
reversed = reversed + ch
return reversed
str = 'abcdefg'
print(reverse(str))
#################### or ####################
def reverse_by_stack(str):
ch_stack = stack_practice.Stack()
for ch in str:
ch_stack.push(ch)
output = ''
while not ch_stack.is_empty():
output += ch_stack.pop()
return output
print(reverse_by_stack(str)) |
'''
d(n) = no. of methods representing n by only sum of 1 or 2 or 3
then
d(n) =
d(n-1) + 1 + (by adding 1)
d(n-2) + 1 + (by adding 2)
d(n-3) + 1 (by adding 3)
'''
def d(n, memo):
if n <= 0:
return 0
if n in memo:
return memo[n]
result = 0
if d(n-1, memo) > 0:
result += d(n-1, memo)
if d(n-2, memo) > 0:
result += d(n-2, memo)
if d(n-3, memo) > 0:
result += d(n-3, memo)
return result
memo = {}
memo[1] = 1
memo[2] = 2
memo[3] = 4
'''
if n == 1: # 1
return 1
if n == 2: # 1,1 / 2
return 2
if n == 3: # 1,1,1 / 1,2 / 2,1 / 3
return 4
'''
cases = int(input())
for c in range(cases):
line_input = int(input())
print(d(line_input, memo)) |
class Deque(object):
def __init__(self):
self.data = []
def push_front(self, x):
self.data.insert(0, x)
def push_back(self, x):
self.data.append(x)
def pop_front(self):
if self.empty() == 1:
return -1
else:
return self.data.pop(0)
def pop_back(self):
if self.empty() == 1:
return -1
else:
return self.data.pop()
def size(self):
return len(self.data)
def empty(self):
if len(self.data) > 0:
return 0
else:
return 1
def front(self):
if self.empty() == 1:
return -1
else:
return self.data[0]
def back(self):
if self.empty() == 1:
return -1
else:
return self.data[len(self.data) - 1]
cases = int(input())
dq = Deque()
for c in range(cases):
line_input = input()
line_input = line_input.split(' ')
if line_input[0] == 'push_front':
x = int(line_input[1])
dq.push_front(x)
elif line_input[0] == 'push_back':
x = int(line_input[1])
dq.push_back(x)
elif line_input[0] == 'pop_front':
print(dq.pop_front())
elif line_input[0] == 'pop_back':
print(dq.pop_back())
elif line_input[0] == 'size':
print(dq.size())
elif line_input[0] == 'empty':
print(dq.empty())
elif line_input[0] == 'front':
print(dq.front())
elif line_input[0] == 'back':
print(dq.back())
else:
continue
|
def is_arithmetic_num(num):
result = True
num_arr = []
while num != 0:
num_arr.append(num % 10)
num //= 10
if len(num_arr) <= 2:
result = True
return result
else:
gap = num_arr[0] - num_arr[1]
for i in range(1, len(num_arr)-1):
if (num_arr[i] - num_arr[i+1]) != gap:
result = False
break
return result
n = int(input())
count = 0
for x in range(1, n + 1):
if is_arithmetic_num(x) is True:
count += 1
print(count)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.