#esoteric-python
1 messages ยท Page 34 of 1
map(int,*input()[::2])```
something like this
!e ```py
print(*map(int,"2 2"[::2]))
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
2 2
sure it works
*map(int,input()[::2])
we did it! cheers
oh shit just works for numbers with one digit
something like "10 5" wouldnt work" XD
duh lol
that would be back to partition
it takes a callable and iterable
literal int is callable and list[str] (from str.split()) is iterable
isnt int a class
you can call int like int("2"), so it's a callable
thanks guys :p
!e py print(list[str].append("123"))
@magic wraith :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(list[str].append("123"))
004 | ^^^^^^^^^^^^^^^^^^^^^^^
005 | TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'str' object
How does this bot interpret code?
I feel like it could be exploitable by running malicious code or libraries
!help eval
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.
Currently only 3.11 version is supported.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
I know it's eval but surely anything that can run code could theoretically be exploited
Because a system still has to take the input
See the last paragraph
A lot of effort has been put into sandboxing the command
Lots of people have tried breaking it in #bot-commands
A couple people have been able to burn it down, but AFAIK no one has ever successfully exploited it in a malicious way
True
Your code is passed to an API that creates an entirely new system shell in a stripped down security shelled called โNSJailโ, and then created a restricted Python process inside of that
Yeah, go ahead
https://leetcode.com/problems/plus-one/submissions/1057792968/ can I make it even shorter?
[*map(int,[*str(int(''.join(map(str,digits)))+1)])]```
Why unpack it into a list before passing it to map
Strings are iterable
didn't think of that
[*map(int,str(int(''.join(map(str,digits)))+1))]```
-3 chars
The link doesn't load for me
all that's left is the header
Is it adding 1 to a number as a list of digits?
i think
yep
yes
int(str(digits)[1::3]) instead of ''.join?
hmmm
is that faster?
str.join should be fairly fast
probably not
but it's shorter
[*map(int,str(int(str(digits)[1::3])+1))]
[*map(int,str(int(''.join(map(str,digits)))+1))]
oh true
!tipy [*map(int,str(int(''.join(map(str,[1,2,3])))+1))]
@arctic skiff :white_check_mark: Your 3.11 timeit job has completed with return code 0.
200000 loops, best of 5: 1.57 usec per loop
!ti```py
[*map(int,str(int(str([1,2,3])[1::3])+1))]
@arctic skiff :white_check_mark: Your 3.11 timeit job has completed with return code 0.
200000 loops, best of 5: 1.34 usec per loop
@versed eagle
Btw if you actually care about speed then you should just add 1 to index 0 and then handle the "overflow" with a loop.
That will basically be instant unless the number ends with 999...
interesting
yeah but that's boring
that will be a lot slower in practice on small inputs
!ti
A = [1,2,3]
A[-1] += 1
if A[-1] == 10: # Happens 1 in 10 times
pass # Add overflow code here
@distant salmon :white_check_mark: Your 3.11 timeit job has completed with return code 0.
1000000 loops, best of 5: 218 nsec per loop
I wouldnt be so sure about that
!e ```py
def addOne(d):
d[-1]+=1
if d[-1]==10:
return addOne(d[:-1])+[0]
return d
print(addOne(list(range(5))))
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
[0, 1, 2, 3, 5]
It dies if all the digits are 9
!e
def addOne(d):
d[-1]+=1
i = len(d) - 1
while i and d[i] == 10:
d[i] = 0
i -= 1
d[i] += 1
if d[0] == 10:
d[0] = 0
d.insert(0, 1)
return d
print(addOne([1,2,3,4,5]))
print(addOne([9,9,9]))
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [1, 2, 3, 4, 6]
002 | [1, 0, 0, 0]
!ti
def addOne(d: list[int]) -> list[int]:
for i in range(len(d)-1,-1,-1):
if d[i] < 9:
d[i] += 1
break
d[i] = 0
else:
d.insert(0, 1)
return d
print(addOne([9,9,9]))
@orchid nymph :white_check_mark: Your 3.11 timeit job has completed with return code 0.
100000 loops, best of 5: 2.32 usec per loop
!ti
def addOne(d):
for i in range(len(d)-1,-1,-1):
if d[i] < 9:
d[i] += 1
break
d[i] = 0
else:
d.insert(0, 1)
return d
addOne([1,2,3])
@orchid nymph :white_check_mark: Your 3.11 timeit job has completed with return code 0.
500000 loops, best of 5: 592 nsec per loop
!ti
d=[1,2,3]
for i in range(len(d)-1,-1,-1):
if d[i] < 9:
d[i] += 1
break
d[i] = 0
else:
d.insert(0, 1)
@orchid nymph :white_check_mark: Your 3.11 timeit job has completed with return code 0.
500000 loops, best of 5: 423 nsec per loop
!ti
d=[9,9,9]
for i in range(len(d)-1,-1,-1):
if d[i] < 9:
d[i] += 1
break
d[i] = 0
else:
d.insert(0, 1)
@orchid nymph :white_check_mark: Your 3.11 timeit job has completed with return code 0.
500000 loops, best of 5: 591 nsec per loop
!ti
d=[9,9,9]
for i in range(len(d))[::-1]:
if d[i] < 9:
d[i] += 1
break
d[i] = 0
else:
d.insert(0, 1)
I've always been a fan of using slicing like this to reverse ranges
@distant salmon :white_check_mark: Your 3.11 timeit job has completed with return code 0.
500000 loops, best of 5: 755 nsec per loop
ow yeah I forgot that range slicing is very fast because it returns a range
Another nice feature of ranges is that they support len
So you don't have to try to come up with a math formula
!e range(1,10)[3]
@fleet bridge :warning: Your 3.11 eval job has completed with return code 0.
[No output]
ranges works like lists of integers that satisfies some constraints
therefore ranges supports all list "readonly" operation, because these operations cannot break the constraints
!e print(range.dict.keys())
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
dict_keys(['__new__', '__repr__', '__hash__', '__getattribute__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__iter__', '__bool__', '__len__', '__getitem__', '__contains__', '__reversed__', '__reduce__', 'count', 'index', 'start', 'stop', 'step', '__doc__'])
!e
del import('sys').modules['builtins']
print("it shouldnt work...")
@stark granite :white_check_mark: Your 3.11 eval job has completed with return code 0.
it shouldnt work...
???
Builtins will be repopulated in some cases
it should throw RuntimeError tho
hm
!e
import sys
for module in sys.modules.copy():
del sys.modules[module]
print("test")
@stark granite :white_check_mark: Your 3.11 eval job has completed with return code 0.
test
repl relies on a lot of random stuff, no wonder it throws
!e
del __builtins__.__import__
import sys
@orchid nymph :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | ImportError: __import__ not found
!e
__builtins__.__import__ = lambda n,*_: n
import lol
print(lol)
@orchid nymph :white_check_mark: Your 3.11 eval job has completed with return code 0.
lol
Yo yall
How can I make certain code execute every time my program errors, (raises an unhandled exception)
if your goal is to catch the exception then just wrap it all in a try/except, if your goal is to print extra data when there is an exception you can use sys.excepthook
!d sys.excepthook
sys.excepthook(type, value, traceback)```
This function prints out a given traceback and exception to `sys.stderr`.
When an exception other than [`SystemExit`](https://docs.python.org/3/library/exceptions.html#SystemExit) is raised and uncaught, the interpreter calls `sys.excepthook` with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to `sys.excepthook`.
!e
builtins.import = lambda *stuff: print(stuff)
import lol
print(lol)
Hi, thanks for responding. I dont really want to wrap it all in try blocks, as it will make my code WAY too confusing to navigate. I have classes and functions in different files, and it doesn't catch when wrapping my main() func in try blocks
!e
builtins.import = lambda *stuff: print(stuff, [type(thing) for thing in stuff])
import lol
print(lol)
@stark granite :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ('lol', {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f8e44350d50>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/main.py', '__cached__': None}, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f8e44350d50>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/main.py', '__cached__': None}, None, 0)
002 | None
!e
exec(bytes(ord(c)%i+32 for c in'๒
๒ญ๐๐ชฃ๑ญ๒๒บ๓๒ฏฅ๑ป๑ผ๒คญ๓ฑ๓ธ๓ฑ๒ซจ็งต๒พถข๓ถ๐ฐญ๑ฌ๓ญผ๒ฏฅ๑ป๐ฟ๒คญ๒งฑ๓๐ป๑ธฃ๐บธฒ๐ฃด๓ฟ๒ญฝผ๓ณ๒ตฅจ๓ฐ๒ฝ๓ค๐๓ฉช๑ฎชท๒ก๓๓น๒ฃคฟ๓นฎ๐ฆ๑พ๑ค๐ฎฟ๑ถ
๐ซขพ๓ฑ๒ก
ๅป๐กฑ๐ฎ
ก๒ฐ๐ฆ๒ทถ๒ฟฐ๓ฒโ๓ฒ๒ช๑ณขช๓พ ๑ตช้ฝ็ซผ๊ต๓พ๐ฃ ๒ธก๒น
์๒ฆด๐ฌญๅ๑ฎฃธไฅ๒ขง๓ขณ๓กฌ๒ถ๑ฆฟ๓ฏ๐ฅ๑ทฎ๓ธ๒ฆด๐ฌญ๐ฒ๑ธฃ๑ถซ'for i in b'efg'))
import five.nine.minus.one.three as result
print(result)
@orchid nymph :white_check_mark: Your 3.11 eval job has completed with return code 0.
46
!e
builtins.import = lambda *stuff: print(stuff, [type(thing) for thing in stuff])
import lol
print(lol)
@stark granite :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ('lol', {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fab0a5bccd0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/main.py', '__cached__': None}, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fab0a5bccd0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/main.py', '__cached__': None}, None, 0) [<class 'str'>, <class 'dict'>, <class 'dict'>, <class 'NoneType'>, <class 'int'>]
002 | None
can you give a normal variant of this code pls
!e
def func(name: str, *_):
class C(int):
def __getattr__(self,n):
return self
return C(eval("".join(
{
"zero": "0",
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"plus": "+",
"minus": "-",
"multipled_by": "*",
"divided_by": "//",
"modulo": "%",
"power": "**",
}.get(part.lower(),"?")
for part in name.split(".")
)))
__builtins__.__import__ = func
import one.plus.one
print(one.plus.one)
there you go, semi readable version
thanks
@orchid nymph :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
Without the try/except, it is difficult for the interpreter to know when to stop propagating the exception, but if your goal is just to do something before the program exits due to the uncaught exception you can use sys.excepthook
how does this work?
seems like it's converting one.plus.one -> ["one", "plus", "one"] -> "1+1" and evaling it to return 2
and 4@ is just overriding import so it uses their own class for this
!e
def hijack_import(name, *_):
print(f"We are hijacking the import of {name}")
return 1
# Make `import test` run `hijack_import(test)` instead of default behavior
__builtins__.__import__ = hijack_import
import test
print(test)
@formal latch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | We are hijacking the import of test
002 | 1
thanks
!e This crashes my idle, let's try here ```py
B = builtins
B.import, B.print = B.print, B.import
print(math)
import math.sqrt```
!e ```py
B = builtins
B.import, B.print = B.print, B.import
print('math')
import math.sqrt```
@magic wraith :white_check_mark: Your 3.11 eval job has completed with return code 0.
math.sqrt {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f4604820d50>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/main.py', '__cached__': None, 'B': <module 'builtins' (built-in)>} {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f4604820d50>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/main.py', '__cached__': None, 'B': <module 'builtins' (built-in)>} None 0
!e py print("".join([chr(getattr(__builtins__,"".join([chr(_)for(_)in[108,101,110]]))(_))for(_)in"โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ".split()])) how can i make this better
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello World!
better in what way
i want it to be short as i can but also confusing
as short as possible is just print("hello, world")
confusing is subjective
you know what i mean
bruh
!e import __hello__
@unique heath :warning: Your 3.11 eval job has completed with return code 0.
[No output]
thats boring, you just switched import and print
!e py print("".join([chr(getattr(__builtins__,"".join(map(chr,[108,101,110])))(_))for(_)in"โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ".split()]))
@ashen adder :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello World!
!e ```py
print('a')
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
b
i dont get it
what is happening?
you are calling len with one empty string, then chr'ing it and joining
where hello world came from
the empty string isn't empty would be my guess
.split will return [""] in that case
its full of unicode trickery
except there are some whitespace-looking non-whitespace chars
i checked
!charinfo " "
its 1096 characters in total
my discord client copied it incorrectly
there's a ton of invisible characters in it
!e ```py
print(len("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"))
... i forgot a parentheses :c
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
1096
but yeah there's unicode trickery going on here
"short" :P
!e ```py
from ctypes import c_void_p as v
def sf(a, b, o__={}):
md = v.from_address(id(a) + 16)
vc = v.from_address(id(a) + 48)
if id(a) not in o__:
o__[id(a)] = (md.value, vc.value)
if id(b) in o__:
nmd, nvc = o__[id(b)]
else:
nmd = v.from_address(id(b) + 16).value
nvc = v.from_address(id(b) + 48).value
md.value, vc.value = nmd, nvc
def sw(a, b):
sf(a, b); sf(b, a)
sw(import, print)
import(f"{print('math') = }")
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
print('math') = <module 'math' from '/lang/python/default/lib/python3.11/lib-dynload/math.cpython-311-x86_64-linux-gnu.so'>
a more interesting way to switch the functions
can it be used with import keyword tho?
import just uses __builtins__.__import__
yes
why wouldn't it be able to?
!e ```py
from ctypes import c_void_p as v
def sf(a, b, o__={}):
md = v.from_address(id(a) + 16)
vc = v.from_address(id(a) + 48)
if id(a) not in o__:
o__[id(a)] = (md.value, vc.value)
if id(b) in o__:
nmd, nvc = o__[id(b)]
else:
nmd = v.from_address(id(b) + 16).value
nvc = v.from_address(id(b) + 48).value
md.value, vc.value = nmd, nvc
def sw(a, b):
sf(a, b); sf(b, a)
sw(import, print)
import hello
import(hello)
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
<module '__hello__' (frozen)>
no
def multiply_matrices(x, y):
u,l=list,len
o,p,r=u(set([l(r)for r in x])),u(set([l(r)for r in y])),range
return[[sum([prod((x[k][i],y[i][j]))for i in r(o[0])])for j in r(p[0])]for k in r(l(x))]if not((l(o),l(p))!=(1,1)or o[0]!=l(y)or p[0]!=l(x))else None```
my attempt at golfing matrices multiplication
assume the function prod exists
what can we do to further golf it
I mean there is probably some math shit you can do
but I am talking python wise
Replace set([...]) with {...}
smart
The sum doesn't need ([, can just be (
You can probably rewrite the last line to not return None explicitly
Is your goal to make it as unreadable as possible
It's golfing, so the goal is to make it as short as possible.
I was gonna golf it even more but my keyboard broke ๐ฉ
- avoid range if possible
zip(*y)is basically y^Taandbare the vectors to dot product- you could also do
map(prod,zip(a,b))instead ofsum(i*j for i,j in zip(a,b))assuming it's defined ofc
set([l(r)for r in x])->{*map(l,x)}x if cond else y->(y,x)[cond]- lambda
l=len
multiply_matricies=lambda x,y:(None,[[sum(i*j for i,j in zip(a,b))for a in x]for b in zip(*y)])[1==l({*map(l,x)})==l({*map(l,y)})and l(x[0])==l(y)and l(y[0])==l(x)]
can you golf this code for me?
n,m=map(int,input().split())
print('a'*(n-m),*map(chr,range(97,97+m)),sep='')
what does it do?
um..
!e ```py
n,m=5,10
print('a'*(n-m),*map(chr,range(97,97+m)),sep='')
@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
abcdefghij
and the optimal method is to spam A's at the start?
!e ```py
n,m=10,5
print('a'*(n-m),*map(chr,range(97,97+m)),sep='')
@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
aaaaaabcde
def mat_mul(m1, m2):
m2 = list(zip(*m2))
return [[sum(a*b for a,b in zip(m1_row, m2_col)) for m2_col in m2] for m1_row in m1]
without golfing any names
!e
n,m=10,5
print('a'*(n-m)+bytes(range(97,97+m)).decode())
@orchid nymph :white_check_mark: Your 3.11 eval job has completed with return code 0.
aaaaaabcde
Does this also return none when the dimensions don't match?
!e
n,m=10,5
while n:print(end=chr(97-min(0,n-m)));n-=1
@orchid nymph :white_check_mark: Your 3.11 eval job has completed with return code 0.
aaaaaabcde
it does not
Does anyone have a solution from other mindsets of programming?
The exercise requires writing a function that takes 7 or 8 and prints 8 or 7 respectively.
def f(x):
print(7 if x == 8 else 8)
def f(x):
print([8, 7][x - 7])
def f(x):
print(15 - x)
def f(x):
print(x ^ 15)
don't the bottom 3 fail on any input other than 7 or 8? or is validation not a concern for these 
ig the first does too
nvm
The assumption is that it takes either 7 or 8
And if it was a low level language, one byte (sign doesn't matter in this case I guess)
wdym, other mindsets?
>>> def f(x): print(chr(63 - x))
>>> f(7)
8
>>> f(8)
7
that's the same as 15 - x except it uses uchars instead of uint8s
well yeah
I mean there aren't gonna be any better solutions
but it's a different path of getting to the same result
>>> def f(x): print(x - 7 and 7 or 8)
...
>>> f(8)
7
>>> f(7)
8
what im saying is that its not really different
codegolf is always the best answer
I like 15-x a tiny bit more since it also works for floating point numbers
The dict solutions also work for floating point input
15-x works for ints and floats, and for numbers other than 7 or 8, and can easily be done for other number pairs
i like x^15 more because it uses some special property of 7 and 8
btw x=1-x is often done to swap 0 and 1
The subtraction trick works much more in general, to swap any numbers a and b, you can just do
(a + b) - x
Thats why I like it
what's x?
>>> def f(x): print(sum([7,8],start=-x))
...
>>> f(7)
8
>>> f(8)
7
i dont understand it
7+[7,8].index(x)
7+[8,7].index(x)
scroll up
Shouldnt it be 7+[8,7].index(x)?
you guys swapping 8 and 7?
that actually returns the same number ๐
We are on a quest to solve a very difficult problem, yes
>>> def f(x): print(-(x >> 3) + 8)
...
>>> f(8)
7
>>> f(7)
8
that's what the xor solution does pretty much
yeha
>>> def f(x): print(7+x%2)
...
>>> f(8)
7
>>> f(7)
8
x+ord(str(x))%4//3
please check that, my brain's interpreter is not good enough today
(this is what my solution does, pretty much)
>>> def f(x): print(x+ord(str(x))%4//3)
...
>>> f(7)
8
>>> f(8)
8
aaa

think 4//3 goes off before mod
It doesn't
Mod, multiplication and division has the same priority
Pretty sure about that
im stoopid, it is doing 7+1 and 8+0, so it is always 8
!e
for x in 7,8:
print(7+0**(x&8))
x-1+ord(str(x))%7//3
this should work
@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8
002 | 7
!e
for x in 7,8:
print(x-1+ord(str(x))%7//3)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8
002 | 7
yay
>>> def f(x): print(*({x} ^ {7,8}))
...
>>> f(8)
7
>>> f(7)
8
({x}^{7,8}).pop() also should work
sorted([7,8],key=x.__eq__)[0]
range(x,30-3*x,15-2*x)[1]
next(filter(x.__ne__,[7,8]))
we want to swap em
Oh yeah right
>>> def f(x): print(__import__('functools').reduce(lambda x,y: x ^ y, [x,7,8]))
...
>>> f(8)
7
>>> f(7)
8
i like that
oh wait, (a^b)^x works for every a,b pair, not only for those which has no common set bits (idk why i thought so)
so 15^x can be extended to a^b^x just like 15-x can be extended to a+b-x
I didn't think about that either, the similarity there
this one has two smiley faces :)
8-(
8)
๐ค
>>> -~-~-~-~-~-~-~(7 >> 3 ^ 1)
8
>>> -~-~-~-~-~-~-~(8 >> 3 ^ 1)
7
!e ```py
i forgot how this operation is called
def G(x,y): return 1/(1/x+1/y)
for x in 7,8:
print(1/(1/G(G(7,8),x)-1/G(7,8)))
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 7.0
002 | 8.0
!e ```py
def G(x,y): return 1/(1/x-1/y)
for x in 7,8:
print(G(G(7,-8),x))
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8.0
002 | 7.0
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8.0
002 | 7.0
!e ```py
from math import *
for x in 7,8:
print(exp(log(7)+log(8)-log(x)))
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 7.999999999999995
002 | 6.999999999999998
almooost
avg float shenanigans
!e
from math import *
for x in 7,800001:
print(exp(log(7)+log(8)-log(x)))```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 7.999999999999995
002 | 6.999991250010937e-05
match x:
case 7:
return 8
case 8:
return 7
try:
1/(7-x)
except:
return 8
else:
return 7
!e (the same as 7*8/x) ```py
from math import *
for x in 7,8:
print(lcm(7,8)//x)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8
002 | 7
!e ```py
from math import *
for x in 7,8:
print(8-(gcd(14,x)-2)//5)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 7
002 | 8
hello, identity function
!e ```py
from math import *
for x in 7,8:
print(7+(gcd(14,x)-2)//5)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8
002 | 7
!e ```py
from math import *
for x in 7,8:
print(3+gcd(14,x)**2%11)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8
002 | 7
!e ```py
from math import *
for x in 7,8:
print(4+factorial(x)%13//2)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8
002 | 7
!e ```py
from ctypes import *
for x in 7,8:
print(py_object.from_address(id(7)+id(8)-id(x)))
@fleet bridge :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
!e py_object dereferences the address passed in to a pointer. It's a bit like PyObject**, you can use _ctypes.PyObj_FromPtr to run that code ```py
from _ctypes import PyObj_FromPtr
for x in 7,8:
print(PyObj_FromPtr(id(7)+id(8)-id(x)))
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8
002 | 7
harmonic mean
this entire timeline is your fault ๐ฟ
๐ฟ
!e
def f(x):print(x^15)
*map(f,(7,8)),
@orchid nymph :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8
002 | 7
!e
import einspect
@einspect.impl(int)
def __eq__(self):
return self == 8 or self == 7
print(8 == 7)```
@unique heath :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | @einspect.impl(int)
004 | ^^^^^^^^^^^^^^^^^^
005 | File "/snekbox/user_base/lib/python3.11/site-packages/einspect/views/view_type.py", line 265, in wrapper
006 | t_view[name] = func
007 | ~~~~~~^^^^^^
008 | File "/snekbox/user_base/lib/python3.11/site-packages/einspect/views/view_type.py", line 407, in __setitem__
009 | with self.as_mutable():
010 | File "/lang/python/default/lib/python3.11/contextlib.py", line 144, in __exit__
011 | next(self.gen)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/S7BMMF5CMVBJR6NOO4FE4BFATE
awws
almost, harmonic mean has 2 in numerator
I guess it's also the l-1 norm
!e
x = lambda x: x*3
print(x(9))
@still totem :white_check_mark: Your 3.11 eval job has completed with return code 0.
27
def f(*a, **kwa):
return something``````py
f = lambda *a, **kwa: something```
Hi, I dont know where to ask this, but in a python dataframe, how do I compare 3 columns if to check if they have null values at the same places. The other values are all different categorical ones. I need to write a command which will give me True if all the three columns have null at the same rows.
this is the wrong channel
use pygen or #databases maybe
Is there anyway to bypass enforced types from dunder methods?
ex. allow for contains to return non booleans
v = res ? Py_True : Py_False;//skip tihs
!e again, __contains__ isn't the issue, it's the __bool__ that gets called by the in keyword
class Foo:
def __contains__(self, item):
return Bar()
class Bar:
def __bool__(self):
return 2
f = Foo()
print(f.__contains__(1))
print(1 in f)
@low lynx :x: Your 3.11 eval job has completed with return code 1.
001 | <__main__.Bar object at 0x7f37aa048090>
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 9, in <module>
004 | print(1 in f)
005 | ^^^^^^
006 | TypeError: __bool__ should return bool, returned int
Clarification: Bypass enforced types from magic methods, ex. __bool__,__int__,__str__, etc.
What I mean by magic
class T:
def __init__(self):
self.__add__=lambda s,x:x+1
def __add__(self,x):
return x+2
T()+1#3
!e```py
class T:
def init(self):
self.add=lambda s,x:x+1
print(T()+1)
@olive beacon :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 4, in <module>
003 | print(T()+1)
004 | ~~~^~
005 | TypeError: unsupported operand type(s) for +: 'T' and 'int'
self.__add__ (or any other magic method) doesn't work like that, because they are looked up on the class only, unlike normal methods.
I.e. x + y doesn't do x.__add__(y), but rather something like type(x).__add__(x, y).
can't skip that
unless you do some machine code modifying
I am aware, I was demonstrating that behavior
ok thanks
any information on when einspect.impl come to 3.12
!e
import einspect
@einspect.impl(str)
def thingy(self):
print("test")
'123'.thingy()
@karmic pumice :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 7, in <module>
003 | '123'.thingy()
004 | ^^^^^^^^^^^^
005 | AttributeError: 'str' object has no attribute 'thingy'
so join 2 first items with , then add a space and then join by x's?
a,b,*s=s.split();s=a+','+b+" "+"x".join(s[2:])
i wanted to do stuff with enumerate but it gets worse
long word
are we assuming that there are at least 2 elements?
presumably
!e ```py
import fishhook
@fishhook.hook(str)
def thingy(self):
print("test")
'123'.thingy()
import sys;print(sys.version)
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | test
002 | 3.12.0 (main, Oct 3 2023, 03:05:14) [GCC 12.2.0]
sweet fishhook works
โจ
3.11 eval but actually 3.12
Task:
You have to get a string as an input of your code. Output whether the string contains any of "aeiou", if yes how many times, and where. Use proper output messages, and try to be as concise as possible!
My attempt:
s = input("Give a string!\n\t> ").lower()
print("\n".join(["\n".join(["",f"{'-'*30} Char: "+i, "Contains" if i in s else "Doesn't contain", str(s.count(i))+" times", "At places: "+", ".join([str(ind+1) for ind,j in enumerate(s) if j == i])][:(6 if i in s else 3)]) for i in "aeiou"]))
To begin with, you can change a load of spaces: py s=input("Give a string!\n\t> ").lower() print("\n".join(["\n".join(["",f"{'-'*30} Char: "+i,"Contains"if i in s else"Doesn't contain",str(s.count(i))+" times","At places: "+", ".join([str(ind+1)for ind,j in enumerate(s)if j==i])][:(6if i in s else 3)])for i in"aeiou"]))
And x if y else z -> [x,z][y]
And str(x)+"y" -> f"{x}y"
That leaves us with
s=input("Give a string!\n\t> ").lower()
print("\n".join(["\n".join(["",f"{'-'*30} Char: "+i,["Doesn't contain",f"Contains {s.count(i)} times"][i in s],"At places: "+", ".join([str(n+1)for n,j in enumerate(s)if j==i])][:[3,6][i in s]])for i in"aeiou"]))
"Contains" if i in s else "Doesn't contain"
i in s and"Contains"or"Doesn't contain"
"Contains"*(i in s)or"Doesn't contain"
Can get a few characters with unpacking as well
s=input("Give a string!\n\t> ").lower()
print(*["\n".join(["",f"{'-'*30} Char: "+i,["Doesn't contain",f"Contains {s.count(i)} times"][i in s],"At places: "+", ".join([f"{n+1}"for(n,j)in enumerate(s)if j==i])][:[3,6][i in s]])for(i)in"aeiou"])
242 (yours) ```py
s=input("Give a string!\n\t> ").lower()
print(*["\n".join(["",f"{'-'*30} Char: "+i,["Doesn't contain",f"Contains {s.count(i)} times"][i in s],"At places: "+", ".join([f"{n+1}"for(n,j)in enumerate(s)if j==i])][:[3,6][i in s]])for(i)in"aeiou"])
226 ```py
s=input("Give a string!\n\t> ").lower()
for(n,c)in zip(map(s.count,v:="aeiou"),v):print('-'*30+' Char: '+c,n and f"Contains {n} times\nAt places: "+", ".join(str(i+1)for(i,j)in enumerate(s)if j==c)or"Doesn't contain",sep='\n')
wait actually
225
s=input("Give a string!\n > ").lower()
for(n,c)in zip(map(s.count,v:="aeiou"),v):print('-'*30+' Char: '+c,n and f"Contains {n} times\nAt places: "+", ".join(str(i+1)for(i,j)in enumerate(s)if j==c)or"Doesn't contain",sep='\n')
you can embed the tab byte directly for more shortness :>
<TAB> is 1 byte, \t is 2
aw discord replaces it with spaces
very sad
oh well
its still possible
... why are we using .lower()?
that would mean if the user inputs AEIOU it will say that it contains all the letters despite the original string not containing any of aeiou
that seems like a bug
218, bug fix
s=input("Give a string!\n\t> ")
for(n,c)in zip(map(s.count,v:="aeiou"),v):print('-'*30+' Char: '+c,n and f"Contains {n} times\nAt places: "+", ".join(str(i+1)for(i,j)in enumerate(s)if j==c)or"Doesn't contain",sep='\n')
209
s=input("Give a string!\n\t> ")
for c in(v:="aeiou"):n=s.count(c);print('-'*30+' Char: '+c,n and f"Contains {n} times\nAt places: "+", ".join(str(i+1)for(i,j)in enumerate(s)if j==c)or"Doesn't contain",sep='\n')
Yeah that was actually intended
I am thinking so hard whether is there a shorter solution with "re"
217, un-bugfix
s=input("Give a string!\n\t> ").lower()
for c in(v:="aeiou"):n=s.count(c);print('-'*30+' Char: '+c,n and f"Contains {n} times\nAt places: "+", ".join(str(i+1)for(i,j)in enumerate(s)if j==c)or"Doesn't contain",sep='\n')
Yeah, but now it creates 10 categories instead of 5
!e ```py
s = 'xxxaaxeexaioxu'
#s=input("Give a string!\n\t> ")
for c in(v:="aeiou"):n=s.count(c);print('-'*30+' Char: '+c,n and f"Contains {n} times\nAt places: "+", ".join(str(i+1)for(i,j)in enumerate(s)if j==c)or"Doesn't contain",sep='\n')
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ------------------------------ Char: a
002 | Contains 3 times
003 | At places: 4, 5, 10
004 | ------------------------------ Char: e
005 | Contains 2 times
006 | At places: 7, 8
007 | ------------------------------ Char: i
008 | Contains 1 times
009 | At places: 11
010 | ------------------------------ Char: o
011 | Contains 1 times
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/22HSBZW7PVLM47K536XF6M3SZA
i guess .lower is shortest then
[aeiou]
Something with the same output ๐
this checks for matches of an individual character f"{c}|{chr(ord(c)+32)}"
no im too tired to count
you'd just use c.upper
its way shorter
i should have slept last night lmao
Isn't there something like /[aeiou] /i for case-insensitive match? I mostly write typescript so Im thinking that way
I'll keep thinking then
re.I is the flag for ignorecase
So you say with vanilla python 217 is the floor wo. Changing how the output looks?
Without
224, fixed output
s=input("Give a string!\n\t> ").lower()
for c in(v:="aeiou"):n=s.count(c);print('-'*30+' Char: '+c,n and f"Contains {n} times\nAt places: "+", ".join(str(i+1)for(i,j)in enumerate(s)if j==c)+'\n'or"Doesn't contain\n",sep='\n')
it was missing newlines
------------------------------ Char: a
Contains 2 times
At places: 1, 10
------------------------------ Char: e
Contains 2 times
At places: 5, 14
------------------------------ Char: i
Contains 2 times
At places: 9, 18
------------------------------ Char: o
Doesn't contain
------------------------------ Char: u
Doesn't contain
``` instead of ```
------------------------------ Char: a
Contains 2 times
At places: 1, 10
------------------------------ Char: e
Contains 2 times
At places: 5, 14
------------------------------ Char: i
Contains 2 times
At places: 9, 18
------------------------------ Char: o
Doesn't contain
------------------------------ Char: u
Doesn't contain
using s = "abcdefghiabcdefghi"
this is the shortest correct one so far
224 is the shortest so far
Nice
222, fstrings are cool ```py
s=input("Give a string!\n\t> ").lower()
for c in(v:="aeiou"):n=s.count(c);print('-'*30+' Char: '+c,n and f"Contains {n} times\nAt places: {', '.join(str(i+1)for(i,j)in enumerate(s)if j==c)}\n"or"Doesn't contain\n",sep='\n')
output is the same
im gonna go eat since i haven't done that yet
ping me if you get it shorter
!e
s="abcdefghiabcdefghi"
#s=input("Give a string!\n > ").lower()
for c in"aeiou":n=s.count(c);print('-'*30+f' Char: {c}\n'+[f"Contains {n} times\nAt places: {", ".join(str(i+1)for(i,j)in enumerate(s)if j==c)}","Doesn't contain\n"][n<1])
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ------------------------------ Char: a
002 | Contains 2 times
003 | At places: 1, 10
004 | ------------------------------ Char: e
005 | Contains 2 times
006 | At places: 5, 14
007 | ------------------------------ Char: i
008 | Contains 2 times
009 | At places: 9, 18
010 | ------------------------------ Char: o
011 | Doesn't contain
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/UUN7ZEFU6DH3X7LZ5NBCISPM3Y
212
@versed eagle
!e 203
s="abcdefghiabcdefghi"
#s=input("Give a string!\n\t> ").lower()
for c in"aeiou":n=s.count(c);print('-'*30+f' Char:',*n and[f"{c}\nContains {n} times\nAt places:",*[i for(i,j)in enumerate(s)if j==c]]or[f"{c}\nDoesn't contain\n"])
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ------------------------------ Char: a
002 | Contains 2 times
003 | At places: 0 9
004 | ------------------------------ Char: e
005 | Contains 2 times
006 | At places: 4 13
007 | ------------------------------ Char: i
008 | Contains 2 times
009 | At places: 8 17
010 | ------------------------------ Char: o
011 | Doesn't contain
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/34AKJWZXKZP6CO2T4PD6POPVRI
!e 196
s="abcdefghiabcdefghi"
#s=input("Give a string!\n\t> ").lower()
for c in"aeiou":n=s.count(c);print('-'*30,'Char:',*n and[c+"\nContains",n,"times\nAt places:"]+[i for(i,j)in enumerate(s)if j==c]or[c+"\nDoesn't contain\n"])
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ------------------------------ Char: a
002 | Contains 2 times
003 | At places: 0 9
004 | ------------------------------ Char: e
005 | Contains 2 times
006 | At places: 4 13
007 | ------------------------------ Char: i
008 | Contains 2 times
009 | At places: 8 17
010 | ------------------------------ Char: o
011 | Doesn't contain
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/3NTUT6UIZU6XYNJJV5VU6HQJ5U
ops didn't notice the "," actually :3 so 209 with sep=', '. I will stop her
oo nice
ooo
โจ
also I typed 3 spaces instead of tab, and counted the spaces (changed it to \t and counted it as 1 byte)
discord doesnt let you embed the <TAB> character
it converts to spaces
we're just assuming its there
a
but yours has an extra new line in the end after "Doesn't cotain" ?
oh true
!e there you go a 206 with ', ' I will leave it at that
s="abcdefghiabcdefghi"
#s=input("Give a string!\n\t> ").lower()
for c in"aeiou":n=s.count(c);print('-'*30,f'Char: {c}\n'+[f"Contains {n} times\nAt places: "+", ".join(str(i+1)for(i,j)in enumerate(s)if j==c),"Doesn't contain"][n<1])
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ------------------------------ Char: a
002 | Contains 2 times
003 | At places: 1, 10
004 | ------------------------------ Char: e
005 | Contains 2 times
006 | At places: 5, 14
007 | ------------------------------ Char: i
008 | Contains 2 times
009 | At places: 9, 18
010 | ------------------------------ Char: o
011 | Doesn't contain
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/LX3YLIFX2DREGI7CJ7RDXQZIMI
!e
s="""Buy it, use it, break it, fix it, trash it, change it, mail, upgrade it
Charge it, point it, zoom it, press it, snap it, work it, quick erase it
Write it, cut it, paste it, save it, load it, check it, quick rewrite it
Plug it, play it, burn it, rip it, rip it, Lock it, fill it, call it, find it, view it, code it, jam, unlock it
Surf it, scroll it, pause it, click it, cross it, crack it, switch, update it
Name it, read it, tune it, print it, scan it, send it, fax, rename it""".lower()
#s=input("Give a string!\n\t> ").lower()
for c in"aeiou":n=s.count(c);print('-'*30,f'Char: {c}\n'+[f"Contains {n} times\nAt places: "+", ".join(str(i+1)for(i,j)in enumerate(s)if j==c),"Doesn't contain"][n<1])
@untold gate :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ------------------------------ Char: a
002 | Contains 22 times
003 | At places: 20, 37, 47, 57, 66, 75, 115, 139, 165, 175, 185, 230, 281, 317, 352, 383, 402, 410, 420, 448, 465, 472
004 | ------------------------------ Char: e
005 | Contains 24 times
006 | At places: 11, 19, 50, 68, 78, 105, 137, 141, 150, 168, 177, 194, 209, 214, 300, 310, 355, 404, 412, 419, 430, 456, 470, 474
007 | ------------------------------ Char: i
008 | Contains 62 times
009 | At places: 5, 13, 23, 28, 31, 41, 52, 58, 70, 80, 86, 90, 99, 109, 118, 127, 133, 143, 148, 152, 160, 170, 179, 188, 198, 204, 212, 216, 224, 233, 242, 247, 250, 255, 258, 267, 272, 276, 285, 290, 294, 299, 303, 312, 328, 336, 347, 357, 363, 367, 377, 387, 393, 406, 414, 423, 432, 438, 442, 451, 460, 476
010 | ------------------------------ Char: o
011 | Contains 10 times
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/T5IMIZWYBPVQBLMFDCYTKFTQ5A
isn this 207
\t is 1 character
mki
!e 203
s="abcdefghiabcdefghi"
#s=input("Give a string!\n\t> ").lower()
for c in"aeiou":n=s.count(c);print('-'*30,f'Char: {c}\n'+[f"Contains {n} times\nAt places: "+str([i+1for(i,j)in enumerate(s)if j==c])[1:-1],"Doesn't contain"][n<1])
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | /home/main.py:3: SyntaxWarning: invalid decimal literal
002 | for c in"aeiou":n=s.count(c);print('-'*30,f'Char: {c}\n'+[f"Contains {n} times\nAt places: "+str([i+1for(i,j)in enumerate(s)if j==c])[1:-1],"Doesn't contain"][n<1])
003 | ------------------------------ Char: a
004 | Contains 2 times
005 | At places: 1, 10
006 | ------------------------------ Char: e
007 | Contains 2 times
008 | At places: 5, 14
009 | ------------------------------ Char: i
010 | Contains 2 times
011 | At places: 9, 18
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/3343X4DV7OLEDAS6U5BMPWMKPY
!e 200 ```py
s="abcdefghiabcdefghi"
#s=input("Give a string!\n\t> ").lower()
for c in"aeiou":l=[i+1for(i,j)in enumerate(s)if j==c];print('-'*30,f'Char: {c}\n'+["Doesn't contain",f"Contains {len(l)} times\nAt places: "+str(l)[1:-1]][l>[]])
@quartz wave :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | /home/main.py:3: SyntaxWarning: invalid decimal literal
002 | for c in"aeiou":l=[i+1for(i,j)in enumerate(s)if j==c];print('-'*30,f'Char: {c}\n'+["Doesn't contain",f"Contains {len(l)} times\nAt places: "+str(l)[1:-1]][l>[]])
003 | ------------------------------ Char: a
004 | Contains 2 times
005 | At places: 1, 10
006 | ------------------------------ Char: e
007 | Contains 2 times
008 | At places: 5, 14
009 | ------------------------------ Char: i
010 | Contains 2 times
011 | At places: 9, 18
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/6DXZXHML7AKQJITP73JHM4OJF4
discord won't let you embed a <TAB> character in a message
it replaces with spaces
but the actual string can contain a <TAB> instead of \t
!e 199
s="abcdefghiabcdefghi"
#s=input("Give a string!\n\t> ").lower()
for c in"aeiou":print('-'*30,f'Char: {c}\n'+["Doesn't contain",f"Contains {len(l:=[i+1for(i,j)in enumerate(s)if j==c])} times\nAt places: "+str(l)[1:-1]][l>[]])
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | /home/main.py:3: SyntaxWarning: invalid decimal literal
002 | for c in"aeiou":print('-'*30,f'Char: {c}\n'+["Doesn't contain",f"Contains {len(l:=[i+1for(i,j)in enumerate(s)if j==c])} times\nAt places: "+str(l)[1:-1]][l>[]])
003 | ------------------------------ Char: a
004 | Contains 2 times
005 | At places: 1, 10
006 | ------------------------------ Char: e
007 | Contains 2 times
008 | At places: 5, 14
009 | ------------------------------ Char: i
010 | Contains 2 times
011 | At places: 9, 18
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/FBZRFJCIGNA3YVBLJ6TXZWBUOU
hello
I need help
x = int(input("What is your code: "))
print(x[0])
Is this even possible
to print the first letter of a user's input
or in this case number
If you want genuine help, you're in the wrong place
You could ask in #python-discussion or #1035199133436354600
that's missing newlines
!e
__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))("hello world")```
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
essentially how it works is
it gets __builtins__.__dir__()'s 42nd item by using __builtins__.__dir__().__len__() and dividing by 4, and then adding 3
and then uses __getattribute__
basically __builtins__.__dir__().__len__() // __name__.__dir__().__len__() = 1, so pretty easy tog o from there
mhm
i'll keep doing simple functions :/
and trying not to cry
!e
(__:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))(__name__.__class__.__call__().join(list(map(__, [104,101,108,108,111,32,119,111,114,108,100])))))
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
kinda afraid of getting past char limit
!e
(_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(_.__add__(_)).__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(_.__add__(_.__add__(_.__add__(_)))).__add__(_).__add__(_).__add__(_)))(__name__.__class__.__call__().join(list(map(__, [104,101,108,108,111,32,119,111,114,108,100])))))``` less words for more obfuscat
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
!e
from __hello__ import*;main()
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello world!
Mb didn't realize
@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello world!
fishhook.hook for object when?
wdym? it works (on 3.11 at least)
!e ```py
from fishhook import hook
@hook(object)
def matmul(self, other):
return (self, other)
print(1 @ 2)
print(import('sys').version)
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | (1, 2)
002 | 3.12.0 (main, Oct 3 2023, 03:05:14) [GCC 12.2.0]
^ it works already?
!e
code
!e 2.6
Hello, I'm trying to change "def" to "func" in cpython syntax. Can anyone get hint where I can find this keyword?
why in gods name
https://github.com/python/cpython/blob/main/Parser/parser.c this would probably be my guess tho, that's the generated parser
I do it for fun, thank u)
https://github.com/python/cpython/blob/main/Grammar/python.gram here's the grammar file
no
dont edit the parser by hand
just edit the grammar file and then run make pegen or whatever the command is
though you will then have to edit every single of the stdlib files that python has
but that can be automated
@vapid magnet
dont edit the generated parser, it's bad for your mental health
Yeah, I did it with make regen-pegen, but I need some work around Lib/*.py. A lot of package contains func as variable...
btw you could've made it a soft keyword instead to avoid having to do this https://github.com/G000D1ESS/cpython/commit/769c71dfde9bc815627ab5b6e2d8a1a4c0a17d0f
@hard spoke re my help post from earlier, apparently the course's grading/testing suite does import functools
so now i have to figure out how to reload the module without using importlib or sys lmao
Thanks for idea, I could try it
since you are doing that
please add braces
Lets go
๐ฅณ
if you're going to insist on braces, then i insist on one thing: if the program uses a brace style other than OTBS, it should crash
๐ฅณ
lmao thurisatic is so happy
looks like he is the reason python don't have braces except for sets and dicts
i will try again sometime soon
we believe in you cereal
This has been done before, although unfortunately has since been deleted: https://web.archive.org/web/20210509011406/https://github.com/nekitdev/braces.py
it convert it to python code and executes it
whats otbs?
alternatively spelled 1TBS, "one true brace style"
In computer programming, an indentation style is a convention governing the indentation of blocks of code to convey program structure. This article largely addresses the free-form languages, such as C and its descendants, but can be (and often is) applied to most other programming languages (especially those in the curly bracket family), where w...
oh
k&r style is better (but with mandatory braces ofc)
@karmic pumice
rest in peace, mind checking it in a repl [preferably ipython]? i usually do all stuff in it so ๐คท
it happened in repl
works with fishhook too
ipython is too heavy for this
it keeps spamming infinitely
certified repl incident
i would assume python to fold those expressions
yeah
i guess optimizer calls int.__add__ at compile time, so if compile time happens after some runtime, it can call non-original method ๐
the compiler is in c
it does not have int.__add__
and making a detour like that to the rest of the interpreter just to add 2 numerical constants is a bit silly
you can try it tho
compile("print(1+2)", "", "exec")
9700 6400 5300 - this is bytecode for 1 + 2
>>> dis.opname[0x97]
'RESUME'
>>> dis.opname[0x64]
'LOAD_CONST'
>>> dis.opname[0x53]
'RETURN_VALUE'
that makes sense
optimizer noticed literal + literal situation and added them together, but i changed how addition works and it received wrong result
that is interesting, i didnt know that is possible (i thought optimizer calls int.__add__ directly, not through int class)
is there a shorter way of checking if a float is an int than n.is_integer()
ah got it
n==int(n)
n.is_integer()
i used n%1==0
wrong channel
how so?
might be better in pydis
read the description lol
this channels for golfing
very first thing listed is golfing
niabufbdifjoiajijdoisgoih iohoue
how can this be shortened py if(sum(x:=[...])/len(x))%1==0
that wont work
it works
!e
print(sum([...]))
@versed eagle :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(sum([...]))
004 | ^^^^^^^^^^
005 | TypeError: unsupported operand type(s) for +: 'int' and 'ellipsis'
.
.
the ... is filler
0 + ... doesn't work
like i have more code in there
its a list comprehension
.
it changes
get your story straight,
on mine, just compile was enough to get the hook called
i know, and i showed that (but I wasn't doing compile in repl because my repl is too fancy)
i also showed that peepholer indeed optimized that, and it used value i gave him
there im running compile, and it triggers hook (but in this case hook doesn't print anything, so it is less obvious)
you can omit outer pair of braces because % has the same priority as *, / and // (cus they are all kinds related to multiplication)
also, if your "if" has "else" branch, yiu can omit ==0 part and swap branches
also you can replace (...)%1==0 with not(...)%1, that takes same amount of chars
not will execute after %, so its fine
be smarter pls
you are essentially checking if a/b is an integer
that happens only if a is divisible by b
so you can replace a/b%1==0 with a%b==0, that is -2 chars
and you still can omit ==0 by swapping if-else branches, if you have them, of course
so its like ```py
if sum(x:=[...])%len(x): ... # not int
else: ... # int
if sum(x:=[...])%len(x)==0: ... # int
i dont see a way to shorten it further without any knowledge about list comprehension
what
thats,, rude
tbh i did not expect to see something like that from you denball
I didn't mean to be rude. I just suggested that you pay a little more attention to the problem, and not to nit-picking
Focusing on tearing apart others for minor things that don't matter much. Saying things like "get your story straight" is pretty rude
Ah I missed that
wouldnโtโve expected the compiler to call python functions
when i do a%b instead of a/b%1 i can use <1 instead of ==0
idk why it works but it does
so thats -1
and bc its <1 i can now do this
sum(x:=[...])%len(x)<1==print(i)
getting rid of the if
Hey, I have a small golfing challange for ya
You have a 2d grid, n width and m high. Each cell in the grid can store 0 on 1, 0 being a free space and 1 being a wall.
Imagine a Battleship game, u have x long ship and u can place it horizontally or vertically on the grid. The challange is to find a cell with the highest probability of being a ship.
in this example
this would be the best cell
what if there are multiple optimal locations?
then return all of them
but you said find "a" cell with the highest probablility fine
yep, i didn't think about that
shipLength = 3
grid = [
[0,0,0,0,1],
[0,1,1,0,0],
[0,0,0,0,0],
[1,1,0,0,0],
[0,0,0,0,0]
]
Let's say they are already defined
CP-style input might be shorter lol
CP-style input?
competitive programming
a format like ```
n m x
0 0 0 0 0
0 0 0 0 0
...
into stdin
because I'm thinking of just flattening the 2d list anyway
lets go with this
or just do whatever you want ;p
im gonna give it a go too
yep
yes
So x y would be grid[y][x]
yup
Cool
g=[''.join(map(str,u))for u in grid]
x=shipLength
a=[[min(j+1,i-x+1,i-j) for j in range(i)] if i>=x else[0]*i for i in range(6)]
v=[sum((a[len(q)]+[0] for q in r.split('1')),[])for r in g]
w=[sum((a[len(q)]+[0] for q in ''.join(r).split('1')),[])for r in zip(*g)]
t=[sum(x)for r in zip(v,zip(*w))for x in zip(*r)]
[print(i%5,i//5)for i,q in enumerate(t) if q==max(t)]```passes the one testcase, didn't test it further.
Hmm, strings are interesting
I was thinking of g=sum(grid,[]) and not any(g[ <something> ])
It seemed fairly fitting since the result depends on the length of the 0 runs
Tested it on other grid
grid = [
[1,0,1,0,1],
[1,1,1,1,0],
[0,0,1,0,1],
[1,1,0,1,0],
[0,0,1,0,0]
]
so 3 long ship cant fit here
hmm, my x handling could be entirely wrong
Ah nvm, it is correct, it reports every spot since every spot can contain the ship with the highest probability, I was copy pasting wrong before.
min(j+1,i-x+1,i-j,x) This may be needed for x other than 3
but walls can't have a ship
neither can any other spot
oh true
x=shipLength
M=i=0
n=len(grid[0])
g=sum(grid,L:=[])
for _ in g:
i+=1
print(x-sum(o%n>n-x or any(g[o:o+x])for o in range(i-x,i)))
``` horizontal checking is working
x=shipLength
M=2*x
n=len(grid[i:=0])
g=sum(grid,L:=[])
for _ in g:
p=sum(o%n>n-x or any(g[o:o+x])for o in range(i-x+1,i+1))+sum(0>o or o+x*n>len(g)or any(g[o:o+x*n:n])for o in range(i-x*n+n,i+n,n))
if p<M:M,*L=p,
L+=[i]*(p==M);i+=1
for i in L:print(i//n,i%n)
``` 261, works as far as I can tell
@finite blaze
257, same output so i assume it works ```py
x=shipLength
M=2x
n=len(grid[i:=0])
g=sum(grid,L:=[])
for _ in g:
p=sum(any(g[o:o+x]+[o%n>n-x])for o in range(i-x+1,i+1))+sum(any(g[o:o+xn:n]+[0>o,o+xn>len(g)])for o in range(i-xn+n,i+n,n))
if p<M:M,L=p,
L+=[i](p==M);i+=1
for i in L:print(i//n,i%n)
x=shipLength
M=2*x
n=len(grid[i:=0])
g=sum(grid,L:=[])
for _ in g:
p=sum([any(g[o:o+x]+[o%n>n-x])for o in range(i-x+1,i+1)]+[any(g[o:o+x*n:n]+[0>o,o+x*n>len(g)])for o in range(i-x*n+n,i+n,n)])
if p<M:M,*L=p,
L+=[i]*(p==M);i+=1
for i in L:print(i//n,i%n)
``` 256
how so
,, how am i supposed to answer their question if they keep changing their question
What is the reason for the M=2*x?
p counts the number of invalid boat placements
So if all boats are invalid (which would be the least probability) then p would be 2x
Ah ok, but then isnt L:=[] completely unnecessary?
Since if p<M:M,*L=p, should always trigger first iteration
hmm
it wouldn't, if none of the placements are valid
actually, M=3*x should fix that
ye
x=shipLength
M=3*x
n=len(grid[i:=0])
g=sum(grid,[])
for _ in g:
p=sum(any(g[(a:=o*n+i)-x*n:a:n]+[x*n>a,a>len(g)])+any([(b:=o-x+i)%n>n-x]+g[b:o+i])for o in range(1,x+1))
if p<M:M,*L=p,
L+=[i]*(p==M);i+=1
for i in L:print(i//n,i%n)
``` 232
L+=M//p*[i] saves 2 characters
Do that yourself
!e
A = [[1,2], [3,4]]
print(sum(A, []))
A = ["12", "34"]
print(sum(A, ""))
What is the reason why sum with [] works, but sum with "" doesn't work? Has sum been hardcoded to not allow strings?
@distant salmon :x: Your 3.12 eval job has completed with return code 1.
001 | [1, 2, 3, 4]
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 5, in <module>
004 | print(sum(A, ""))
005 | ^^^^^^^^^^
006 | TypeError: sum() can't sum strings [use ''.join(seq) instead]
they were telling you that what was in the placeholder value ... didn't matter for their question. Both a list and a list comp produce the same type of object and can be used in sum so either way it wouldn't really matter to your answer
Iirc its hardcoded
๐ฉ
Python/bltinmodule.c line 2515
/* reject string values for 'start' parameter */```
oh, of course! i missed that
!e
print(
sum(["a", "b"], type("", (), {"__add__":"".__add__})())
)
@restive void :white_check_mark: Your 3.12 eval job has completed with return code 0.
ab
I really wish sum would work in the same way as min and max
!e
A = [2,3]
print(min(A))
print(min(2,3))
print(min(A, default=-123))
@distant salmon :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 2
002 | 2
003 | 2
In what way? 
There are ton of things that make sum unwieldy.
While min(a,b) and max(a,b) is thing, you cant do sum(a,b) to add two numbers
Another frustrating thing about sum is that you have to tell it the start value. Which you really should need to have to do.
Had sum worked in the same way as min and max, then for example
sum([[1,2], [3,4]])
would just work straight out of the box
Oh yeah that last part I agree with
Or like being able to pass a non-number to start and concatenating strings for example
sum is fundamentally not the right way to concatenate strings, and I don't think it is a good idea to make it call "".join for you
!e ```py
_ = type('',(),dict(add=lambda a, b: b))()
print(sum([[1,2], [3,4]], start=))
print(sum(['a', 'b'], start=))
print(sum([1, 2], start=_))
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | [1, 2, 3, 4]
002 | ab
003 | 3
I mean min and max just call > on the items they are given, I don't see why sum should be any different just calling +
I don't know why sum works in a different way compared to min and max
In a perfect world, they would work the same way
Tf
til
# now sum has this signature: (i oversimplified it)
def sum(_i: Iterable[...], start: ... = 0) -> ...: ...
# if i understood correctly you want this:
def sum(_i: Iterable[...], default: ...) -> ...: ...
sum(['a', 'b']) == 'ab'
sum([[1, 2], [3, 4]]) == [1,2,3,4]
sum([1, 2]) == 3
sum([]) -> error
sum([], default=x) -> x
# and you also want this:
def sum(*_i: ..., default: ...) -> ...: ...
sum('a', 'b') == 'ab'
sum([1, 2], [3, 4]) == [1,2,3,4]
sum(1, 2) == 3
sum(*[]) -> error
sum(*[], default=x) -> x
i think that is possible, but that would be a huge breaking change right now
Ye, almost. I would also want default in sum to by default be 0.
So sum([]) == 0
and sum() == 0
It would be a breaking change, yes. But only if someone is using start as a non-zero value.
In 99% of cases it wouldn't break anything
that would be weird:
sum('a', 'b', 'c') -> 'abc'
sum('a', 'b') -> 'ab'
sum('a') -> 'a'
sum() -> 0 # WTF???
(just ignore the fact that im using strings, they are just convenient to show the behaviour)
Default is simply 0. I don't think it is weird.
i don't like that both ways are valid
because imo the current interface implies that min(*it) and min(it) are always the same, but with it=("abc",) this is not the case
its like a little lie hiding inside python
same with max
i think that it should be all args or all inside one iterable
I'm not sure I understand what you mean
min(a,b,c) and min([a,b,c]) are the same
Oh. But that is simply how Python works currently
I and I find that to be very useful and easy to use in practice
min(a,b) and min([a,b]) are the same
but min(a) and min([a]) are NOT the same
this is what i have a problem with
another question: what should sum([1]) return?
sum([1], [2], [3]) -> [1, 2, 3]
sum([1], [2]) -> [1, 2]
sum([1]) -> 1 or [1] ?
sum() -> 0
Hmm ye, that is a good question.
Logically it must be 1
this ambiguity stems from the same problem as what's present currently in min and max
min(it) and min(*it) are the same UNLESS it has one element
which is stupid and annoying
From a users perspective, it is pretty nice to be able to use min and max in both cases.
MISSING = object()
def sum(*i, default=MISSING):
if len(i) == 1 and hasattr(i[0], '__iter__'):
i = i[0]
i = list(i)
if not i:
if default is MISSING:
raise ValueError('empty sequence with no default')
else:
return default
res = i[0]
for x in i[1:]:
res += x
return res
assert sum([1, 2]) == 3
assert sum([1]) == 1
assert sum(['a', 'b']) == 'ab'
assert sum(['a']) == 'a'
assert sum([], default=42) == 42
assert sum(1, 2) == 3
assert sum(1) == 1
assert sum('a', 'b') == 'ab'
assert sum('abc') == 'abc' # it is not just returning string, it splits it and constructs back from chars
assert sum(default=42) == 42
assert sum([1], [2], [3]) == [1, 2, 3]
assert sum([1], [2]) == [1, 2]
assert sum([1]) == 1
assert sum([], default=0) == 0
``` my quick and dirty implementation of what you want (but you have to pass default in order to use it)
yes, until the disconnect is encountered
im not saying that i dislike the idea as a whole, im saying that i dislike it that they are inconsistent
You have to think about how people use min and max in code. No one calls min and max using min(*A).
They either do min(a,b) or min(A)
,, i do
Well you probably shouldn't
i guess min(a, b) is the most popular use of min(*x) by far
>>> min('abc')
'a'
>>> min('abc', 'def')
'abc'
>>> min('abc', 'def', 'ghi')
'abc'
I've definitely seen both min(a,b) and min(A) be used quite frequently
yes, but min(A) doesnt use star-args feature
Ye I don't even recall ever seeing anyone use the star args feature with min
im talking about cases where args are "unpacked" into min
min(a,b) is frequent, min(a,b,c) is a lot less frequent, min(*A) is weird
min(A) is totally ok
ye
Another thing I don't recall ever seeing is someone actually using the start variable in sum (for something other than 0/[]/...)
Even if I had wanted to have a non-zero start value, then I would probably still just do it like sum(A) + x instead
So start is pretty much a totally useless feature
i guess if you are summing some non-int numbers (like Fraction or Decimal) you have to pass Fraction starting value
Well Python is ok with adding those
>>> sum([F(1, 2), F(1, 3)])
Fraction(5, 6)
``` yeah
The modification that I'm suggesting for sum would only really break in cases like this
sum([[1,2], [3,4]], [5,6])
so it will return [1,2,3,4] instead of [5,6,1,2,3,4] and return [5,6] iff input is empty, right?
yes
Another scenario that would break is if someone uses start to change the type of the sum sum([1,2,3], 0.0)
Why???
Have a look at the function signature from the Python docs:
sum(iterable, /, start=0)
We were talking about changing how sum works
To make it work in the same way as min and max does
But why?
just use None in that case
falsly in every scenario and somewhat makes sense
huh? it doesnt solve the problem
wrong message for some reason, i am confident i replied to the correct one
i meant the sum of nothing could return None, and it would make sense somewhat
no, not really
It is pretty common to use that sum([]) is 0
Empty sums being 0 is simply the most natural definition
Yeah, I think it is fine that sum is 0 by default, even if it is not a default that will work everywhere
There are languages like purescript, where zero is a polymorphic across everything that supports addition, but python is not one of those
I never really stopped to think just how impressive PyLongObject is
even better one https://paste.pythondiscord.com/FFTA
why when you gonna to use the funcion print in a varibale to save characters the variable is always called I
for example
I=input
n = int(I())
h = I()
I(n,h)```
xd
is like something idiomatic ?
why not ```py
I=input
I(int(I()),I())
`input()` starts with the letter "i" and `i` is commonly used as a variable for other purposes so `I` is used for `input()` instead
in general, i prefer uppercased letters for aliases of builtins because that way im less likely to use them later for something else
My golfed solution for this problem, too lazy to mess with the setup https://leetcode.com/problems/permutation-sequence/description/ py class Solution: def getPermutation(self, n: int, k: int) -> str: f=lambda x:0**x or x*f(x-1) l=lambda x,y:x and x.pop(((y-1)//f(len(x)-1))%len(x))+l(x,y)or"" return n<2 and"1"or l([*map(str,range(1,n+1))],k)
getPermutation=lambda self, n, k: sorted([''.join(x) for x in itertools.permutations([str(i + 1) for i in range(n)], n)])[k - 1]
(credit to the solution i found that from)
I would have done that, but I also wanted to be able to submit it with my lowly free rank. Also with the non-itertools.permuations style solutions will work for insanely large n, while anything above 10 causes the ones that use it to grind to a halt.
Using permutations, the shortest would probably be something like py getPermutation=lambda self,n,k:"".join([*__import__("itertools").permutations(map(str,range(1,n+1)))][k-1])
cmon
getPermutation=lambda _,n,k:"".join([*__import__("itertools").permutations(map(str,range(1,n+1)))][k-1])
fully named self? cmon man
i love the python parser
I think I understand what's happening. In the first case, print(1) is an annotation for lambda_, thus it gets "ignored" and you get lambda_ = 123. Thus for the second case, print(1) is an annotation for _, so it gets "ignored" and you just get lambda = 123, which is the syntax error.
yeahn't
the first one is correct, print(1) is the type hint expression for a variable called lambda_
-> gets evaluated
second one is literally just a lambda that takes one unused parameter and prints 1
and i am trying to assign something to that lambda
maximal munch applies in pretty much every language. lambda_ being a valid variable name is not specific to python but pretty much every language
eg. class_ will be a valid variable name in java and c++
wrong chat, #python-discussion
idk where to ask this but what is the best site to learn python for free?
Anyone used poetry much? How does it compare with pipenv for dep management
I have used it
though i never used pipenv
- wrong channel
- python documentation, https://docs.python.org
wrong channel
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ok guys just printed my first hello world program\
python looks pretty fun
!e
(lambda i: [print(chr(x),end='') for x in (lambda i=i: [globals().update({"h":(lambda _=(i[-1]+i[2]): (_*_)+i[3])()}) or h,h - i[2],globals().update({"l":h + i[3]}) or l,l,globals().update({"o":l + i[2]}) or o,(i[-1] + i[0]) * 4,o + (i[3] * 2),o,o + i[2],l,h - i[3],i[4] * 2])()])([_.__code__.co_argcount for _ in ((lambda _: None),(lambda _, __: None),(lambda _, __, ___: None),(lambda _, __, ___, ____: None),(lambda _, __, ___, ____, _____: None),(lambda _, __, ___, ____, _____, ______: None),(lambda _, __, ___, ____, _____, ______, _______: None))])
@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
ehh the only interesting thing is using function argcount
just simple python nothing crazy ๐
Is it a fractal or something
for all rational numbers a/b from 0 to 1:
draw (a/b, b)
import functools
import itertools
N = 720 # screen size
MAX_DEN = N
@functools.cache
def rats(n: int) -> list[tuple[int, int]]:
r = []
if n == 0:
r.append((0, 1))
r.append((1, 1))
return r
p = iter(rats(n - 1))
a, b = next(p)
r.append((a, b))
for c, d in p:
if b + d < MAX_DEN: # ignore all rationals with too big denom
r.append((a + c, b + d))
r.append((c, d))
a, b = c, d
return r
import pygame as pg
pg.init()
s = pg.display.set_mode((N + 1, N + 1))
s.fill((0, 0, 0))
for d in itertools.count(): # draw more and more every time, inefficient!
for a, b in rats(d):
s.set_at(
(N * a / b, b - 1),
(255, 255, 255),
)
pg.display.flip()
for e in pg.event.get():
if e.type == pg.QUIT:
pg.quit()
1/0
number 1/100 will appear in 100th Farey sequence, but n-th Farey sequence contains 2^n+1 numbers, so generating all 100th sequence is not possible
that is why im ignoring all rationals with denominator bigger than some fixed number (in this case - screen size)
but my algo is definitely not optimal, it degrades to O((number of all rats with denoms < N)^2) complexity, which is pretty slow
i think this conversation better fits into #algos-and-data-structs channel ๐ค
!e absolute rookie
print(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())))))
``` this is just the print function lmao
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
<built-in function print>
code golfing anyone?
you got something to golf?
idk
code

๐๏ธโโ๏ธ
why do we have a spinning pride python emoji but not a spinning normal python emoji
friend sent me this funny way of obfuscating/confusing your python code to make it harder to read
__________ = eval(getattr(__import__(bytes([98, 97, 115, 101, 54, 52]).decode()), bytes([98, 54, 52, 100, 101, 99, 111, 100, 101]).decode())(bytes([90, 88, 90, 104, 98, 65, 61, 61])).decode());___________ = __________(getattr(__import__(bytes([98, 97, 115, 101, 54, 52]).decode()), bytes([98, 54, 52, 100, 101, 99, 111, 100, 101]).decode())(bytes([90, 50, 86, 48, 89, 88, 82, 48, 99, 103, 61, 61])).decode());_______________ = __________(getattr(__import__(bytes([98, 97, 115, 101, 54, 52]).decode()), bytes([98, 54, 52, 100, 101, 99, 111, 100, 101]).decode())(bytes([88, 49, 57, 112, 98, 88, 66, 118, 99, 110, 82, 102, 88, 119, 61, 61])).decode());________________ = __________(getattr(__import__(bytes([98, 97, 115, 101, 54, 52]).decode()), bytes([98, 54, 52, 100, 101, 99, 111, 100, 101]).decode())(bytes([89, 110, 108, 48, 90, 88, 77, 61])).decode())
!e
__________ = eval(getattr(__import__(bytes([98, 97, 115, 101, 54, 52]).decode()), bytes([98, 54, 52, 100, 101, 99, 111, 100, 101]).decode())(bytes([90, 88, 90, 104, 98, 65, 61, 61])).decode());___________ = __________(getattr(__import__(bytes([98, 97, 115, 101, 54, 52]).decode()), bytes([98, 54, 52, 100, 101, 99, 111, 100, 101]).decode())(bytes([90, 50, 86, 48, 89, 88, 82, 48, 99, 103, 61, 61])).decode());_______________ = __________(getattr(__import__(bytes([98, 97, 115, 101, 54, 52]).decode()), bytes([98, 54, 52, 100, 101, 99, 111, 100, 101]).decode())(bytes([88, 49, 57, 112, 98, 88, 66, 118, 99, 110, 82, 102, 88, 119, 61, 61])).decode());________________ = __________(getattr(__import__(bytes([98, 97, 115, 101, 54, 52]).decode()), bytes([98, 54, 52, 100, 101, 99, 111, 100, 101]).decode())(bytes([89, 110, 108, 48, 90, 88, 77, 61])).decode())
@sick hound :warning: Your 3.12 eval job has completed with return code 0.
[No output]
thats boring tho
that's also really easy to deobfuscate
This was my (admittedly somewhat lazy) attempt at an obfuscator/deobfuscator a few years back (works in 3.9, but not 3.10+ since it relies on orderings of __dir__ for various modules)
Basically just maps every letter in the code to an obfuscated thing that execs to it
I was going to change it to not rely on __dir__ so that it'd work on more versions but never bothered in the end
can this be golfed any further?
o=range(1,10000)
for i in o:sum(x:=[j for j in o if i%j<1])%len(x)<1==print(i)```
!e ```py
o=range(1,10000)
for i in o:sum(x:=[j for j in o if i%j<1])%len(x)<1==print(i)
@gleaming linden :x: Your 3.12 eval job timed out or ran out of memory.
001 | 1
002 | 3
003 | 5
004 | 6
005 | 7
006 | 11
007 | 13
008 | 14
009 | 15
010 | 17
011 | 19
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/FCXRFBHDM5UCENT6NRI3E4A3NI
what is it supposed to do?
prints numbers from 1-10k if the mean of their divisors is an integer
<1== -> or
that's just how or works
it short-circuits after the first truthy value
so if sum(...)%len(x) was nonzero it wouldn't print
I have 75 bytes but don't want to spoil it bc ...
https://code.golf/arithmetic-numbers#python
is it very different from my solution?
no 2 little tricks
It is kinda frustrating that you get TLE doing this
o=range(1,10000)
for i in o:sum(x:=[j*(i%j<1)for j in o])%len(x)<1==print(i)
They set a very unfortunate timelimit for that problem
That solution actually doesn't work because the length. If there is a timeout it still displays the output before the timeout.
Wait what?
wdym length?
the length of x is not the same
oh
!e ```py
def foo(x:lambda: print("foo")()):
print("foo",x)
foo(1)
print(callable(foo.annotations['x']))
print(foo.annotations'x')```
@fleet bridge :x: Your 3.12 eval job has completed with return code 1.
001 | foo 1
002 | True
003 | foo
004 | Traceback (most recent call last):
005 | File "/home/main.py", line 6, in <module>
006 | print(foo.__annotations__['x']())
007 | ^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/home/main.py", line 1, in <lambda>
009 | def foo(x:lambda: print("foo")()):
010 | ^^^^^^^^^^^^^^
011 | TypeError: 'NoneType' object is not callable
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/GIQ22ZAG32QQDA6Q45CY46Y7DY
!e
def foo(x:lambda: print("foo")):
print("foo",x)
foo(1)
print(callable(foo.__annotations__['x']))
print(foo.__annotations__['x']())
@restive void :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | foo 1
002 | True
003 | foo
004 | None
!e
def foo(x:(lambda: print("foo"))()):
print("foo",x)
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
foo
!e
def foo(x:lambda: print("foo")):
print("foo",x)
foo.__annotations__['x']()
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
foo
!e
n=0
type F=exec("n.bit_count()%2 or print(n);n+=1;n<16!=F.__value__",globals())
F.__value__
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 3
003 | 5
004 | 6
005 | 9
006 | 10
007 | 12
008 | 15
lmao
are you using some weird unicode trickery?
the new 3.12 syntax, it uses lazy evaluation which makes that possible
Can anyone get something more performant than
lambda l: sum(map(lambda x, times: (x,) * times, l, map(lambda x: (not x) + 1, l)), ())[:len(l)]
which does the same thing?
With timeit.timeit I measure around 2.45 seconds for l = 0, 0, 1, 2, 0, 3, 4, 5
It doesn't matter what specific sequence l is, probably, nor does it matter what the resulting object's sequence type is
I saw this and decided to give it my best in Python and I ended up with that expression for maximum performance
Introducing Uiua! A new stack-oriented array language. This video briefly introduces the language by solving a simple PWC Problem.
Uiua: https://www.uiua.org/
UiuaPad (with DupZeroes): https://uiua.org/pad?src=DupZeroes โ โโงปโถโฝ%2B1%3D0..
%23 Tests
DupZeroes [1 0 2 3 0 4 5 0%5...
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.
Currently only 3.12 version is supported.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
!e print(
sum(["a", "b"], type("", (), {"add":"".add})())
)
@nocturne spruce :white_check_mark: Your 3.12 eval job has completed with return code 0.
ab
Turns out looping and extending a list is faster than an expression like this
!e
__chr__ = __builtins__.__getattribute__(__name__.__reduce__.__name__[(__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__())] + __name__.__add__.__class__.__name__[(__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__())] + __name__.__class__.__name__[-(__name__.__len__() // __name__.__len__())])
__import__(__chr__((__name__.__len__())*(__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__())) + __chr__((__name__.__len__())*(__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__())) + __chr__((__name__.__len__())*(__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__() // __name__.__len__())) + __chr__((__name__.__len__())*(__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__()) + (__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__()) + (__name__.__len__() // __name__.__len__())))
@oak anchor :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/PKI6SPR7BQSRG2U35CPFO7YVJY
I'd love to replace all the operators with dunders as well but discord won't let me post a message that big
oh ew
they added more typehinting stuff
code that uses it will be easier on the eyes than it was before
if you dont like it dont use it
how is it bad
code that uses it will be easier on the eyes than it was before
what's easiest on the eyes is just none of it at all
if you don't like it don't use it
that'd be all well and good if i existed in a vacuum with no one else, but i dont. other people are going to use it, and im going to have to deal with it
how is it bad
it's pointless nonsense
well for people who use it it's great, and those who don't, it generally doesn't affect them
if you didn't care about XML files you wouldn't go out and say the xml module is pointless nonsense, why this
about other people using it, would you rather see
class Foo(Generic[T]):
or
class Foo[T]:
i think you'll get used to option 2 pretty quickly if that's the only two options
- xml handling doesn't result in changes to the core language
- xml has a much better noise to signal ratio than typehinting
as for if ideally you'd rather see none of it at all, unfortunately it's useful to some and indeed we don't live in a vacuum
typehinting got beyond the point of practical usefulness a while ago
pep695 decreases noise that's kinda the entire point
if it had gone beyond i doubt its usage would be going up
and the cost of that is that more people are going to use typehinting
meaning there will be more noise overall
more people are using it regardless
no? without it the same number of people would be using it
something can't be more than itself
I'll leave this here
0:00 Intro
2:44 The Algorithm
6:38 Why it works
9:28 Code
10:41 Final Thoughts
Our implementation of Universal Search: https://github.com/polylog-cs/universal-search/blob/main/code/universal_search.py
Our Patreon: https://www.patreon.com/Polylog
Impromptu: https://impromptu.fun/
More about universal search:
-- To prove that the universal se...
I am challenging if anyone could understand this:
lambda x,y: ''.join([{0: [' '],2:['A','B','C'],3:['D','E','F'],4:['G','H','I'],5:['J','K','L'],6:['M','N','O'],7:['P','Q','R','S'],8:['T','U','V'],9:['W','X','Y','Z']}[d[1]][([(i,b[0]) for i,b in enumerate(zip(x,y)) if i==0 or b[0]!=x[i-1] or b[1]>y[i-1]+0.5] + [(len(x), )])[i+1][0]-d[0]-1] for i,d in enumerate([(i,b[0]) for i,b in enumerate(zip(x,y)) if i==0 or b[0]!=x[i-1] or b[1]>y[i-1]+0.5])])
Given info:
x and y are both iterable
Found info:
element in x is bind to the dict key (by @programming_enjoye r)
How do I stop it from actually pinging people but still show the username
It just instantly convert to <@id> lmao
well i also think that x and y are iterable but in some condition subscription is needed so they need to be sequences so there's definetely a lot of logic going on
cereal is usually good at uncompressing those kinds of stuff
Ok lol
you wrote this right
Yeah
And also good luck decompressing since I straight away build this from one linear with just a few semi-colon
And a global variable that I now throw inside the function(which is quite obviously which is)
yeah this is exactly like a telephone keypad but i struggle to understand the input/output relation
๐คฃ, it use to be just one thing at the start which is way easier
And now they are referenced 4 and 3 times for each
f([3],[any_ascii_char])=='D'
?
thats uhh something
even if i give an int its still 'D'
f([3],(anything)) seems to be 'D'
Well, not anything
