I have some code that effectively replaces this excel spreadsheet where I am trying to find the difference between two times. Depending on the state of the second column of that value I want to segregate this into two columns.
I converted the data in the first two columns into a list of lists in the form
[...[2.96738, 0], [3.91727, 1], [3.9729, 0], [4.88419, 1], [4.93686, 0], [5.86113, 1], [5.91125, 0]...]
Running my code:
def Delta_Time_One_State(CleanState):
for counter, value in enumerate(CleanState[1:]):
DeltaT = value[0] - CleanState[counter][0]
Lgt_cut_Time = []
Lgt_Uncut_Time = []
if value[1] == 0:
Lgt_cut_Time.append([value[0] + DeltaT / 2, DeltaT])
else:
Lgt_Uncut_Time.append([value[0] + DeltaT / 2, DeltaT])
clean_state_A = [[0.0, 0], [0.03253, 1], [0.08479, 0], [0.98748, 1], [1.03717, 0], ... [483.8888, 0], [484.6563, 1]]
Delta_Time_One_State(clean_state_A)
gives me
Lgt_Uncut_Time = [[485.04004999999995, 0.7674999999999841]]
Lgt_cut_Time = []
Which can't be right because the for loop runs through almost all of clean_state_A. Since every loop passes through the if statement something appears to be wrong with the .append function but I can't tell what.
Every loop you are redefining the two lists. Move them outside of the for loop so you're appending to the same list every iteration.
def Delta_Time_One_State(CleanState):
Lgt_cut_Time = []
Lgt_Uncut_Time = []
for counter, value in enumerate(CleanState[1:]):
DeltaT = value[0] - CleanState[counter][0]
calculated_data = [value[0] + DeltaT / 2, DeltaT]
if value[1] == 0:
Lgt_cut_Time.append(calculated_data)
else:
Lgt_Uncut_Time.append(calculated_data)
You are recreating the Lgt_cut_Time and Lgt_Uncut_Time lists every loop.
def Delta_Time_One_State(CleanState):
for counter, value in enumerate(CleanState[1:]):
DeltaT = value[0] - CleanState[counter][0]
Lgt_cut_Time = []
Lgt_Uncut_Time = []
if value[1] == 0:
Lgt_cut_Time.append([value[0] + DeltaT / 2, DeltaT])
else:
Lgt_Uncut_Time.append([value[0] + DeltaT / 2, DeltaT])
Just move them outside of the loop so that they accumulate the results instead of replacing them on every loop.
def Delta_Time_One_State(CleanState):
Lgt_cut_Time = []
Lgt_Uncut_Time = []
for counter, value in enumerate(CleanState[1:]):
DeltaT = value[0] - CleanState[counter][0]
if value[1] == 0:
Lgt_cut_Time.append([value[0] + DeltaT / 2, DeltaT])
else:
Lgt_Uncut_Time.append([value[0] + DeltaT / 2, DeltaT])
Related
The code works perfectly fine for the first test case but gives wrong answer for the second one. Why is that?
arr = [1,2,3,4,5,6,7]
arr2 = [-1,-100,3,99]
def reverse(array, start, end):
while start < end:
array[start], array[end] = array[end], array[start]
start += 1
end -= 1
return array
def rotate(array, k):
reverse(array, 0, k)
reverse(array, k+1, len(array)-1)
reverse(array, 0, len(array)-1)
return array
print(rotate(arr, 3)) # output: [5, 6, 7, 1, 2, 3, 4]
# print(reverse(arr, 2, 4))
rotate(arr2, 2)
print(arr2) # output: [99, -1, -100, 3] (should be [3, 99, -1, -100])
Your existing logic does the following -
Move k + 1 item from front of the list to the back of the list.
But the solution needs to move k elements from back of the list to the front. Or another way to think is move len(array) - k element from front to the back.
To do so, two changes required in the rotate() -
Update k to len(array) - k
Change your logic to move k instead of k + 1 element from front to back
So, your rotate() needs to be changed to following -
def rotate(array, k):
k = len(array) - k
reverse(array, 0, k-1)
reverse(array, k, len(array)-1)
reverse(array, 0, len(array)-1)
return array
I think there are better ways to solve this but with your logic this should solve the problem.
My implementation of BFS in Python to solve the 8-puzzle is taking at least 21 minutes to find a solution. How can I improve my code in order to achieve a better time?
The way I've implemented is very inefficient. I'd like to know any advice about how can I improve it in a way to solve in an acceptable time.
class Node():
def __init__(self, board=[]):
self.board=board
self.adjacency_list=[]
def get_adjacency_list(self):
return self.adjacency_list
def set_adjacency_list(self, adjacency_list):
self.adjacency_list = adjacency_list
def add_item_to_adjacency_list(self, item):
self.adjacency_list.append(item)
def generate_adjacency_list(self):
'''
Generates the adjancency list
from a given puzzle 8's board.
'''
adj_lists = []
empty_cell = 0
row_empty_cell = col_empty_cell = 0
tmp_array = None
for array in self.board:
if empty_cell in array:
tmp_array = array
break
row_empty_cell = self.board.index(tmp_array)
col_empty_cell = tmp_array.index(empty_cell)
left = (row_empty_cell, col_empty_cell - 1)
right = (row_empty_cell, col_empty_cell + 1)
up = (row_empty_cell - 1, col_empty_cell)
down = (row_empty_cell + 1, col_empty_cell)
max_bound = 3
for direction in [left, up, right, down]:
(row, col) = direction
if row >= 0 and row < max_bound and col >= 0 and col < max_bound:
adj_list = [r[:] for r in self.board]
adj_list[row_empty_cell][col_empty_cell] = adj_list[row][col]
adj_list[row][col] = empty_cell
self.add_item_to_adjacency_list(Node(adj_list))
def bfs(root_node, goal_node):
'''
Implementation of the Breadth
First Search algorithm.
The problem to be solved by this
algorithm is the Puzzle 8 game.
input: root -- the root node where
the search begins.
goal_node -- The objective to reach.
return:
(path, node) -- A tuple with a
dictionary path whose key node
gives the path backwards to the
objective node.
'''
frontier = [root_node]
path = {root_node : None} # The path where a node came from
level = {root_node : 0}
boards = [root_node.get_board()] # List of boards to check a board was already generated
i = 1
while frontier:
next_frontier = []
for node_parent in frontier:
if node_parent.get_board() == goal_node.get_board():
return (path, node_parent)
node_parent.generate_adjacency_list()
for children in node_parent.get_adjacency_list():
if children.get_board() not in boards:
boards.append(children.get_board())
next_frontier.append(children)
level[children] = i
path[children] = node_parent
frontier = next_frontier
print("Level ", i)
print("Number of nodes ", len(frontier))
i += 1
return (path, root_node)
root_node = Node([[2, 6, 0],
[5, 7, 3],
[8, 1, 4]])
goal_node = Node([[1, 2, 3],
[4, 5, 6],
[7, 8, 0]])
import time
start = time.time()
path, node = bfs(root_node, goal_node)
end = time.time()
print(end - start)
I think that the problem is in this line:
if children.get_board() not in boards:
This is a linear search, try to change this to binary search.
Use a heuristic, like A*. This is known to work well and there are many guides on it.
I am trying to define a function, median, that consumes a list of numbers and returns the median number from the list. If the list is empty, then I want to return None. To calculate the median, I need to find the middle index of the list after it has been sorted. Do not use a built-in function.
SURVEY_RESULTS = [1.5, 1, 2, 1.5, 2, 3, 1, 1, 1, 2]
def median(SURVEY_RESULTS):
length = 0
order = sorted(SURVEY_RESULTS)
I'm not sure how to use indexing to now determine the median.
Here is my implementation:
def QuickSort(myList,start,end):
if start < end:
i,j = start,end
base = myList[i]
while i < j:
while (i < j) and (myList[j] >= base):
j = j - 1
myList[i] = myList[j]
while (i < j) and (myList[i] <= base):
i = i + 1
myList[j] = myList[i]
myList[i] = base
QuickSort(myList, start, i - 1)
QuickSort(myList, j + 1, end)
return myList
def median(l):
half = len(l) // 2
return (l[half] + l[~half])/2 # Use reverse index
SURVEY_RESULTS = [1.5, 1, 2, 1.5, 2, 3, 1, 1, 1, 2]
# Sort first
QuickSort(SURVEY_RESULTS, 0, len(SURVEY_RESULTS)-1)
result = median(SURVEY_RESULTS)
print (result)
I'm new to python3 I'm trying to write a code that takes a matrix as its argument and computes and prints the QR factorization using the modified Gram-Schmidt algorithm. I'm trying to use nested for loops for the code and not use NUMPY at all. I have attached my code below any help would be greatly appreciated. Thank you in advance.
def twoNorm(vector):
'''
twoNorm takes a vector as it's argument. It then computes the sum of
the squares of each element of the vector. It then returns the square
root of this sum.
'''
# This variable will keep track of the validity of our input.
inputStatus = True
# This for loop will check each element of the vector to see if it's a number.
for i in range(len(vector01)):
if ((type(vector01[i]) != int) and (type(vector01[i]) != float) and (type(vector01[i]) != complex)):
inputStatus = False
print("Invalid Input")
# If the input is valid the function continues to compute the 2-norm
if inputStatus == True:
result = 0
# This for loop will compute the sum of the squares of the elements of the vector.
for i in range(len(vector01)):
result = result + (vector01[i]**2)
result = result**(1/2)
return result
def QR(matrix):
r[i][i] = twoNorm(vector01)
return [vector01 * (1/(twoNorm(vector01)) for i in matrix]
for j in range(len(matrix)):
r[i][j] = q[i] * vector02[i]
vector02 = vector02[i] - (r[i][j] * q[i])
matrix = [[1, 2], [0, 1], [1, 0]]
vector01 = [1, 0, 1]
vector02 = [2, 1, 0]
I want to get dictionary with 'bigram: frequency' where bigram = str[i] + str[i + 1]. So this is my solution:
f_dict = {}
for i in range(0, len(string) - 1, step):
if string[i] + string[i + 1] in f_dict:
f_dict[string[i] + string[i + 1]] += 1
else:
f_dict[string[i] + string[i + 1]] = 1
Is it possible to write this with dict comprehensions in one line, or is there a better solution (within the meaning of performance)?
You can do as follows :
s = 'abaabaab' # Your string
# Dictionary comprehension
dic = {k : s.count(k) for k in {s[i]+s[i+1] for i in range(len(s)-1)}}
Result :
In[2]: dic
Out[3]: {'aa': 2, 'ab': 3, 'ba': 2}