21
\$\begingroup\$

Title is an homage to this classic challenge

In Pip, the Scalar data type encompasses strings and numbers. A Scalar value is truthy in most cases. It is falsey only if:

  • It is the empty string ""; or
  • It is some representation of the number zero.

A Scalar is considered to be a representation of zero if:

  • It consists of one or more 0s; or
  • It consists of one or more 0s plus a single . anywhere among them.

The decimal point can be in the middle, at the beginning, or at the end.

Challenge

Given a string containing printable ASCII characters, determine whether it is a truthy Scalar or a falsey Scalar according to Pip.

The default allowable output formats for apply: you may either output a truthy/falsey value in your language, with swapping allowed, or choose two consistent values, one representing truthy and the other representing falsey.

This is ; the goal is to minimize the size of your source code, measured in bytes.

Examples

Falsey:

""
"0"
"000"
".0"
".00"
"0."
"00."
"0.00"
"0000000000000.00000000000000"

Truthy:

"abc"
"x"
"0001"
"0x00"
"0e0"
" 0"
"0 "
"+0"
"-0"
"."
"0.0.0"
"0.00000000000000000000000001"

Reference implementation

This Python 3 code is adapted from the actual Pip interpreter:

import re
zeroRgx = re.compile(r"^(0+(\.0*)?|0*\.0+)$")
def truthy(value):
    return value != "" and not zeroRgx.match(value)

Try it online!

\$\endgroup\$
0

21 Answers 21

17
\$\begingroup\$

Python, 29 bytes

lambda s:s.strip("0")in"."!=s

Attempt This Online!

Outputs True for falsy and False for truthy.

\$\endgroup\$
7
  • \$\begingroup\$ I feel there should be a better way using float... \$\endgroup\$ Dec 30, 2022 at 12:31
  • 8
    \$\begingroup\$ @UndoneStudios I don't know. float doesn't feel like a good match. First, it has three different outcomes (zero, non-zero and exception). Second, it accepts stuff like 0e1,0_0,+0 and even 0.<lots of zeros>1 for zero while rejecting the empty string. So making it work seems a lot of trouble. \$\endgroup\$ Dec 30, 2022 at 14:46
  • \$\begingroup\$ how does this work?? lol i dont get it \$\endgroup\$
    – DialFrost
    Jan 1, 2023 at 9:10
  • 1
    \$\begingroup\$ @DialFrost It uses Python operator chaining to check that after removing all leading and trailing zeros there is nothing or a single dot left while explicitly ruling out just a single dot (and no zeros). \$\endgroup\$ Jan 1, 2023 at 13:46
  • 1
    \$\begingroup\$ @DialFrost It looks confusing because he's abusing comparison chaining. For non golf purposes it would look more like ((s.strip("0") in ".") and ("." != s)). Fun stuff, nice answer. \$\endgroup\$ Jan 5, 2023 at 22:39
9
\$\begingroup\$

JavaScript (Node.js), 23 bytes

s=>/[^0.]/.test(s)|s!=0

Try it online!

\$\endgroup\$
8
\$\begingroup\$

05AB1E, 7 bytes

„+-₂‡{Ā

Try it online or verify all test cases.

Explanation:

    ‡    # Transliterate in the (implicit) input-string
„+-      # all "+" and "-"
   ₂     # to "2" and "6" respectively
     {   # Sort all characters in this string (based on codepoint)
      Ā  # 'Python-style' truthify this sorted string
         # (which is output implicitly as result)

The new 05AB1E is built in Elixir.
With just Ā, the 0. and 00. test cases are incorrectly truthy instead of falsey and the +0, -0, and 0e0 test cases are incorrectly falsey instead of truthy. The sort { is to fix 0., 00., and 0e0 and the transliterate „+-₂‡ to fix +0 and -0.


05AB1E (legacy), 8 bytes

…+- ₁‡{Ā

Try it online or verify all test cases.

Explanation:

     ‡    # Transliterate in the (implicit) input-string
„+-       # all "+", "-", and " "
    ₁     # to "2", "5", and "6" respectively
      {Ā  # Same as above
          # (after which the result is output implicitly)

The legacy version of 05AB1E is built in Python 3.
With just Ā, the 0, 0 , +0, -0, and 0e0 test cases are incorrectly falsey instead of truthy. The transliterate …+- ₁‡ is to fix 0, 0 , +0, and -0, and sort { is to fix 0e0 (thanks to @JonathanAllan for noticing a bug with this 0e0 test case).


2sable, 11 10 9 bytes

'.Q«Ô0Þså

Outputs an inverted boolean.

Try it online or verify all test cases.

Explanation:

'.Q       '# Check if the (implicit) input is equal to "."
   «       # Append this 1 or 0 to the (implicit) input
    Ô      # Connected uniquify (uniquifies groups of adjacent equal characters)
     0     # Push integer 0
      Þ    # Floatify and then stringify it: "0.0"
       så  # Check if the connected uniquify string is a substring of this
           # (so one of "", "0", "0.", ".0", "0.0", or "."†)
           # (which is output implicitly as result)

2sable is built in Python 3 as well, and is the oldest of the three versions and predecessor of the legacy 05AB1E version.
It lacks a lot of the builtins, including the Ā we use in the other two programs, so I had to find an alternative. I ended up using the connected uniquify builtin Ô and check whether the result is one of "", "0", "0.", .0", "0.0". I do this by checking whether it's a substring of "0.0".
† After which only the "." test case would incorrectly give a truthy instead of falsey result, which I've fixed by adding a leading '.Q«.

\$\endgroup\$
0
6
\$\begingroup\$

Trivial Pip answers, 1 byte

Thanks to defaults, the identity function/program is a solution in Pip, since it turns falsey inputs into falsey outputs and truthy inputs into truthy outputs. Therefore, either of these full programs will work when given input as a command-line argument:

a
g

This program will work when given input on stdin:

q

And this works as a function solution:

_

While we're at it, logically negating the input gives some two- and three-byte solutions:

!a
!q
\!_

I'm making this post as a community wiki to head off these obvious answers (and other trivial solutions such as @g or {a} that are basically the same thing but longer). You are encouraged to post your own non-trivial Pip solutions.

\$\endgroup\$
1
  • \$\begingroup\$ I really don’t get why people always upvote the CW for boring answers to oblivion… \$\endgroup\$
    – noodle man
    Oct 26, 2023 at 12:12
6
\$\begingroup\$

Charcoal, 9 bytes

∧№.⁻θ0⁻.θ

Try it online! Link is to verbose version of code. Outputs . for truthy, nothing for falsy. Note: Due to bugs in Charcoal's input, you need to input an empty string using a blank line. Explanation: Port of @Albert.Lang's Python answer.

 №          Count of
    θ       Input string
   ⁻ 0      With `0`s removed
  .         In literal string `.`
∧           Logical And
       .    Literal string `.`
      ⁻ θ   With input string removed
\$\endgroup\$
1
  • \$\begingroup\$ The newer version of Charcoal on ATO doesn't have the JSON input bug so you can use that to input an empty string: Attempt This Online! \$\endgroup\$
    – Neil
    Dec 30, 2022 at 9:51
5
\$\begingroup\$

Retina 0.8.2, 16 15 bytes

1`0\.|\.0

^0*$

Try it online! Link includes test cases. Explanation:

1`0\.|\.0

Delete at most one . adjacent to a 0.

^0*$

Match any number of zeros.

\$\endgroup\$
1
  • \$\begingroup\$ My previous version ^(?!\.$)0*\.?0*$ is still a 16-byte Regex answer, which ties with @Bubbler's answer, although it requires negative lookahead, which means that it's not quite as universal. \$\endgroup\$
    – Neil
    Jan 6, 2023 at 8:44
5
\$\begingroup\$

Vyxal, 11 bytes

`+- `₈ĿṅsEḃ

Try it online!

Port of Kevin Cruijssen's 05AB1E (legacy) answer.

Explanation

`+- `₈ĿṅsEḃ
      Ŀ     # Transliterate the (implicit) input,
`+- `       # Replacing the characters "+", "-" and " "
     ₈      # With the characters "2", "5" and "6" respectively
       ṅ    # Join the list created by nothing
        s   # Sort the string
         E  # Evaluate the string
          ḃ # And convert to a boolean (Python-style)
\$\endgroup\$
1
4
\$\begingroup\$

Factor + math.unicode, 45 bytes

[ dup "0"without "."subseq? swap "."≠ and ]

Attempt This Online!

Returns t for falsey and f for truthy. With zeros removed, is it a sub-sequence of "."? And is the original input not equal to "."?

\$\endgroup\$
4
\$\begingroup\$

C (gcc), 75 bytes

i;f(char*s){return*s==48?i+=2,f(s+1):*s-46||i++&1?s=i!=1&!*s,i=0,s:f(s+1);}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ 74 bytes swapping back truthy and falsey \$\endgroup\$
    – c--
    Jul 18, 2023 at 16:07
3
\$\begingroup\$

Go, 106 bytes

import."regexp"
func f(s string)bool{return len(s)>0&&!MustCompile(`^(0+(\.0*)?|0*\.0+)$`).MatchString(s)}

Attempt This Online!

Port of the reference regexp.

\$\endgroup\$
3
\$\begingroup\$

R, 36 bytes

\(s)trimws(s,,0)%in%c("",".")&s!="."

Attempt This Online!

Port of @Albert.Lang's answer.

Uses the whitespace argument of the trimws function introduced in R 3.6.0.

\$\endgroup\$
3
\$\begingroup\$

Regex (any), 16 bytes

^0*(0\.|\.0)?0*$

Falsy matches the regex, truthy doesn't.

Python 3, 46 bytes

import re;re.compile(r"0*(0\.|\.0)?0*$").match

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Pip, 16 13 bytes

aRM0N'.&!aQ'.

Try It Online!

-3 bytes thanks to @DLosc
Non-trivial pip answer, port of @Albert.Lang's answer

\$\endgroup\$
0
3
+200
\$\begingroup\$

Acc!!, 107 bytes

Count i while 1-_/4 {
_*524+N
53308230694/5^(_/131+2*0^(_%131-48)^2+0^(_%131-46)^2+_^130%131)%5+1
}
Write _

Attempt This Online!

Takes the input NULL-terminated, returns chr(5) for truthy and chr(4) for falsey.

53308230694 encodes this table (minus 1, which is later added), which represents the transitions of a FSM for this language, and the rest of the code just converts the input to the correct format.

State\Input 0 1 2 3
0 5 4 3 1
1 5 4 2 1
2 5 4 4 2
3 4 4 4 2

Where 0 is "null byte", 1 is "invalid character", 2 is ".", and 3 is "0". The state 4 is rejected, and 5 is accepted.

\$\endgroup\$
2
\$\begingroup\$

Python 3, 73 72 67 66 64 bytes

lambda v:not re.match("^(0+(\.0*)?|0*\.0+)$",v)and""<v
import re

Try it online!

Golfed reference implementation from @DLosc.

\$\endgroup\$
4
  • \$\begingroup\$ you don't need ""<, you can just output truthy/falsey \$\endgroup\$
    – naffetS
    Jan 1, 2023 at 14:47
  • \$\begingroup\$ @Steffan then it'll fail when v="" as the 1st truthy testcase \$\endgroup\$
    – DialFrost
    Jan 1, 2023 at 21:16
  • \$\begingroup\$ No it won't, just boolify the result first \$\endgroup\$
    – naffetS
    Jan 1, 2023 at 21:16
  • \$\begingroup\$ Hint: my regex isn't the golfiest possible regex ;) \$\endgroup\$
    – DLosc
    Jan 2, 2023 at 5:47
2
\$\begingroup\$

PowerShell Core, 31 bytes

"$args"-match"^0*(0\.|\.0)?0*$"

Try it online!

Down to 31 bytes using Bubbler's regex

\$\endgroup\$
2
\$\begingroup\$

Pyth, 8 bytes

x"0."_S{

Try it online!

Feels like there's gotta be something shorter but I couldn't find it.

Outputs 0 for falsy and -1 or 1 for truthy.

Explanation

x"0."_S{Q    # Implicitly add Q
             # Implicitly assign Q = eval(input())
       {Q    # deduplicate
      S      # sort
     _       # reverse (at this point we have either "", "0", or "0.")
x"0."        # find in "0." (returns 0 for above, 1 for ".", -1 for all else)
\$\endgroup\$
2
  • \$\begingroup\$ @DLosc You are correct, I guess I was assuming that the returns needed to be consistent for all truthy/falsy cases. \$\endgroup\$ Jan 10, 2023 at 14:55
  • 1
    \$\begingroup\$ Fails for inputs like "0..0" and "0.0.0" (not falsy but outputs 0). \$\endgroup\$
    – Bubbler
    Nov 1, 2023 at 7:38
2
\$\begingroup\$

Google Sheets, 37 34 bytes

=regexmatch(A1,"^0*\.?0*$")*(A1<>".")

Put the input in cell A1 and the formula in B1. Outputs 1 for falsey and 0 for truthy.

Using Bubbler's regex:

=regexmatch(A1,"^0*(0\.|\.0)?0*$")

Outputs TRUE for falsey and FALSE for truthy.

\$\endgroup\$
2
\$\begingroup\$

Uiua, 33 bytes 28 bytes (SBCS)

Edit: Using Bubbler's improved regex.

=0⧻regex"^0*(0\\.|\\.0)?0*$"

Try it online!

Not much to explain here - it just matches the regex with the input string and checks that the number of matches is 0.

Idiomatic Uiua, 39 bytes

(0;|(↥⊃'>⊢(<⊢⇌)∶1|1;)∊0∩/+⍉.∺="0.")>0⧻.

Try it online!

Explanation:

(0;|                                )>0⧻.   # If the length is 0 return 0. Otherwise:
                              ∺="0."        # Produce a matrix of matches with '0' and '.'
                           ⍉.              # Make a copy and transpose it
                        ∩/+                 # In both the original and transposed matrices, add up each row
    (             |1;)∊0                    # If there is a 0 in the per character array
                                            # (signifying a character other than '0' or '.'),
                                            # return 1. Otherwise:
                ∶1                          # Put a 1 on the stack and swap the top two items
      ⊃                                     # Apply both of the next functions to the same values
          (<⊢⇌)                            # Reverse the array and check if 1 < the first value
                                            # (This tests that the number of '.' chars is > 1)
       '>⊢                                  # Check if 1 > the first value
                                            # (This tests that the number of '0' chars is < 1)
     ↥                                      # Return the maximum of the two checks
# (This will return 0 if the number of '0' chars >= 1 AND the number of '.' <= 1)
\$\endgroup\$
2
\$\begingroup\$

Uiua, 18 bytes

<∩≍¬⊚.=@.⊃▽'△.≠@0.

Try it online!

Initially based on chunes' Factor answer, but it evolved a lot from it. Returns 1 if the input is falsy, 0 otherwise.

<∩≍¬⊚.=@.⊃▽'△.≠@0.    input: a string S
                  ≠@0.    keep S and push its non-zero-digit mask
          ⊃▽            S with zeros filtered out
       =@.                is-dot mask of above
 ∩≍¬⊚.                C1:is it the same as boolean negation of its nonzero indices?
(the length can be equal only if the mask is all ones, and the content equal only if
 the length is zero or one, i.e. the array is [] or [1].
 this tests if the input without zeros is either empty or a sole dot.
 now we need to filter out the case where S = ".")
 ∩≍       ⊃  '△.     C2:take the non-zero-digit mask, and test if it is the same
                          as its shape
(this test passes only if the array is [1])
<                         test if C1 is true and C2 is false

More explanation on the C1 condition:

The input is a boolean vector. (where) on it collects the zero-based indices of ones, e.g. [1, 0, 1, 1, 0, 0, 1] becomes [0, 2, 3, 6]. The "logical negation" ¬ calculates 1-x for each value x in the array, e.g. [0, 2, 3, 6] becomes [1, -1, -2, -5].

For the input to equal its ¬⊚, the following conditions need to be met:

  • The lengths are equal. For a boolean vector input, generates a vector whose length is the count of ones in the input. To meet the length requirement, the input vector must be all ones.
  • The individual values are equal. Since the input is boolean, the output must be also boolean (either 0 or 1). ¬ maps 2 or higher to negative numbers, so the original input cannot contain a 1 at indices 2 or higher. This reduces the candidates to [], [1], and [1,1].

Now we can do an exhaustive check:

input -> ⊚ -> ¬⊚
[] -> [] -> []
[1] -> [0] -> [1]
[1,1] -> [0,1] -> [1,0]

Therefore ≍¬⊚. checks if the given boolean vector is either [] or [1].

\$\endgroup\$
1
  • \$\begingroup\$ Nice work. It took me way too long to figure out "the same as boolean negation of its nonzero indices," though--maybe it would help if you broke that part of the explanation into multiple steps? \$\endgroup\$
    – DLosc
    Nov 1, 2023 at 15:58
0
\$\begingroup\$

JavaScript (Node.js), 15 bytes

s=>-s!=0+s+'e0'

Try it online!

  • If s is number, then s==0 to make it false. e0 avoids another e in number(0e0).
  • If s is ., x or o, then -s is NaN
  • If s is 0 or 0 , then 0+s+0 is NaN

Assumes double handle enough logrange

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This approach returns false for the input "x", which should return true. I've added it as a test case. \$\endgroup\$
    – DLosc
    Nov 2, 2023 at 23:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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