《Lua程序设计(第4版)》:第5章练习答案

练习5.1

monday sunday sunday

练习5.2

一样,都指向该表。

a.a.a.a=3,执行的是该表的索引 a 赋值为3,之后的a.a.a.a将会引发异常,因现a.a=3,而非表。

练习5.3

在方括号里写索引值

tab={["\n"]=1,["\n\t\a"]=666,["lisper"]="lua"}
for i,j in pairs(tab) do
  io.write(">",i,">>",j,"\n")
end

练习5.4

function ans_s(t,x)
  local sp=t[1]
  for i=2,#t do
    sp=sp+t[i]*x^(i-1)
  end
  return sp
end

练习5.5

function ans(t,x)
  local sp=t[1]
  local dp=x
  for i=2,#t do
    sp=sp+dp*t[i]
    dp=dp*x
  end
  return sp
end

练习5.6

对比ipairs和pairs迭代器循环次数

function ispair(t)
  local x,y
  for i in pairs(t) do
    x=i
  end
  for i in ipairs(t) do
    y=i
  end
  if x~=y then
    return false
  else
    return true
  end
end

练习5.7

function movetable(t1,t2,n)
  table.move(t1,1,#t1,n,t2)
  return t2
end

练习5.8

简单二分优化实现表字符串元素连接函数

function tabconcat(tab)
  local len,con=0,0
  len=#tab
  repeat
    if len%2==1 then
      len=len-1
      con=1
    else
      con=0
    end
    for i=1,len/2,1 do
      tab[i]=tab[2*i-1]..tab[2*i]
    end
    if con==1 then
      tab[len/2+1]=tab[len+1]
      len=len/2+1
    else
      len=len/2
    end
  until len==1
  return tab[1]
end

与标准库table.concat函数进行对比测试。

function test(tm)
  print(">> ",tm," * a concat")
  tab1={}
  for i=1,tm do
    tab1[i]="a"
  end
  time=os.clock()
  str1=tabconcat(tab1)
  print(os.clock()-time,#str1)

  tab2={}
  for i=1,tm do
    tab2[i]="a"
  end
  time=os.clock()
  str2=table.concat(tab2)
  print(os.clock()-time,#str2)
end

test(1000000)
test(10000000)
test(100000000)

测试结果:

>>      1000000  * a concat
0.384   1000000
0.191   1000000
>>      10000000         * a concat
4.168   10000000
1.981   10000000
>>      100000000        * a concat
43.36   100000000
19.721  100000000

时间大约是标准库的二倍。

END

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值