Recursively counting the number of characters in a string. (Ruby) - ruby

I need to write a recursive function that utilizes just two string methods, .empty? and .chop.
No, I can't use .length (Can you tell it's homework yet?)
So far I'm stuck on writing the function itself, I passed it the string, but I am unsure on how to recursively go through the characters with the .chop string method. Would I just have a counter? Syntax for this thing seems tricky to me.
def stringLength(string)
if string.empty?
return 0
else
.....
end
end
I wish I could put more down, but this is what I'm stuck at.

return 1 + stringLength(string.chop)
Thats your missing line. Here is an example of how this will work:
stringLength("Hello") = 1 + stringLength("Hell")
stringLength("Hell") = 1 + stringLength("Hel")
stringLength("Hel") = 1 + stringLength("He")
stringLength("He") = 1 + stringLength("H")
stringLength("H") = 1 + stringLength("")
stringLength("") = 0

Related

'Return' outside of function

def suspect_dict():
dict = pd.read_csv("suspectdict.csv", squeeze=True)
pattern = '|'.join(dict)
result = np.where(news_df["headline"].str.contains(pattern, na=False),1, 0)
for index, value in enumerate(result):
return {value}
I am trying to return 1 and 0 if words in "suspectdict" exists in "news_df".
Code works for
for index, value in enumerate(result):
print(f"{value}")
example of output:
0
1
0
1
1
When using return I got Syntax error: 'return' outside function
How do I fix this?
As the error says, your return is outside a function. Return should be used within a scope of a function, in your case, on suspect_dict() function.
You could either just loop the result and print it, without returning anything, also, you don't need to use enumerate as you're not dealing with indexes:
def suspect_dict():
dict = pd.read_csv("suspectdict.csv", squeeze=True)
pattern = '|'.join(dict)
result = np.where(news_df["headline"].str.contains(pattern, na=False),1, 0)
for value in result:
print(value)
But if you need to return the result, you could just use return result inside the function:
def suspect_dict():
dict = pd.read_csv("suspectdict.csv", squeeze=True)
pattern = '|'.join(dict)
result = np.where(news_df["headline"].str.contains(pattern,na=False),1,0)
return result
Note that python uses indentation to understand where a block of code begins and ends, so make sure that all codes that might belong to the function are well indented.

converting C to Lingo

does anyone here knows how to convert this expression below to lingo:
for(var channel=1;channel<30;channel+=3)
there is already sample below on how to use for statement to repeat with, my problem is i dont know how to use channel+=3 in lingo statement since they only provided channel++.
//Lingo
on puppetize
repeat with channel = 1 to 30
_movie.puppetSprite(channel, TRUE)
end repeat
end puppetize
// Javascript
function puppetize()
{
for(var channel=1;channel<30;channel++)
{
_movie.puppetSprite(channel, true);
}
}
hope you could help me with this. thanks.
As the Lingo reference says about the repeat keyword having no incrementing syntax, you are indeed adding 1 to channel yourself. But did you try using a more basic syntax c = c + 1 instead of c++ or c += 1? Also, in Lingo, you would be adding only 2, because the repeat loop is already adding 1 on it's own. Please see below.
//Lingo
on puppetize
repeat with channel = 1 to 30
_movie.puppetSprite(channel, TRUE)
channel = channel + 2 <---------------------my change here.
end repeat
end puppetize

How do I implement atof (ascii to float) method in ruby?

I am trying to make an RPN calculator. I have to implement my own .to_i and .to_f method. I cannot use send, eval, Float(str) or String(str) method. The assignment is done, but I still want to know how to implement it.
The input: atof("255.25") as string type
Output: 255.55 as float type
Here is my code for atoi
ASCII_NUM_START = 48 # start of ascii code for 0
def ascii_to_i(int_as_str)
array_ascii = int_as_str.bytes
converted_arr = array_ascii.map {|ascii| ascii - ASCII_NUM_START }
converted_arr.inject { |sum, n| sum * 10 + n }
end
def ascii_to_f(float_as_str)
???
end
I got it working doing the following (and utilizing your ascii_to_i function).
ASCII_NUM_START = 48 # start of ascii code for 0
def ascii_to_i(int_as_str)
array_ascii = int_as_str.bytes
converted_arr = array_ascii.map {|ascii| ascii - ASCII_NUM_START }
converted_arr.inject { |sum, n| sum * 10 + n }
end
def ascii_to_f(float_as_str)
int_split = float_as_str.split(".")
results = []
int_split.each { |val| results << ascii_to_i(val) }
results[0] + (results[1] / (10.0 ** int_split.last.length))
end
I can see you have made a reasonable effort at ascii_to_i.
The code for ascii_to_f can be similar, and in addition you will need to divide the result by the number of decimal places that you have processed.
Probably the easiest adaptation is:
find the position of the . character (ASCII code 46) in the String, save that as a variable
remove the . character (ASCII code 46) from your array of bytes
calculate the Integer value from the array of bytes as before
divide by 10.0 (must be a Float) to the power of (the length of the remaining array minus the position you found the . in).
I am not giving code, because it is an assignment. See if you can figure out the correct syntax, looking at documentation for the Array class for finding the position of a specific value, for deleting a specific value, and for getting length of the array.

Returning multiple ints and passing them as multiple arguements in Lua

I have a function that takes a variable amount of ints as arguments.
thisFunction(1,1,1,2,2,2,2,3,4,4,7,4,2)
this function was given in a framework and I'd rather not change the code of the function or the .lua it is from. So I want a function that repeats a number for me a certain amount of times so this is less repetitive. Something that could work like this and achieve what was done above
thisFunction(repeatNum(1,3),repeatNum(2,4),3,repeatNum(4,2),7,4,2)
is this possible in Lua? I'm even comfortable with something like this:
thisFunction(repeatNum(1,3,2,4,3,1,4,2,7,1,4,1,2,1))
I think you're stuck with something along the lines of your second proposed solution, i.e.
thisFunction(repeatNum(1,3,2,4,3,1,4,2,7,1,4,1,2,1))
because if you use a function that returns multiple values in the middle of a list, it's adjusted so that it only returns one value. However, at the end of a list, the function does not have its return values adjusted.
You can code repeatNum as follows. It's not optimized and there's no error-checking. This works in Lua 5.1. If you're using 5.2, you'll need to make adjustments.
function repeatNum(...)
local results = {}
local n = #{...}
for i = 1,n,2 do
local val = select(i, ...)
local reps = select(i+1, ...)
for j = 1,reps do
table.insert(results, val)
end
end
return unpack(results)
end
I don't have 5.2 installed on this computer, but I believe the only change you need is to replace unpack with table.unpack.
I realise this question has been answered, but I wondered from a readability point of view if using tables to mark the repeats would be clearer, of course it's probably far less efficient.
function repeatnum(...)
local i = 0
local t = {...}
local tblO = {}
for j,v in ipairs(t) do
if type(v) == 'table' then
for k = 1,v[2] do
i = i + 1
tblO[i] = v[1]
end
else
i = i + 1
tblO[i] = v
end
end
return unpack(tblO)
end
print(repeatnum({1,3},{2,4},3,{4,2},7,4,2))

how does Enumerable#cycle work? (ruby)

looper = (0..3).cycle
20.times { puts looper.next }
can I somehow find the next of 3? I mean if I can get .next of any particular element at any given time. Not just display loop that starts with the first element.
UPDATE
Of course I went though ruby doc before posting my question. But I did not find answer there ...
UPDATE2
input
looper = (0..max_cycle).cycle
max_cycle = variable that can be different every time the script runs
looper = variable that is always from interval (0..max_cycle) but the current value when the script starts could be any. It is based on Time.now.hour
output
I want to know .next value of looper at any time during the running time of the script
Your question is not very clear. Maybe you want something like this?
(current_value + 1) % (max_cycle + 1)
If, for example, max_cycle = 3 you will have the following output:
current_value returns
0 1
1 2
2 3
3 0
http://ruby-doc.org/core-1.9/classes/Enumerable.html#M003074

Resources