I was looking at the Qiita trend page in my usual routine, and I saw an article like this!
Considering Conner Davis's answer, "Print numbers from 1 to 100 without looping, recursion, or goto" https://qiita.com/xtetsuji/items/19d07c629852876da401
No no no
Isn't it too interesting and amazing to be able to get a number from 1 to 100 with this?
It is reproduced in perl and ruby in the article, but it seems that it is not reproduced in python that I usually use, so I tried it.
make_num.py
from decimal import *
import re
getcontext().prec = 298
data = Decimal(1000) / Decimal(999**2) #Calculation part
data = (str(data).split(".")[1])
print(re.findall(r'...', data)) #Split+Output part
@shiracamus @ Louisa0616 The calculation part and the division part have been changed according to the two people's suggestions. ↓ Before change data = Decimal("1000")/Decimal(str(999**2)) print(re.split('(...)',data)[1::2])
In normal python division, the result is float and it is not possible to output up to 300 digits. Therefore, the decimal library is used to output up to the specified number of digits. Also, since the calculation results are stuck together like 0.001002003 ...., I use a regular expression to separate them.
The output looks like this:
$ python make_num.py
['001', '002', '003', '004', '005', '006', '007', '008', '009', '010',
'011', '012', '013', '014', '015', '016', '017', '018', '019', '020',
'021', '022', '023', '024', '025', '026', '027', '028', '029', '030',
'031', '032', '033', '034', '035', '036', '037', '038', '039', '040',
'041', '042', '043', '044', '045', '046', '047', '048', '049', '050',
'051', '052', '053', '054', '055', '056', '057', '058', '059', '060',
'061', '062', '063', '064', '065', '066', '067', '068', '069', '070',
'071', '072', '073', '074', '075', '076', '077', '078', '079', '080',
'081', '082', '083', '084', '085', '086', '087', '088', '089', '090',
'091', '092', '093', '094', '095', '096', '097', '098', '099', '100']
I can't predict where it will be used in the future, but the idea of being able to display numbers from 1 to 100 without using a for statement was interesting.
References
- https://techacademy.jp/magazine/19130
- https://kaworu.jpn.org/python/Python%E3%81%A7%E6%96%87%E5%AD%97%E5%88%97%E3%82%922%E6%96%87%E5%AD%97%E3%81%9A%E3%81%A4%E5%88%86%E5%89%B2%E3%81%99%E3%82%8B
Recommended Posts