小编ggo*_*don的帖子

Python 2.7 - 续分数扩展 - 理解错误

我编写了这段代码来计算使用欧几里德算法的有理数N的连续分数展开:

from __future__ import division

def contFract(N):
    while True:
        yield N//1
        f = N - (N//1)
        if f == 0:
            break
        N = 1/f
Run Code Online (Sandbox Code Playgroud)

如果说N是3.245,则函数永远不会结束,因为显然f永远不等于0.扩展的前10个术语是:

[3.0,4.0,12.0,3.0,1.0,247777268231.0,4.0,1.0,2.0,1.0]

这显然是一个错误,因为实际扩展只是:

[3; 4,12,3,1]或[3; 4,12,4]

是什么原因引起了这个问题?这是某种舍入错误吗?

python division integer-division fractions continued-fractions

5
推荐指数
1
解决办法
405
查看次数

Python - 是五角形数字检查

我正在尝试写一张支票,以确定数字是否为五边形.五角形数字是由公式生成的数字:

PN = N(3N-1)/ 2

即第一个五边形数字是:

1,5,12,22,35,51,70,92,117,145,......

当答案应该为True时,我的代码会抛出False,因此显然不正确,但我很难理解为什么.它如下:

from math import sqrt
def is_pent(n):
    ans = any((x*((3*x)-1))/2 == n for x in range(int(sqrt(n))))
    return ans
Run Code Online (Sandbox Code Playgroud)

我会感谢一些帮助!

python math sequence

4
推荐指数
1
解决办法
1432
查看次数

从列表中调用函数 - Python

我有一个字符串列表,我想为字符串中的每个字符调用一个函数。当我为每个函数分配变量时,我不希望它们运行,我只想在迭代字符串时调用它们。这是我的代码:

import random

def make_s():
    result = ''

    V = make_v
    C = make_c
    P = make_p
    B = make_b

    structs = ['VPCVBCC', 'VCVVC', 'VVPCC', 'VCVBCC', 'VPCCVBC', 'VCVCC', 'VPCBC', \
            'VVPCVBCC', 'VCVC', 'VPCVVBC']

    struct = random.choice(structs)

    for elem in struct:
        /* Call function defined above and add the result to the result string */
        result += elem()

    return result
Run Code Online (Sandbox Code Playgroud)

这样做的最佳方法是什么?

非常感谢 :)

python function call

3
推荐指数
1
解决办法
8181
查看次数

Python - 从素数列表中删除包含偶数的素数

我想写一个程序,它从素数列表中删除包含偶数位的所有素数.

任何人都可以解释为什么这个代码返回正确的结果如果limit = 200,但如果limit = 300则返回错误?

def odd_primes(limit):
    r = list(gen_primes(limit))
    for i in r[:]:
        for j in str(i):
            if int(j)%2==0:
                r.remove(i)
return r
Run Code Online (Sandbox Code Playgroud)

哪个gen_primes(limit)是在限制下返回所有素数的发电机.

如果limit = 200则返回:

[3, 5, 7, 11, 13, 17, 19, 31, 37, 53, 59, 71, 73, 79, 97, 113, 131, 137, 139, 151, 157, 173, 179, 191, 193, 197, 199]
Run Code Online (Sandbox Code Playgroud)

但如果限制为300,我会收到此错误:

line 19, in odd_primes
r.remove(i)
ValueError: list.remove(x): x not in list
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我该如何纠正呢?

python primes loops list

1
推荐指数
1
解决办法
130
查看次数

Python - Project Euler#57,理解错误

当我运行此代码来计算根2连续分数的收敛:

def root_two_expansion():
    total=0
    a=(3,2)
    b=(7,5)
    x=3
    while x<=1000:
        c=((sum(a)+sum(b)),sum(b))
        if len(str(c[0]))>len(str(c[1])):
            total+=1
        a=b,b=c
        x+=1
    return total

print root_two_expansion()
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

069.506.py",第7行,在root_two_expansion中c =((sum(a)+ sum(b)),sum(b))TypeError:'int'对象不可迭代

为什么是这样?我不明白代码在哪个阶段尝试迭代int.我会很感激任何建议.

python iteration

0
推荐指数
1
解决办法
62
查看次数