3
\$\begingroup\$

To start off I'd like to note I am aware of int(val, base). My goal was to write a short function capable of taking in a base int, and a string defining the value to be summed.

The function rests upon the equation:

represented_value = value * base ^ placeholder

>>> base_v = lambda base_v, num_a: sum(int(num_a[len(num_a) - ph - 1]) * base_v ** ph for ph in range(len(num_a)))
>>> base_v(10, "123")
123
>>> base_v(100, "123")
10203

I can even do something silly like:

>>> base_v(-10, "123")
83
>>>
>>> base_v(-10, ["123", "123", "123"])
11193

I am curious how this function can be made more succinct and what pitfalls it may have.

\$\endgroup\$
  • \$\begingroup\$ When you say "any input" do you mean "any number-like input" or literally anything whatsoever, like null or "hello"? \$\endgroup\$ – Phrancis Jul 2 '16 at 0:48
  • \$\begingroup\$ @Phrancis Sorry about that; is that better? \$\endgroup\$ – motoku Jul 2 '16 at 0:50
  • \$\begingroup\$ May I suggest the tag "reinventing-the-wheel", since you are aware of int(val, base)? \$\endgroup\$ – Graipher Jul 4 '16 at 10:01
9
\$\begingroup\$

A few quick comments:

  • Use a proper function here, not a lambda. It’s generally more readable, and should be preferred unless you’re writing a ~very short function. And then use different variable names for the function and its arguments, otherwise things get confusing.

    Trying to make code more concise is good, but be careful not to make it too short.

  • This function probably needs a docstring (especially because the argument order is the opposite of that used by int()) and a comment. It took me a minute to work out how the code that’s written corresponds to your equation – and indeed, the equation itself isn’t entirely obvious.

  • Your function allows me to pass inputs that don’t make sense. For example:

    >>> print base_v(2, "3")
    3
    

    But 3 isn’t a valid base-2 number: you should throw a ValueError here (like int() does).

  • Rather than indexing from the end of the string with num_a[len(num_a) - ph - 1], you can use negative indexing just to do num_a[-ph-1], which is cleaner and neater.

  • ETA: The other problem is that it can only deal with the digits 1–10. It doesn’t deal with numeric strings that contain letters, e.g. base_v(16, "a") throws a ValueError, even though a is a valid base-16 number.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.