You are given an array of positive integers @N. Write a script to return an array @M where $M[i] is the product of all elements of @N except the index $N[i].
#!/usr/bin/env tclsh
#
# You are given an array of positive integers @N.
# Write a script to return an array @M where $M[i] is the product
# of all elements of @N except the index $N[i].
#
if {$argc <= 1} {
puts "Please input a list."
exit
}
set mylist $argv
set p [tcl::mathop::* {*}$mylist]
set result [list]
foreach element $mylist {lappend result [tcl::mathop::/ $p $element]}
puts $result
使用 lmap 來尋訪串列中的每一個元素來解題,可以改寫如下:
#!/usr/bin/env tclsh
#
# You are given an array of positive integers @N.
# Write a script to return an array @M where $M[i] is the product
# of all elements of @N except the index $N[i].
#
if {$argc <= 1} {
puts "Please input a list."
exit
}
set mylist $argv
set p [tcl::mathop::* {*}$mylist]
set result [lmap element $mylist {tcl::mathop::/ $p $element}]
puts $result
沒有留言:
張貼留言