【问题标题】:Function that sets an exponent in string in Julia在 Julia 中设置字符串中的指数的函数
【发布时间】:2022-01-23 19:56:17
【问题描述】:

我正在寻找执行以下渲染的函数:

f("2") = 2²
f("15") = 2¹⁵

我试过 f(s) = "2\^($s)" 但这似乎不是一个有效的指数,因为我不能 TAB。

【问题讨论】:

标签: julia julia-plots


【解决方案1】:

你可以试试例如:

julia> function f(s::AbstractString)
           codes = Dict(collect("1234567890") .=> collect("¹²³⁴⁵⁶⁷⁸⁹⁰"))
           return "2" * map(c -> codes[c], s)
       end
f (generic function with 1 method)

julia> f("2")
"2²"

julia> f("15")
"2¹⁵"

(我还没有优化它的速度,但我希望它足够快,并且易于阅读代码)

【讨论】:

  • 更好的一步(可能)是codes = [x for x in "⁰¹²³⁴⁵⁶⁷⁸⁹"]map(c -> codes[c-'0'+1], s)
  • 硬编码元组 ('⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹') 会更快,因为它是非分配的,但我认为它不太清楚。
【解决方案2】:

这应该快一点,并且使用replace:

function exp2text(x) 
  two = '2'
  exponents = ('⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹') 
  #'⁰':'⁹' does not contain the ranges 
  exp = replace(x,'0':'9' =>i ->exponents[Int(i)-48+1])
  #Int(i)-48+1 returns the number of the character if the character is a number
  return two * exp
end

在这种情况下,我使用了 replace 可以接受 Pair{collection,function} 的事实:

if char in collection
  replace(char,function(char))
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多