Python编程练习 codewars:List of all Rationals

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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zhanghp947

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值