用Python输出一个杨辉三角的例子
关于杨辉三角是什么东西,右转维基百科:杨辉三角
稍微看一下直观一点的图:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
杨辉三角有以下几个特点:
每一项的值等于他左上角的数和右上角的数的和,如果左上角或者右上角没有数字,就按0计算。
第N层项数总比N-1层多1个
计算第N层的杨辉三角,必须知道N-1层的数字,然后将相邻2项的数字相加,就能得到下一层除了最边上2个1的所有数字。 听起来有点像递归的思想,我们不妨假设我们已经知道N-1层的数字,来计算一下N层的数字吧。
def _yanghui_trangle(n, result):
if n == 1:
return [1]
else:
return [sum(i) for i in zip([0] + result, result + [0])]
上面代码中,result表示N-1层杨辉三角的数字。实习上,我们在列表2端各补了一个0,然后计算相邻项的和,就可以直接得到结果。
稍微完善一下代码:
def yanghui_trangle(n):
def _yanghui_trangle(n, result):
if n == 1:
return [1]
else:
return [sum(i) for i in zip([0] + result, result + [0])]
pre_result = []
for i in xrange(n):
pre_result = _yanghui_trangle(i + 1, pre_result)
yield pre_result
if __name__ == "__main__":
for line in yanghui_trangle1(5):
print line
_yanghui_trangle可以用lambda的方式简写,但是可读性感觉会变差,所以还是保持现状好了。
tips: 上面的程序并没有考虑数据格式化的问题,也就是说输出不是完美的三角形。
鉴于最近在学习erlang,补上一个erlang版本的,性能上没有测试过,不过还是要惊叹于函数式语言的表达能力:
-module(yanghui).
-author(lfyzjck).
-export([triangle/1]).
triangle_next(P) ->
lists:zipwith(fun(X, Y) -> X+Y end, [0|P], P ++ [0]).
triangle(1) ->
[[1]];
triangle(N) ->
L = triangle(N - 1),
[H|_] = L,
[triangle_next(H)|L].

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.
