Parallel resistance in electric circuits

21

1

Introduction:

Two resistors, R1 and R2, in parallel (denoted R1 || R2) have a combined resistance Rp given as:

$$R_{P_2} = \frac{R_1\cdot R_2}{R_1+R_2}$$ or as suggested in comments:

$$R_{P_2} = \frac{1}{\frac{1}{R_1} + \frac{1}{R_2}}$$

Three resistors, R1, R2 and R3 in parallel (R1 || R2 || R3) have a combined resistance (R1 || R2) || R3 = Rp || R3 :

$$R_{P_3} = \frac{\frac{R_1\cdot R_2}{R_1+R_2}\cdot R_3}{\frac{R_1\cdot R_2}{R_1+R_2}+R_3}$$

or, again as suggested in comments:

$$R_{P_3} = \frac{1}{\frac{1}{R_1} + \frac{1}{R_2}+ \frac{1}{R_3}}$$

These formulas can of course be extended to an indefinite number of resistors.


Challenge:

Take a list of positive resistor values as input, and output the combined resistance if they were placed in parallel in an electric circuit. You may not assume a maximum number of resistors (except that your computer can handle it of course).

Test cases:

1, 1
0.5

1, 1, 1
0.3333333

4, 6, 3
1.3333333

20, 14, 18, 8, 2, 12
1.1295

10, 10, 20, 30, 40, 50, 60, 70, 80, 90
2.6117  

Shortest code in each language wins. Explanations are highly encouraged.

Stewie Griffin

Posted 2019-09-11T13:55:03.297

Reputation: 43 471

6

There are a few other challenges that refer to the harmonic mean (1 2 3) but I don't think there is a duplicate. In line with what flawr suggested, I think this challenge body should have that phrase listed somewhere so we can close a future dupe more easily.

– FryAmTheEggman – 2019-09-11T15:17:17.173

Answers

13

05AB1E, 5 3 bytes

zOz

Try it online!


Explanation

z                     # compute 1/x for each x in input 
 O                    # sum input 
  z                   # compute 1/sum

Expired Data

Posted 2019-09-11T13:55:03.297

Reputation: 3 129

4Excepting built-ins, this is probably as low as we can go! – None – 2019-09-11T14:57:57.707

9

Haskell, 18 16 bytes

(1/).sum.map(1/)

Try it online!

flawr

Posted 2019-09-11T13:55:03.297

Reputation: 40 560

3It looks beautiful. – Eric Duminil – 2019-09-12T11:52:48.753

Solution along the OP's recursive lines would be 22 chars: foldr1(\r s->r*s/(r+s)). – ceased to turn counterclockwis – 2019-09-12T15:53:33.343

9

MATLAB, 14 bytes

In MATLAB norm(...,p) computes the p-norm of a vector. This is usually defined for \$p \geqslant 1\$ as

$$\Vert v \Vert_p = \left( \sum_i \vert v_i \vert^p \right)^{\frac{1}{p}}.$$

But luckily for us, it also happens to work for \$p=-1\$. (Note that it does not work in Octave.)

@(x)norm(x,-1)

Don't try it online!

flawr

Posted 2019-09-11T13:55:03.297

Reputation: 40 560

4This is horrible and beautiful simultaneously! – ceased to turn counterclockwis – 2019-09-12T15:45:56.537

1Thanks, these are the best compliments:) – flawr – 2019-09-12T16:21:28.797

7

Jelly,  5  3 bytes

İSİ

Try it online!

How?

Initially I forgot this form from my electronic engineering days ...how easily we forget.

İSİ - Link: list of numbers, R   e.g. [r1, r2, ..., rn]
İ   - inverse (vectorises)            [1/r1, 1/r2, ..., 1/rn]
 S  - sum                             1/r1 + 1/r2 + ... + 1/rn
  İ - inverse                         1/(1/r1 + 1/r2 + ... + 1/rn)

Jonathan Allan

Posted 2019-09-11T13:55:03.297

Reputation: 67 804

4I'm assuming İ is pronounced the same way i is pronounced in list. Is this a way of saying the challenge was easy? – Stewie Griffin – 2019-09-13T06:31:14.713

4

Octave, 15 bytes

@(x)1/sum(1./x)

Try it online!

Harmonic mean, divided by n. Easy peasy.

Giuseppe

Posted 2019-09-11T13:55:03.297

Reputation: 21 077

@tsh you know, I don't think I ever noticed that. I guess it's almost the harmonic mean... – Giuseppe – 2019-09-13T13:59:34.347

4

PowerShell, 22 bytes

$args|%{$y+=1/$_};1/$y

Try it online!

Takes input via splatting and uses the same 1/sum of inverse trick as many of the others are doing

Veskah

Posted 2019-09-11T13:55:03.297

Reputation: 3 580

4

APL (Dyalog Unicode), 4 bytes

÷1⊥÷

Try it online!

-1 thanks to Adám.

Erik the Outgolfer

Posted 2019-09-11T13:55:03.297

Reputation: 38 134

1APL is the original golfing language! – None – 2019-09-12T13:35:45.333

@YiminRong It's not a golfing language... :P – Erik the Outgolfer – 2019-09-12T15:11:57.803

I know, but its byte count is on par with modern golfing languages! – None – 2019-09-12T15:33:26.163

-1 byte: ÷1⊥÷ Try it online!

– Adám – 2019-09-15T09:27:54.110

@Adám Oh duh of course 1∘⊥ is the same as +/ for vectors... – Erik the Outgolfer – 2019-09-15T11:36:51.967

Heh, it is even on APLcart.

– Adám – 2019-09-15T11:38:25.670

@Adám Hm... somewhat obscure entry... :P – Erik the Outgolfer – 2019-09-15T11:42:48.437

3

R, 15 bytes

1/sum(1/scan())

Try it online!

Follows the same Harmonic Mean principle seen in other answers.

Sumner18

Posted 2019-09-11T13:55:03.297

Reputation: 1 334

3

JavaScript, 28 bytes

a=>a.map(y=>x+=1/y,x=0)&&1/x

Try it Online!

Shaggy

Posted 2019-09-11T13:55:03.297

Reputation: 24 623

3

Perl 6, 14 bytes

1/*.sum o 1/**

Try it online!

1 / ** is an anonymous function that returns a list of the reciprocals of its arguments. 1 / *.sum is another anonymous function that returns the reciprocal of the sum of the elements of its list argument. The o operator composes those two functions.

Sean

Posted 2019-09-11T13:55:03.297

Reputation: 4 136

Very nice. I don't see HyperWhatevers used often enough in golfing since they can't be used in more complex expressions. If they were closer to normal Whatevers, I'd expect sumething like this to work, but alas...

– Jo King – 2019-09-12T00:17:20.230

Yeah, this is probably the first time I've even thought about using one for golfing, and I was disappointed to discover its limitations. – Sean – 2019-09-12T00:28:42.520

3

Perl 5 -pa -MList::Util=reduce, 26 bytes

$_=reduce{$a*$b/($a+$b)}@F

Try it online!

Xcali

Posted 2019-09-11T13:55:03.297

Reputation: 7 671

20 bytes – Nahuel Fouilleul – 2019-09-11T18:45:08.513

@NahuelFouilleul 17 bytes, no -M

– Grimmy – 2019-09-12T00:26:11.127

3

bash + coreutils, 25 bytes

bc -l<<<"1/(0${@/#/+1/})"

TIO

Nahuel Fouilleul

Posted 2019-09-11T13:55:03.297

Reputation: 5 582

3

attinat

Posted 2019-09-11T13:55:03.297

Reputation: 3 495

Is there no harmonic mean builtin, or is it longer to type? – Eric Duminil – 2019-09-12T11:53:30.593

@Eric AFAIK it's intuitively named HarmonicMean and is longer. – my pronoun is monicareinstate – 2019-09-12T15:23:42.497

3

MathGolf, 3 bytes

∩Σ∩

The same as other answers, using the builtins (\$\frac{1}{n}\$) and Σ (sum): $$M(x_1,...,x_n)=\frac{1}{\frac{1}{x_1} + \frac{1}{x_2} + ... + \frac{1}{x_n}}$$

Try it online.

Kevin Cruijssen

Posted 2019-09-11T13:55:03.297

Reputation: 67 575

2

JavaScript (ES6), 29 bytes

a=>a.reduce((p,c)=>p*c/(p+c))

Try it online!

or:

a=>1/a.reduce((p,c)=>p+1/c,0)

Try it online!

But with this approach, using map() (as Shaggy did) is 1 byte shorter.

Arnauld

Posted 2019-09-11T13:55:03.297

Reputation: 111 334

2

MATL, 5 bytes

,1w/s

Try it online!

I'm not sure if "do twice" (,) counts as a loop, but this is just the harmonic mean, divided by n.

Alternately, ,-1^s is five bytes as well.

Giuseppe

Posted 2019-09-11T13:55:03.297

Reputation: 21 077

2

PHP, 51 bytes

Reciprocal of sum of reciprocals. Input is $a.

1/array_reduce($a,function($c,$i){return$c+1/$i;});

Try it online!

user15259

Posted 2019-09-11T13:55:03.297

Reputation:

With PHP7.4, I think you can do this: 1/array_reduce($a,fn($c,$i)=>$c+1/$i); (38 bytes). Read more in https://wiki.php.net/rfc/arrow_functions

– Ismael Miguel – 2019-09-13T16:41:05.617

I think you're right! But nowhere to demo? – None – 2019-09-13T18:28:58.147

You have to download it yourself. However, since PHP 7.4.0RC1 was released on the 5th of this month (https://www.php.net/archive/2019.php#2019-09-05-1), you probably are safe using it. If you have doubts, you can ask in the meta.

– Ismael Miguel – 2019-09-13T21:41:08.510

2

Python 3, 30 bytes

lambda r:1/sum(1/v for v in r)

Try it online!

Jonathan Allan

Posted 2019-09-11T13:55:03.297

Reputation: 67 804

2

Perl 5 (-p), 17 bytes

$a+=1/$_}{$_=1/$a

Try it online!

Grimmy

Posted 2019-09-11T13:55:03.297

Reputation: 12 521

2

x86-64 Machine code - 20 18 bytes

0F 57 C0             xorps       xmm0,xmm0  
loopHead
F3 0F 53 4C 8A FC    rcpss       xmm1,dword ptr [rdx+rcx*4-4]
0F 58 C1             addps       xmm0,xmm1  
E2 F6                loop        loopHead
0F 53 C0             rcpps       xmm0,xmm0  
C3                   ret  

Input - Windows calling convention. First parameter is the number of resistors in RCX. A pointer to the resistors is in RDX. *ps instructions are used since they are one byte smaller. Technically, you can only have around 2^61 resistors but you will be out of RAM long before then. The precision isn't great either, since we are using rcpps.

me'

Posted 2019-09-11T13:55:03.297

Reputation: 451

“Only 2⁶¹ resistors” would probably fill the observable universe (many times over)! – None – 2019-09-12T13:39:08.157

Actually, 2^61 is only 2.305843e+18 and the observable universe is 8.8 × 10^26 m in diameter. – me' – 2019-09-14T09:22:52.117

Yeah, serious overestimation! Actual magnitude would be around the size and mass of Deimos, smaller moon of Mars. – None – 2019-09-14T14:48:36.923

2

Java 8, 24 bytes

a->1/a.map(d->1/d).sum()

I noticed there wasn't a Java answer yet, so figured I'd add one.

Try it online.

Explanation:

Uses the same Harmonic Mean approach as other answers:

$$M(x_1,...,x_n)=\frac{1}{\frac{1}{x_1} + \frac{1}{x_2} + ... + \frac{1}{x_n}}$$

a->                       // Method with DoubleStream parameter and double return-type
     a.map(d->1/d)        //  Calculate 1/d for each value `d` in the input-stream
                  .sum()  //  Then take the sum of the mapped list
   1/                     //  And return 1/sum as result

Kevin Cruijssen

Posted 2019-09-11T13:55:03.297

Reputation: 67 575

2

Intel 8087 FPU machine code, 19 bytes

 D9 E8      FLD1                    ; push 1 for top numerator on stack
 D9 EE      FLDZ                    ; push 0 for running sum 
        R_LOOP: 
 D9 E8      FLD1                    ; push 1 numerator for resistor
 DF 04      FILD WORD PTR[SI]       ; push resistor value onto stack 
 DE F9      FDIV                    ; divide 1 / value 
 DE C1      FADD                    ; add to running sum 
 AD         LODSW                   ; increment SI by 2 bytes 
 E2 F4      LOOP R_LOOP             ; keep looping 
 DE F9      FDIV                    ; divide 1 / result                  
 D9 1D      FSTP WORD PTR[DI]       ; store result as float in [DI]

This uses the stack-based floating point instructions in the original IBM PC's 8087 FPU.

Input is pointer to resistor values in [SI], number of resistors in CX. Output is to a single precision (DD) value at [DI].

640KB

Posted 2019-09-11T13:55:03.297

Reputation: 7 149

1

Charcoal, 7 bytes

I∕¹Σ∕¹A

Try it online! Link is to verbose version of code. Works by calculating the current drawn by each resistor when 1V is applied, taking the total, and calculating the resistance that would draw that current when 1V is applied. Explanation:

      A Input array
    ∕¹  Reciprocal (vectorised)
   Σ    Sum
 ∕¹     Reciprocal
I       Cast to string for implicit print

Neil

Posted 2019-09-11T13:55:03.297

Reputation: 95 035

1

Dart, 42 bytes

f(List<num>a)=>a.reduce((p,e)=>p*e/(p+e));

Try it online!

Having to explicitly specify the num type is kinda sucky, prevents type infering, because it would infer to (dynamic, dynamic) => dynamic which can't yield doubles for some reason

Elcan

Posted 2019-09-11T13:55:03.297

Reputation: 913

1

PHP, 40 bytes

for(;$n=$argv[++$i];$r+=1/$n);echo 1/$r;

Try it online!

Tests: Try it online!

Similar to Yimin Rong's solution but without built-ins and all program bytes are included in the bytes count.

Night2

Posted 2019-09-11T13:55:03.297

Reputation: 5 484

1

Python 3, 58 44 bytes

f=lambda x,y=0,*i:f(x*y/(x+y),*i)if y else x

A recursive function. Requires arguments to be passed unpacked, like so:

i=[10, 10, 20]
f(*i)

or

f(10, 10, 20)

Explanation:

# lambda function with three arguments. *i will take any unpacked arguments past x and y,
# so a call like f(10, 20) is also valid and i will be an empty tuple
# since y has a default value, f(10) is also valid
f=lambda x,y=0,*i: \

# a if case else b
# determine parallel resistance of x and y and use it as variable x
# since i is passed unpacked, the first item in the remaining list will be y and
# the rest of the items will be stored in i
# in the case where there were no items in the list, y will have the default value of 0
f(x*y/(x+y),*i) \

# if y does not exist or is zero, return x
if y else x

Triggernometry

Posted 2019-09-11T13:55:03.297

Reputation: 765

1

J, 6 bytes

1%1#.%

Try it online!

Galen Ivanov

Posted 2019-09-11T13:55:03.297

Reputation: 13 815

2it's a pity "sum under reciprocal" is the same number of bytes: +/&.:% – ngn – 2019-09-13T16:53:45.197

@ngn Yes, but your solution looks more idiomatic to J. – Galen Ivanov – 2019-09-13T17:55:31.300

1

Ruby, 26 22 bytes

-4 bytes thanks to @ValueInk.

->x{1/x.sum{|i|1.0/i}}

Try it online!

Eric Duminil

Posted 2019-09-11T13:55:03.297

Reputation: 701

1x.sum{...} is equivalent to x.map{...}.sum – Value Ink – 2019-09-13T20:24:51.410

@ValueInk: Doh! Thanks a lot – Eric Duminil – 2019-09-13T20:38:40.647

1

[MATLAB], 15 bytes

One more byte than flawr excellent answer, but I had to use other functions so here goes:

@(x)1/sum(1./x)

It's rather explicit, it sums the inverse of the resistances, then invert the sum to output the equivalent parallel resistance.

Hoki

Posted 2019-09-11T13:55:03.297

Reputation: 271

1

Forth (gforth), 49 bytes

: f 0e 0 do dup i cells + @ s>f 1/f f+ loop 1/f ;

Try it online!

Input is a memory address and array length (used as an impromptu array, since Forth doesn't have a built-in array construct)

Uses the sum-of-inverse method as most other answers are

Code Explanation

: f           \ start a new word definition
  0e          \ stick an accumulator on the floating point stack
  0 do        \ start a loop from 0 to array-length -1
    dup       \ copy the array address
    i cells + \ get the address of the current array value
    @ s>f     \ get the value and convert it to a float
    1/f f+    \ invert and add to accumulator
  loop        \ end the loop definition
  1/f         \ invert the resulting sum
;             \ end the word definition

reffu

Posted 2019-09-11T13:55:03.297

Reputation: 1 361

1

C#, 16 bytes

1/l.Sum(n=>1f/n)

Try It

koviroli

Posted 2019-09-11T13:55:03.297

Reputation: 119

1

Since the Sum() function can also accept a selector, you can cut 9 bytes by ommiting the .Select() part, like so

– pappbence96 – 2019-09-13T13:21:24.190

1Just realized, one more byte can be saved by writing 1f/n instead of 1.0/n as both methods will avoid integer division. – pappbence96 – 2019-09-13T13:29:47.583

nice catch mate! – koviroli – 2019-09-13T13:33:09.080

1

expl3 (LaTeX3 programming layer), 65 bytes

The following defines a function that prints the result to the terminal (unfortunately expl3 has very verbose function names):

\def\1#1{\fp_show:n{1/(\clist_map_function:nN{#1}\2)}}\def\2{+1/}

A complete script which can be run from the terminal including all the test cases as well as the setup to enter expl3:

\RequirePackage{expl3}\ExplSyntaxOn
\def\1#1{\fp_show:n{1/(\clist_map_function:nN{#1}\2)}}\def\2{+1/}
\1{1, 1}
\1{1, 1, 1}
\1{4, 6, 3}
\1{20, 14, 18, 8, 2, 12}
\1{10, 10, 20, 30, 40, 50, 60, 70, 80, 90}
\stop

If run with pdflatex <filename> the following is the console output:

This is pdfTeX, Version 3.14159265-2.6-1.40.20 (TeX Live 2019) (preloaded format=pdflatex)
 restricted \write18 enabled.
entering extended mode
(./cg_resistance.tex
LaTeX2e <2018-12-01>
(/usr/local/texlive/2019/texmf-dist/tex/latex/unravel/unravel.sty
(/usr/local/texlive/2019/texmf-dist/tex/latex/l3kernel/expl3.sty
(/usr/local/texlive/2019/texmf-dist/tex/latex/l3kernel/expl3-code.tex)
(/usr/local/texlive/2019/texmf-dist/tex/latex/l3backend/l3backend-pdfmode.def))
 (/usr/local/texlive/2019/texmf-dist/tex/latex/l3packages/xparse/xparse.sty)
(/usr/local/texlive/2019/texmf-dist/tex/generic/gtl/gtl.sty))
> 1/(\clist_map_function:nN {1,1}\2)=0.5.
<recently read> }

l.3 \1{1, 1}

?
> 1/(\clist_map_function:nN {1,1,1}\2)=0.3333333333333333.
<recently read> }

l.4 \1{1, 1, 1}

?
> 1/(\clist_map_function:nN {4,6,3}\2)=1.333333333333333.
<recently read> }

l.5 \1{4, 6, 3}

?
> 1/(\clist_map_function:nN {20,14,18,8,2,12}\2)=1.129538323621694.
<recently read> }

l.6 \1{20, 14, 18, 8, 2, 12}

?
> 1/(\clist_map_function:nN
{10,10,20,30,40,50,60,70,80,90}\2)=2.611669603067675.
<recently read> }

l.7 \1{10, 10, 20, 30, 40, 50, 60, 70, 80, 90}

?
 )
No pages of output.
Transcript written on cg_resistance.log.

Explanation

\fp_show:n : evaluates its argument as a floating point expression and prints the result on the terminal, every expandable macro is expanded during that process.

\clist_map_function:nN : takes two arguments, a comma separated list and a function/macro, if called like \clist_map_function:nN { l1, l2, l3 } \foo it expands to something like \foo{l1}\foo{l2}\foo{l3}. In our case instead of \foo the macro \2 is used, which expands to +1/ so that the expression expands to +1/{l1}+1/{l2}+1/{l3}

Skillmon

Posted 2019-09-11T13:55:03.297

Reputation: 431

1

SimpleTemplate, 72 bytes

Okay, this was VERY hard!
Specifically with a language that has VERY poor math support.

{@fnx A,S}{@eachA}{@set/_ 1 _}{@set+S S,_}{@/}{@set/S 1 S}{@returnS}{@/}

Creates a function x that must be called by passing an array as the first and only argument.

Ungolfed:

{@fn calc values, sum}
    {@each values as value}
        {@set/ value 1 value}
        {@set+ sum sum, value}
    {@/}
    {@set/ sum 1 sum}
    {@return sum}
{@/}

Explanation:

  • {@fn calc values, sum} - Creates the function calc, which has 2 variables (values and sum) taking the values of the first arguments (defaults to null)
  • {@each values as value} - Loops over each value in values
  • {@set/ value 1 value} - Divides 1 by value, storing it into value
  • {@set+ sum sum, value} - Adds sum to value, storing it into sum
  • {@/} - Closes the {@each} (usually optional)
  • {@set/ sum 1 sum} - Divides 1 by sum, storing it into sum
  • {@return sum} - Returns sum (duh)
  • {@/} - Closes the {@fn} (usually optional, even if it shouldn't be for functions)

To use the function, you can use this code:

{@set values 10, 10, 20, 30, 40, 50, 60, 70, 80, 90} {@//array of values}
{@call calc into result values}
{@echo result} {@//2.6116696030677}


If you are curious, the ungolfed example compiles to this PHP code:

// {@fn calc values, sum}
$DATA['calc'] = function()use(&$FN, &$_){
    $DATA = array(
        'argv' => func_get_args(),
        'argc' => func_num_args(),
        'VERSION' => '0.62',
        'EOL' => PHP_EOL,
        'PARENT' => &$_
    );
    $_ = &$DATA;
    $DATA["values"] = &$DATA["argv"][0];
    $DATA["sum"] = &$DATA["argv"][1];


    // {@each values as value}
    // loop variables
    $tmp_1_val = isset($DATA['values']) ? $tmp_1_val = &$DATA['values'] : null;
    $tmp_1_keys = gettype($DATA['values']) == 'array'
        ? array_keys($DATA['values'])
        : array_keys(range(0, strlen($tmp_1_val = $tmp_1_val . '') - 1));
    $tmp_1_key_last = end($tmp_1_keys);

    // loop
    foreach($tmp_1_keys as $tmp_1_index => $tmp_1_key){
        $DATA['loop'] = array(
            'index' => $tmp_1_index,
            'i' => $tmp_1_index,
            'key' => $tmp_1_key,
            'k' => $tmp_1_key,
            'value' => $tmp_1_val[$tmp_1_key],
            'v' => $tmp_1_val[$tmp_1_key],
            'first' => $tmp_1_key === $tmp_1_keys[0],
            'last' => $tmp_1_key === $tmp_1_key_last,
        );
        $DATA['__'] = $tmp_1_key;
        $DATA['value'] = $tmp_1_val[$tmp_1_key];

        // {@set/ value 1 value}
        $DATA['value'] = array_map(function($value)use(&$DATA){return (1 / $value);}, $FN['array_flat']((isset($DATA['value'])?$DATA['value']:null)));

        // {@set+ sum sum, value}
        $DATA['sum'] = array_sum($FN['array_flat'](array((isset($DATA['sum'])?$DATA['sum']:null),(isset($DATA['value'])?$DATA['value']:null))));

    // {@/}
    };

    // {@set/ sum 1 sum}
    $DATA['sum'] = array_map(function($value)use(&$DATA){return (1 / $value);}, $FN['array_flat']((isset($DATA['sum'])?$DATA['sum']:null)));

    // {@return sum}
    return (isset($DATA['sum'])?$DATA['sum']:null);

// {@/}
};

// {@set values 10, 10, 20, 30, 40, 50, 60, 70, 80, 90}
$DATA['values'] = array(10,10,20,30,40,50,60,70,80,90);

// {@call calc into result values}
$DATA['result'] = call_user_func_array(isset($DATA['calc']) && is_callable($DATA['calc'])? $DATA['calc']: (isset($FN["calc"])? $FN["calc"]: "calc"), array((isset($DATA['values'])?$DATA['values']:null)));

// {@echo result}
echo implode('', $FN['array_flat']((isset($DATA['result'])?$DATA['result']:null)));

Ismael Miguel

Posted 2019-09-11T13:55:03.297

Reputation: 6 797

0

Pyth, 6 bytes

c1scL1

Try it online!

Uses the modified formula \$\frac{1}{R_P}=\frac{1}{R_1} + \frac{1}{R_2}\$.

c1      # 1/
  s     #   sum(                     )
   cL1  #       map(lambda x: 1/x, Q)  # Q (=input) is implicit

ar4093

Posted 2019-09-11T13:55:03.297

Reputation: 531

0

Japt v2.0a0, 7 bytes

1÷Ux!÷1

Try it

Shaggy

Posted 2019-09-11T13:55:03.297

Reputation: 24 623

0

OCaml, 50 bytes

fun l->1./.(List.fold_left(fun a e->a+.1./.e)0. l)

Try it online!

Saswat Padhi

Posted 2019-09-11T13:55:03.297

Reputation: 111

0

Stax, 5 bytes

{u+Fu

Run and debug it at staxlang.xyz!

{  F     For each:
 u         Invert
  +        Add to running total
    u    Invert
         Implicit print as fraction

Khuldraeseth na'Barya

Posted 2019-09-11T13:55:03.297

Reputation: 2 608

0

Scala, 15 bytes

1/_.map(1/).sum

Try it online!

Soapy

Posted 2019-09-11T13:55:03.297

Reputation: 251

0

Python, 30 bytes

lambda v:1/sum(1/x for x in v)

-2, thanks @JoKing

pikaynu

Posted 2019-09-11T13:55:03.297

Reputation: 101

Welcome to PPCG! Unfortunately, submissions should either be a full program (preface with v=input();print) or a function (preface with lambda v:) to be valid. A snippet which presumes pre-defined variables isn't allowed. – Value Ink – 2019-09-16T18:41:56.210

Welcome to the site! This is a snippet, which means that you don't output or input according to our Input/Output rules. You can correct this by wrapping the statement in print(...) and by taking v as input, either in a lambda or by using input.

– caird coinheringaahing – 2019-09-16T18:42:48.173

That's unfortunate, thanks for pointing me to the IO conventions. I have updated my answer. :) – pikaynu – 2019-09-17T09:54:17.720

0

jq, 16 characters

1/(map(1/.)|add)

Sample run:

bash-5.0$ jq '1/(map(1/.)|add)' <<< '[10, 10, 20, 30, 40, 50, 60, 70, 80, 90]'
2.611669603067675

Try it online!

manatwork

Posted 2019-09-11T13:55:03.297

Reputation: 17 865

0

C (gcc), 65 62 bytes

Thanks to ceilingcat for -3 bytes.

float a(b,c)int*b;{float d=0;for(;c--;)d+=1./b[c];return 1/d;}

Try it online!

girobuz

Posted 2019-09-11T13:55:03.297

Reputation: 391

0

C++ (clang), 78 bytes

#import<list>
void f(std::list<int>r,double&s){s=0;for(int p:r)s+=1./p;s=1/s;}

Try it online!

bznein

Posted 2019-09-11T13:55:03.297

Reputation: 121

77 bytes – ceilingcat – 2019-12-04T21:13:00.203