社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中打印前1000个(平方根、立方根、第四根和第五根)的列表?

LifeBeyondTheClouds • 7 年前 • 2323 次点击  

我很好奇如何在Python中生成自己的列表(第一个,第n个数字):(平方根、立方根、第四个根和第五个根)。

类似这样(没有gui):

Imgur Picture of: List of First 1000 Cube Numbers

我真的很好奇这是如何创建的,因为我通常会学到很多关于数学根的知识,以及关于解决Python根问题的知识。

谢谢您。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48383
文章 [ 2 ]  |  最新文章 7 年前
seymourgoestohollywood
Reply   •   1 楼
seymourgoestohollywood    7 年前
for i in range(1, 1001):
    print(i, i * i * i)

印刷品:

1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
10 1000
11 1331
12 1728
13 2197
14 2744
15 3375
16 4096
...
Chris Doyle
Reply   •   2 楼
Chris Doyle    7 年前

当你对各种不同的能力更感兴趣时,你可以写一个函数,它包含你想打印的n个数字和你想使用的能力。然后它将返回当前值的元组 n ,的值 n个 致 power 然后是一个文本公式。

这个函数也会产生结果,所以如果你在寻找大的N值,它们不会立即加载到内存中。

在这个例子中,我加载了pandas模块,只是为了方便将输出作为数据帧打印。

编辑 更新了根的示例。roots函数可以接受一个可选的十进制精度参数,因为roots通常返回十进制值。如果函数中没有精度值,则将显示完整的精度

import pandas as pd

def get_nth_powers(nth, power):
    for n in range(nth):
        written_formula = (" x ".join([str(n)] * power))
        yield (n, n ** power, written_formula)


def get_nth_roots(nth, root, decimal_precision=0):
    decimal_precision = f'0.{decimal_precision}f' if decimal_precision else ''
    for n in range(nth):
        value = n ** (1/root)
        written_formula = (" x ".join([f'{value:{decimal_precision}}'] * root))
        yield (n, value, written_formula)


data = get_nth_powers(1000, 4)
df = pd.DataFrame(data, columns=('Nth', 'To Power', 'formula'))
print(df)

data = get_nth_roots(1000, 2, 3)
df = pd.DataFrame(data, columns=('Nth', 'value', 'formula'))
print(df)

输出

     Nth      To Power                formula
0      0             0          0 x 0 x 0 x 0
1      1             1          1 x 1 x 1 x 1
2      2            16          2 x 2 x 2 x 2
3      3            81          3 x 3 x 3 x 3
4      4           256          4 x 4 x 4 x 4
..   ...           ...                    ...
995  995  980149500625  995 x 995 x 995 x 995
996  996  984095744256  996 x 996 x 996 x 996
997  997  988053892081  997 x 997 x 997 x 997
998  998  992023968016  998 x 998 x 998 x 998
999  999  996005996001  999 x 999 x 999 x 999

[1000 rows x 3 columns]
     Nth      value          formula
0      0   0.000000    0.000 x 0.000
1      1   1.000000    1.000 x 1.000
2      2   1.414214    1.414 x 1.414
3      3   1.732051    1.732 x 1.732
4      4   2.000000    2.000 x 2.000
..   ...        ...              ...
995  995  31.543621  31.544 x 31.544
996  996  31.559468  31.559 x 31.559
997  997  31.575307  31.575 x 31.575
998  998  31.591138  31.591 x 31.591
999  999  31.606961  31.607 x 31.607

[1000 rows x 3 columns]