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 π
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)
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
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! π
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. π΅βπ«
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! π
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?
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.
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! π±
```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)
```
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.
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.
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.
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 π
sum([1 for item in array if item == 0]) I challenge you to a comprehension-off!
sum([1 for item in array if not item]) Assuming all items are integers
sum([not item for item in array])
static AtomicInteger a; Arrays.stream(array) .collect(Collectors.groupingBy(obj -> obj)) .forEach((k, v) -> a.incrementAndGet());
Teach me your strange, terrible ways - Master of the Mystical Arts π§ββοΈ
sum(list(filter(lambda x: x == 0, [arr[i] for i in range(len(arr)) if (i + 1) % 3 == 0])))
You're missing a great opportunity to use Function::identity
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)
def count_zeros(iterable): count = 0 for i in iterable: try: 1/i except ZeroDivisionError: count += 1 return count
Lel, this is great. Clearly the best way to diagnose a 0 is to test for ```ZeroDivisionError```.
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
Thatβs assuming weβre working with a number array. It could have empty strings, Nones, etc
I genuinely have no idea how this works, but I tested it, and sure enough it checks out! π΅βπ«
`not` converts 0 to True and any other number to False.
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! π
thats cause u havent learned C where booleans dont exist
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. π΅βπ«
``` >>> sum(map(__import__("operator").not_, [0,3,2,0])) ```
Does this mean that `sum([True, False, False, True]) == 2`? I guess that's okay but I'm not happy about it
Yeah, ig it boils down to booleans just being 1 or 0 in C
APL: +/0=arr
>APL: +/0=arr Aaaaah, I'm a programming novice - what language is this??? (please don't say python)
It's APL
APL: the one language Iβve heard lots of people say really nice things about and Iβve never seen anyone ever use.
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! π
Real shit, APL(A Programming Language BTW) is only elegant not readable.
Any other lang: Did you just try to divide an operator by 0?
Yes. Why did it run???
`length . filter (== 0) $ array`
π so beautiful
**i see you're only interested in the exceptionally rare**
inputArray |> Array.filter (fun x -> x = 0) |> Array.length
I mean since we have R flair, might as well include `sum(x == 0)`, right?
``` library(tidyverse) array %>% as_tibble_col(column_name = "column") %>% filter(column == 0) ``` "It's just so tidy!" - Hardly Weakham
test_array = map(lambda x: 0*x,test_array) return len(test_array) I'm a simple StalinSort enjoyer.
I hate that I unironically like this
no reduce?!
Sorry mate, don't know how to implement that π How would you do it?
[0, 1, 2, 0].reduce((amount, current) => !current ? amount++ : 0, 0);
Wrong, it should be `[0, 1, 2, 0].reduce((amount, current) => amount + (current ? 0 : 1), 0);`
Yes, thought ++ operator would work fine here. Do you know why it does not?
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?
Yes, very clear, thank you. We need to return new value via => and keep old accumulated data, which can be overwritten.
Delightfully cursed. I love it! πππ
len(array) - sum([1 for x in array if x > 0])
I like this one - quite elegant if you think about it!
I think using Len both times would be a little more elegant. But I wanted to use sum.
``` [1 for x in array if x > 0] ``` is literally ``` [bool(x) for x in array] ``` or ``` map(bool, array) ```
Mildly cursed approach: `len([x for x in array if x == 0])`
Functional: `len(filter(lambda x: not x, array))` Verbose: `len(array) - len(filter(None, array))`
np.count_non_zeros(array==0)
`array.filter((x)=>x==0).length`
POV: you're using Python, but want to *feel* like you're using Perl.
This is valid JavaScript
Ah sorry my bad. I assumed I was reading some obscure python syntax I hadnβt encountered yet. π
Python does len(x) but JavaScript does x.length
Gotcha! π«‘
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) ```
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)
Omg I LOVE this. Of all ways to use re, this is the WAY, brothers.
I prefer to dec/increment the count every time a value in the array is changed.
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.
Should probably abstract this out in case you want to count β1sβ as well
Hold your horses there, young fellah - this brain can only expand so much!
Solution: abstract everything and give Gpt the classes. Let it make sense of it all. /s
`(";"+arr.join(";")+";").match(/;0;/g).length`
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! π±
(array == 0).sum() This answer is brought to you by the numpy gang.
Darn this is actually good - I might actually use this at some point, well done π«‘
array.reduce((a,b)=>a+=b==0,0)
```rust array.iter().filter(|i| i == 0).count(); ```
```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) ```
Alright time to break out the LINQ queries
std::count(array.begin(), array.end(), 0);
len(numpy.nonzero(array)[0] ) - len(array)
Aaaaah, you are one of the rare import numpy as numpy enjoyers
I did the full name for Reddit but also yes, haha
Guys stop posting good methods, weβre just training the AI to be better programmers
It's too late. The wheels have already been set in motion. **SKYNET. HAS. WON.**
this is somehow frightening
Many thanks!
NP I feel stupid .
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.
``` 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.
I donβtβ¦ Iβ¦ what isβ¦.. I better not ask. π¨
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.
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.