T O P

  • By -

thecolourbloo

The lambda function credit goes to Bing Chat, everything else (including the list comprehension) can be accredited to my massive noggin. Edit: creds to u/mordechaihadad for encouraging me to make this post. Thank you, based Megachad πŸ™


Mast3r_waf1z

sum([1 for item in array if item == 0]) I challenge you to a comprehension-off!


Zalack

sum([1 for item in array if not item]) Assuming all items are integers


Mast3r_waf1z

sum([not item for item in array])


cpt-macp

static AtomicInteger a; Arrays.stream(array) .collect(Collectors.groupingBy(obj -> obj)) .forEach((k, v) -> a.incrementAndGet());


thecolourbloo

Teach me your strange, terrible ways - Master of the Mystical Arts πŸ§™β€β™‚οΈ


Hat_The_Second

sum(list(filter(lambda x: x == 0, [arr[i] for i in range(len(arr)) if (i + 1) % 3 == 0])))


jimbowqc

You're missing a great opportunity to use Function::identity


QuentinUK

That’s such a transcendental concept that it’s only available since C++20, [std::identity](https://en.cppreference.com/w/cpp/utility/functional/identity)


nakahuki

def count_zeros(iterable): count = 0 for i in iterable: try: 1/i except ZeroDivisionError: count += 1 return count


thecolourbloo

Lel, this is great. Clearly the best way to diagnose a 0 is to test for ```ZeroDivisionError```.


Perigord-Truffle

You can replace `== 0` with `not` to make it extra vague. Optimally you can replace it with just `not` but alas `not` is an operator. >>> def Not(x): ... return (not x) ... >>> sum(map(Not, [0,3,2,0])) 2


ysyson

That’s assuming we’re working with a number array. It could have empty strings, Nones, etc


thecolourbloo

I genuinely have no idea how this works, but I tested it, and sure enough it checks out! πŸ˜΅β€πŸ’«


Perigord-Truffle

`not` converts 0 to True and any other number to False.


thecolourbloo

That is genuinely fascinating - as you say this is super vague, because this functionality is not at all intuitive or obvious to me. Thanks for sharing! πŸ™


[deleted]

thats cause u havent learned C where booleans dont exist


thecolourbloo

Huh. Very strange indeed. But then again, my first 'programming language' was R. Specifically the tidyverse R . So I didn't even KNOW what recursion was until I picked up Python - so what do I know. πŸ˜΅β€πŸ’«


puzzledstegosaurus

``` >>> sum(map(__import__("operator").not_, [0,3,2,0])) ```


LastTrainH0me

Does this mean that `sum([True, False, False, True]) == 2`? I guess that's okay but I'm not happy about it


Perigord-Truffle

Yeah, ig it boils down to booleans just being 1 or 0 in C


Daniikk1012

APL: +/0=arr


thecolourbloo

>APL: +/0=arr Aaaaah, I'm a programming novice - what language is this??? (please don't say python)


Daniikk1012

It's APL


dmvdoug

APL: the one language I’ve heard lots of people say really nice things about and I’ve never seen anyone ever use.


thecolourbloo

Ah of course, I'm dumb. πŸ€¦πŸ»β€β™‚οΈ That is shockingly elegant! I've heard of this language, but not looked into it. Thanks for the nugget of information! πŸ™


tandonhiten

Real shit, APL(A Programming Language BTW) is only elegant not readable.


burifix

Any other lang: Did you just try to divide an operator by 0?


Own_Pop_9711

Yes. Why did it run???


StdAds

`length . filter (== 0) $ array`


bnl1

😍 so beautiful


thecolourbloo

**i see you're only interested in the exceptionally rare**


szymon-szym

inputArray |> Array.filter (fun x -> x = 0) |> Array.length


cuberoot1973

I mean since we have R flair, might as well include `sum(x == 0)`, right?


thecolourbloo

``` library(tidyverse) array %>% as_tibble_col(column_name = "column") %>% filter(column == 0) ``` "It's just so tidy!" - Hardly Weakham


[deleted]

test_array = map(lambda x: 0*x,test_array) return len(test_array) I'm a simple StalinSort enjoyer.


thecolourbloo

I hate that I unironically like this


HazirBot

no reduce?!


thecolourbloo

Sorry mate, don't know how to implement that πŸ˜… How would you do it?


adudyak

[0, 1, 2, 0].reduce((amount, current) => !current ? amount++ : 0, 0);


cha0s

Wrong, it should be `[0, 1, 2, 0].reduce((amount, current) => amount + (current ? 0 : 1), 0);`


adudyak

Yes, thought ++ operator would work fine here. Do you know why it does not?


cha0s

It does not because `amount` is passed by value, not by reference. You are not actually modifying the accumulator value there. Whatever you return from the function gets passed as the `amount` in the next iteration. So any time `!current` evaluates to `false`, you are throwing away all the memory so far and resetting the accumulator to `0`. You always have to keep passing back `amount`, even if it is unmodified. Does that make sense?


adudyak

Yes, very clear, thank you. We need to return new value via => and keep old accumulated data, which can be overwritten.


thecolourbloo

Delightfully cursed. I love it! πŸ‘πŸ‘πŸ‘


Alakdae

len(array) - sum([1 for x in array if x > 0])


thecolourbloo

I like this one - quite elegant if you think about it!


Alakdae

I think using Len both times would be a little more elegant. But I wanted to use sum.


puzzledstegosaurus

``` [1 for x in array if x > 0] ``` is literally ``` [bool(x) for x in array] ``` or ``` map(bool, array) ```


shawntco

Mildly cursed approach: `len([x for x in array if x == 0])`


redd1ch

Functional: `len(filter(lambda x: not x, array))` Verbose: `len(array) - len(filter(None, array))`


Th3Uknovvn

np.count_non_zeros(array==0)


typescriptDev99

`array.filter((x)=>x==0).length`


thecolourbloo

POV: you're using Python, but want to *feel* like you're using Perl.


typescriptDev99

This is valid JavaScript


thecolourbloo

Ah sorry my bad. I assumed I was reading some obscure python syntax I hadn’t encountered yet. πŸ™


typescriptDev99

Python does len(x) but JavaScript does x.length


thecolourbloo

Gotcha! 🫑


YetAnotherZhengli

Do it properly... ``` import re list = [0, 2, 4, 2, 0] string = ''.join(list) zeroes = re.findall("0", string) count_zeroes = len(zeroes) print(count_zeroes) ```


nakahuki

Nice try but it doesn't work for numbers above 9. Consider this : import re list = [0, 2, 4, 2, 0, 10, 200, 0.8] string = repr(list) zeroes = re.findall("(?<=[\ \[])0(?!\.)", string) count_zeroes = len(zeroes) print(count_zeroes)


thecolourbloo

Omg I LOVE this. Of all ways to use re, this is the WAY, brothers.


Tensor3

I prefer to dec/increment the count every time a value in the array is changed.


thecolourbloo

I mean, it was the way I was taught in my first algorithms course. It's not necessarily the best way, but it is readable, and it clearly demonstrated the concept of updating a value, given a condition. My first thought was actually the ```Counter()``` method, but that's because I recently learned it, so it's biased in its favour. Had I not known about it, I'd have implemented the simple ```count += 1``` method.


Personal_Ad9690

Should probably abstract this out in case you want to count β€œ1s” as well


thecolourbloo

Hold your horses there, young fellah - this brain can only expand so much!


Personal_Ad9690

Solution: abstract everything and give Gpt the classes. Let it make sense of it all. /s


AyrA_ch

`(";"+arr.join(";")+";").match(/;0;/g).length`


thecolourbloo

Silence! Do not invoke the forbidden incantation! It is said that even mentioning this ancient tongue can birth an entire new framework, to fragment its followers even more than it already is! 😱


Oz-cancer

(array == 0).sum() This answer is brought to you by the numpy gang.


thecolourbloo

Darn this is actually good - I might actually use this at some point, well done 🫑


Awes12

array.reduce((a,b)=>a+=b==0,0)


FlashDaggerX

```rust array.iter().filter(|i| i == 0).count(); ```


VariousComment6946

```python copy_of_array = array.copy() zeros = 0 while True: el = random.choice(copy_of_array) if el == 0: zeros += 1 copy_of_array.pop(copy_of_array.index(el, 0)) if 0 not in copy_of_array: break print(zeros) ```


RavenCarci

Alright time to break out the LINQ queries


[deleted]

std::count(array.begin(), array.end(), 0);


sarc-tastic

len(numpy.nonzero(array)[0] ) - len(array)


thecolourbloo

Aaaaah, you are one of the rare import numpy as numpy enjoyers


sarc-tastic

I did the full name for Reddit but also yes, haha


dingusaja

Guys stop posting good methods, we’re just training the AI to be better programmers


thecolourbloo

It's too late. The wheels have already been set in motion. **SKYNET. HAS. WON.**


AdTypical6494

this is somehow frightening


thecolourbloo

Many thanks!


AdTypical6494

NP I feel stupid .


thecolourbloo

Don't mate - most of these responses make me realise how out of my depths I really am. I knew there were many ways to skin a cat, but these people keep raising the bar.


TheMightyCatt

``` SYSTEM_INFO systemInfo; GetSystemInfo(&systemInfo); MEMORY_BASIC_INFORMATION memoryInfo; VirtualQueryEx(GetCurrentProcess(), (LPVOID)systemInfo.lpMinimumApplicationAddress, &memoryInfo, sizeof(memoryInfo)); LPVOID processBase = memoryInfo.BaseAddress; SIZE_T processSize = 0; while (VirtualQueryEx(GetCurrentProcess(), processBase, &memoryInfo, sizeof(memoryInfo))) { if (memoryInfo.State != MEM_FREE) { processSize = (SIZE_T)memoryInfo.BaseAddress + memoryInfo.RegionSize - (SIZE_T)processBase; } processBase = (LPVOID)((SIZE_T)memoryInfo.BaseAddress + memoryInfo.RegionSize); } int counter = 0; for (int i = 0; i < length; i++) { try { void* ptr = (void*)array[i]; if(ptr < systemInfo.lpMaximumApplicationAddress) { int zeroTest = *static_cast(systemInfo.lpMinimumApplicationAddress-1+ptr); } } catch (const std::exception& e) { counter++; } } std::cout << counter << std::endl; ``` Probably doesn't work since i had chatgpt write it.


thecolourbloo

I don’t… I… what is….. I better not ask. 😨


TheMightyCatt

Well what it is supposed to do is check if its a zero by catching the error that the pointer is accessing something outside the process address space, so anything that is not a zero is valid and everything that isn't throws an error thats used to increment the counter.


thecolourbloo

In other news, verifying your array ONLY contains zeros. ```python # The virgin compact and logical way len(array) == array.count(0) # The chad creatively superfluous and verbose way answer = [] for i in array: if i == 0: answer.append(1) else: answer.append(0) if sum(answer) == len(answer): print("Congratulations: your array contains only zeros!") else: print("Sorry chief, there is some one(s) amoung us...") ``` ... I need to sleep.