Refactoring from DynamicVector to a different data structure?

I'm currently teaching myself Mojo by porting the solutions to Codewars katas in Python over to the new language. The "safecracker" problem asks you to write a function that returns a tuple of three integers. My Python solution used the tuple type. My Mojo solution uses DynamicVector in place of tuple. There must be a better way to do it than that, surely? I'm having difficulty with the official docs (skill issue on my part). Suggestions welcome. Help appreciated.
from utils.vector import DynamicVector

fn safecracker(start:Int, incs:DynamicVector[Int]) -> DynamicVector[Int]:
var vec = DynamicVector[Int](3)
vec.push_back((start - incs[0]) % 100)
vec.push_back((vec[0] + incs[1]) % 100)
vec.push_back((vec[1] - incs[2]) % 100)
return vec

fn main():
var vec0 = DynamicVector[Int](3)
vec0.push_back(54)
vec0.push_back(48)
vec0.push_back(77)
let result = safecracker(96, vec0)
print(result[0], result[1], result[2])
from utils.vector import DynamicVector

fn safecracker(start:Int, incs:DynamicVector[Int]) -> DynamicVector[Int]:
var vec = DynamicVector[Int](3)
vec.push_back((start - incs[0]) % 100)
vec.push_back((vec[0] + incs[1]) % 100)
vec.push_back((vec[1] - incs[2]) % 100)
return vec

fn main():
var vec0 = DynamicVector[Int](3)
vec0.push_back(54)
vec0.push_back(48)
vec0.push_back(77)
let result = safecracker(96, vec0)
print(result[0], result[1], result[2])
2 Replies
Stole
Stole14mo ago
DynamicVector's really for containers that change size a lot. Mojo has a Tuple type which has similar functionality to Python's tuple, and you can see it here: https://docs.modular.com/mojo/stdlib/builtin/tuple.html. However, I think that StaticTuple (https://docs.modular.com/mojo/stdlib/utils/static_tuple.html) actually could be better suited here, since it's for containers whose sizes don't change, and with homogenous types (Tuple can handle different types, which we don't need, and makes it a little more annoying to access elements). Something like this is likely what you're looking for.
from utils.static_tuple import StaticTuple
alias Tuple3I = StaticTuple[3, Int]

fn safecracker(start: Int, incs: Tuple3I) -> Tuple3I:
var vec = Tuple3I()
vec[0] = (start - incs[0]) % 100
vec[1] = (vec[0] + incs[1]) % 100
vec[2] = (vec[1] - incs[2]) % 100
return vec

fn main():
let vec0 = Tuple3I(54, 48, 77)
let result = safecracker(96, vec0)
print(result[0], result[1], result[2])
from utils.static_tuple import StaticTuple
alias Tuple3I = StaticTuple[3, Int]

fn safecracker(start: Int, incs: Tuple3I) -> Tuple3I:
var vec = Tuple3I()
vec[0] = (start - incs[0]) % 100
vec[1] = (vec[0] + incs[1]) % 100
vec[2] = (vec[1] - incs[2]) % 100
return vec

fn main():
let vec0 = Tuple3I(54, 48, 77)
let result = safecracker(96, vec0)
print(result[0], result[1], result[2])
Sammi Turner
Sammi TurnerOP14mo ago
Perfect answer. Thank you!
Want results from more Discord servers?
Add your server