Speed/pace calculation code; keep getting invalid syntax. Very new; what am I doing wrong? - syntax

def calculation(minutes, seconds, miles):
pace = (int(minutes) + (int(seconds)/60)/miles)
speed = (float(miles)/(int(minutes) + (int(seconds)/60)
minutes = raw_input("Minutes ==> ")
seconds = raw_input("Seconds ==> ")
miles = raw_input("Miles ==>" )
I'm attempting to do an input that is supposed to calculate the pace and speed of user-inputted variables but I keep getting syntax errors starting from the fourth line down. I'm very new to this for the record so it's probably something stupid but any help is appreciated!

Related

Currently trying to script a game and I don't understand how to debug this section of coding

I'm following a youtube tutorial on scripting to create a game on roblox and whilst following it, "Status", the variable I use to identify a value decides to stop working (line39). My output box says the following:
21:16:36.197 - sword game.rbxl auto-recovery file was created
21:16:36.715 - ServerScriptService.MainScript:39: Expected ']' (to close '[' at line 37), got 'Status'
21:16:38.617 - ScriptNavigationHandler : No script currently available.
I haven't learned much about debugging code but if someone can shine some light on what is wrong that would greatly help me on my conquest to learn scripting during the fight against the invisible enemy.
-- Define varibles
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local MapsFolder = ServerStorage:WaitForChild("Maps")
local Status = ReplicatedStorage:WaitForChild("Status")
local GameLength = 60
--Game loop
while true do
Status.Value = "Waiting for enoughplayers"
repeat wait(1) until game.Players.NumPlayers >=2
Status.Value = "Intermission"
wait(8)
local plrs = {}
for i, player in pairs(game.Players:GetPlayers()) do
if player then
table.insert(plrs,player) --Add each player into plrs table
end
end
wait(2)
local AvaliableMaps =MapsFolder:GetChildren()
local ChosenMap = AvaliableMaps[math.random(1,#AvailableMaps)
Status.Value = ChosenMap.Name "Chosen"
local ClonedMap = ChosenMap:Clone()
ClonedMap.Parent = workspace
-- Teleport players to the map
local SpawnPoints = ClonedMap:FindFirstChild("SpawnPoints")
if not SpawnPoints then
print("SpawnPoints not found!")
end
local AvailableSpawnPoints = SpawnPoints:GetChildren()
for i, player in pairs(plrs) do
if player then
character = player.Character
if character then
-- Teleport them
character:FindFirstChild("HumanoidRootPart").CFrame = AvailableSpawnPoints[1].CFrame
table.remove(AvailableSpawnPoints,1)
-- Give Sword
local Sword = ServerStorage.Sword:Clone()
Sword.Parent = player.Backpack
local GameTag = Instance.new("BoolValue")
GameTag.Name = "GameTag"
GameTag.Parent = player.Character
else
-- There is no character
if not player then
table.remove(plrs,i)
end
end
end
end
end
In
local ChosenMap = AvaliableMaps[math.random(1,#AvailableMaps)
you are missing the closing square bracket.
Night94 has pointed out the correct fix for your broken code, but since your question is about learning to debug, I'll try to help you understand your error messages.
21:16:36.715 - ServerScriptService.MainScript:39: Expected ']' (to close '[' at line 37), got 'Status'
Let's break this down piece by piece :
ServerScriptStorage.MainScript:39 this tells us where the file is, and on what line the error appeared.
So let's look at line 39 (through 41) you see :
local ChosenMap = AvaliableMaps[math.random(1,#AvailableMaps)
Status.Value = ChosenMap.Name "Chosen"
Next we have : Expected ']' (to close '[' at line 37), got 'Status'
This means that at some point, the code was expecting a square bracket to close the one that was opened at 37 : AvaliableMaps[, but instead it found the next line of code Status
So with these pieces of information, you should have all the pieces to understand what went wrong: A square bracket was opened, but never closed. It should go somewhere before the next line of code.
local ChosenMap = AvaliableMaps[math.random(1,#AvailableMaps)]

How to improve running time of my binary search code in peripherical parts?

I am studying for this great Coursera course https://www.coursera.org/learn/algorithmic-toolbox . On the fourth week, we have an assignment related to binary trees.
I think I did a good job. I created a binary search code that solves this problem using recursion in Python3. That's my code:
#python3
data_in_sequence = list(map(int,(input().split())))
data_in_keys = list(map(int,(input()).split()))
original_array = data_in_sequence[1:]
data_in_sequence = data_in_sequence[1:]
data_in_keys = data_in_keys[1:]
def binary_search(data_in_sequence,target):
answer = 0
sub_array = data_in_sequence
#print("sub_array",sub_array)
if not sub_array:
# print("sub_array",sub_array)
answer = -1
return answer
#print("target",target)
mid_point_index = (len(sub_array)//2)
#print("mid_point", sub_array[mid_point_index])
beg_point_index = 0
#print("beg_point_index",beg_point_index)
end_point_index = len(sub_array)-1
#print("end_point_index",end_point_index)
if sub_array[mid_point_index]==target:
#print ("final midpoint, ", sub_array[mid_point_index])
#print ("original_array",original_array)
#print("sub_array[mid_point_index]",sub_array[mid_point_index])
#print ("answer",answer)
answer = original_array.index(sub_array[mid_point_index])
return answer
elif target>sub_array[mid_point_index]:
#print("target num higher than current midpoint")
beg_point_index = mid_point_index+1
sub_array=sub_array[beg_point_index:]
end_point_index = len(sub_array)-1
#print("sub_array",sub_array)
return binary_search(sub_array,target)
elif target<sub_array[mid_point_index]:
#print("target num smaller than current midpoint")
sub_array = sub_array[:mid_point_index]
return binary_search(sub_array,target)
else:
return None
def bin_search_over_seq(data_in_sequence,data_in_keys):
final_output = ""
for key in data_in_keys:
final_output = final_output + " " + str(binary_search(data_in_sequence,key))
return final_output
print (bin_search_over_seq(data_in_sequence,data_in_keys))
I usually get the correct output. For instance, if I input:
5 1 5 8 12 13
5 8 1 23 1 11
I get the correct indexes of the sequences or (-1) if the term is not in sequence (first line):
2 0 -1 0 -1
However, my code does not pass on the expected running time.
Failed case #4/22: time limit exceeded (Time used: 13.47/10.00, memory used: 36696064/536870912.)
I think this happens not due to the implementation of my binary search (I think it is right). Actually, I think this happens due to some inneficieny in a peripheral part of the code. Like the way I am managing to output the final answer. However, the way I am presenting the final answer does not seem to be really "heavy"... I am lost.
Am I not seeing something? Is there another inefficiency I am not seeing? How can I solve this? Just trying to present the final result in a faster way?

Working with very big data faster in Matlab?

I have to deal with very big data (Point clouds generally more than 30 000 000 points) using Matlab. I can read ascii data using textscan function. After reading, I need to detect invalid data (points with 0,0,0 coordinates) and then I need to do some mathematical operations on each point or each line in the data. In my way, first I read data with textscan and then I assign this data to a matrix. Secondly, I use for loops for detecting invalid points and doing some mathematical operations on each point or line in the data. A sample of my code is shown as below. According to profile tool of Matlab textscan takes 37% and line
transformed_list((i:i),(1:4)) = coordinate_list((i:i),(1:4))*t_matrix;
takes 35% of all computation time.
I tried it with another point cloud (stores around 5 500 000) and profile tool reported same results. Is there a way of avoiding for loops, or is there another way of speeding up this computation?
fileID = fopen('C:\Users\Mustafa\Desktop\ptx_all_data\dede5.ptx');
original_data = textscan(fileID,'%f %f %f %f %f %f %f', 'delimiter',' ');
fclose(fileID);
column = original_data{1}(1);
row = original_data{1}(2);
t_matrix = [original_data{1}(7) original_data{2}(7) original_data{3}(7) original_data{4}(7)
original_data{1}(8) original_data{2}(8) original_data{3}(8) original_data{4}(8)
original_data{1}(9) original_data{2}(9) original_data{3}(9) original_data{4}(9)
original_data{1}(10) original_data{2}(10) original_data{3}(10) original_data{4}(10)];
coordinate_list(:,1) = original_data{1}(11:length(original_data{1}));
coordinate_list(:,2) = original_data{2}(11:length(original_data{2}));
coordinate_list(:,3) = original_data{3}(11:length(original_data{3}));
coordinate_list(:,4) = 0;
coordinate_list(:,5) = original_data{4}(11:length(original_data{4}));
transformed_list = zeros(length(coordinate_list),5);
for i = 1:length(coordinate_list)
if coordinate_list(i,1) == 0 && coordinate_list(i,2) == 0 && coordinate_list(i,3) == 0
transformed_list(i,:) = NaN;
else
%transformed_list(i,:) = coordinate_list(i,:)*t_matrix;
transformed_list((i:i),(1:4)) = coordinate_list((i:i),(1:4))*t_matrix;
transformed_list(i,5) = coordinate_list(i,5);
end
%i
end
Thanks in advance
for loops with conditional statements like those will take ages to run. But what Matlab lacks in loop speed it makes up with vectorization and indexing.
Let's try some logical indexing like this to solve the first step:
coordinate_list(coordinate_list(:,1) == 0 .* ...
coordinate_list(:,2) == 0 .* ...
coordinate_list(:,3) == 0)=nan;
And then vectorize the second statement:
transformed_list(:,(1:4)) = coordinate_list(:,(1:4))*t_matrix;
As EBH mentioned above this might be a bit heavy on your RAM. If it's more than your computer can handle asks yourself if the coordinates really have to be doubles, maybe single precision will do. If that still doesn't do, try slicing the vector and performing the operation in parts.
Small example to give you an idea because I had a 2million element point cloud around here:
In R2015a
transformed_list = zeros(length(coordinate_list),5);
tic
for i = 1:length(coordinate_list)
if coordinate_list(i,1) == 0 && coordinate_list(i,2) == 0 && coordinate_list(i,3) == 0
transformed_list(i,:) = NaN;
else
%transformed_list(i,:) = coordinate_list(i,:)*t_matrix;
transformed_list((i:i),(1:3)) = coordinate_list((i:i),(1:3))*t_matrix;
transformed_list(i,5) = 1;
end
%i
end
toc
Returns Elapsed time is 10.928142 seconds.
transformed_list=coordinate_list;
tic
coordinate_list(coordinate_list(:,1) == 0 .* ...
coordinate_list(:,2) == 0 .* ...
coordinate_list(:,3) == 0)=nan;
transformed_list(:,(1:3)) = coordinate_list(:,(1:3))*t_matrix;
toc
Returns Elapsed time is 0.101696 seconds.
Rather than read the whole file, you'd be better off using a loop with
fscanf(fileID, '%f', 7)
and processing input as you read it.

why doesn't this ruby code work

here's a practice question - Write a method that will take in a number of minutes, and returns a string that formats the number into hours:minutes.
def time_conversion(minutes)
hours = minutes / 60
mins = minutes % 60
time = hours + ":" + mins
return time
end
the following are tests to see if this works. if they return true then it means my code works correctly.
puts('time_conversion(15) == "0:15": ' + (time_conversion(15) == '0:15').to_s)
puts('time_conversion(150) == "2:30": ' + (time_conversion(150) == '2:30').to_s)
puts('time_conversion(360) == "6:00": ' + (time_conversion(360) == '6:00').to_s)
sometimes i get true for the first two tests but the third test line shows false even though the code will print out exactly the required.
other times I get the following error:
String can't be coerced into Fixnum (repl):4:in +' (repl):4:intime_conversion' (repl):1:in `initialize'
please assist.
The error mainly refers to this line
time = hours + ":" + mins
hours & mins are Fixnum, whereas ":" is String
As the error message indicates, "String can't be coerced into Fixnum".
You could either do time = hours.to_s + ":" + minutes.to_s or time = "#{hours}:#{minutes}".
Because Fixnum#+ takes a Numeral argument, not a String.

Testing time critical code

I've written a feature for my library Rubikon that displays a throbber (a spinning — as you may have seen in other console apps) as long as some other code is running.
To test this feature I capture the output of the throbber in a StringIO and compare it with the expected value. As the throbber is only displayed as long as the other code is running the content of the IO gets longer when the code runs longer. In my tests I do a simple sleep 1 and should have a constant 1 second delay. This works most of the time, but sometimes (apparently due to external factors like heavy load on the CPU) it fails, because the code doesn't run for 1 second, but for a bit more, so that the throbber prints a few additional characters.
My question is: Is there any possibility to test such time critical features in Ruby?
From your github repository, I found this test for the Throbber class:
should 'work correctly' do
ostream = StringIO.new
thread = Thread.new { sleep 1 }
throbber = Throbber.new(ostream, thread)
thread.join
throbber.join
assert_equal " \b-\b\\\b|\b/\b", ostream.string
end
I'll assume that a throbber iterates over ['-', '\', '|', '/'], backspacing before each write, once per second. Consider the following test:
should 'work correctly' do
ostream = StringIO.new
started_at = Time.now
ended_at = nil
thread = Thread.new { sleep 1; ended_at = Time.now }
throbber = Throbber.new(ostream, thread)
thread.join
throbber.join
duration = ended_at - started_at
iterated_chars = " -\\|/"
expected = ""
if duration >= 1
# After n seconds we should have n copies of " -\\|/", excluding \b for now
expected << iterated_chars * duration.to_i
end
# Next append the characters we'd get from working for fractions of a second:
remainder = duration - duration.to_i
expected << iterated_chars[0..((iterated_chars.length*remainder).to_i)] if remainder > 0.0
expected = expected.split('').join("\b") + "\b"
assert_equal expected, ostream.string
end
The last assignment of expected is a bit unpleasant, but I made the assumption that the throbber would write character/backspace pairs atomically. If this is not true, you should be able to insert the \b escape sequence into the iterated_chars string and remove the last assignment entirely.
This question is similar (I think, altough I'm not completely sure) to this one:
Only real time operating system can
give you such precision. You can
assume Thread.Sleep has a precision of
about 20 ms so you could, in theory
sleep until the desired time - the
actual time is about 20 ms and THEN
spin for 20 ms but you'll have to
waste those 20 ms. And even that
doesn't guarantee that you'll get real
time results, the scheduler might just
take your thread out just when it was
about to execute the RELEVANT part
(just after spinning)
The problem is not rubby (possibly, I'm no expert in ruby), the problem is the real time capabilities of your operating system.

Resources