Python编程练习 codewars:List of all Rationals
Instructions
Here’s a way to construct a list containing every positive rational number:Build a binary tree where each node is a rational and the root is 1/1, with the following rules for creating the nodes below:
The value of the left-hand node below a/b is a/a+b
The value of the right-hand node below a/b is a+b/b
So the tree will look like this:
Now traverse the tree, breadth first, to get a list of rationals.
[ 1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, … ]
Every positive rational will occur, in its reduced form, exactly once in the list, at a finite index.In the kata, we will use tuples of type (int, int) to represent rationals, where (a, b) represents a / b
Use this method to create an infinite list of tuples:
def all_rationals() -> Generator[(int, int)]:
matching the list described above:
all_rationals => [(1, 1), (1, 2), (2, 1), (1, 3), (3, 2), …]
题目分析
这道题目呢是要我们用这个函数去生成一个数列,并且值得注意的是这个函数是没有参数传进去的。
那么这道题目呢,我是用了完全二叉树结点的性质:如果节点的下标为p(根节点的坐标从1开始),则其左子节点的坐标是2p,右子节点的坐标是2p+1。反之也可以由子节点的坐标q求出父节点的坐标q//2。下面放上我的代码。
我的代码
def all_rationals():
ls=[(1,1)]
for i in range(1000000):#这个参数可以随便设,意思是生成长度为n的数列
pi=(len(ls)+1)//2#求父节点的坐标
a,b=ls[pi-1]
ls.append((a,a+b))#求左子节点并加到列表中
ls.append((a+b,b)) #求右子节点并加到列表中
return ls