GVKun编程网logo

Pascal的Python三角形(python 三角形)

11

以上就是给各位分享Pascal的Python三角形,其中也会对python三角形进行解释,同时本文还将给你拓展7-4jmu-python-判断是否构成三角形(10分)、ipythonparallel的

以上就是给各位分享Pascal的Python三角形,其中也会对python 三角形进行解释,同时本文还将给你拓展7-4 jmu-python-判断是否构成三角形 (10 分)、ipython parallel的Python名称空间问题、java – pascal三角形算法的时间复杂度、java – Pascal的三角格式等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

Pascal的Python三角形(python 三角形)

Pascal的Python三角形(python 三角形)

作为Python的学习经验,我正在尝试编写自己的Pascal三角形版本。我花了几个小时(因为我刚刚开始),但是我得到了以下代码:

pascals_triangle = []def blank_list_gen(x):    while len(pascals_triangle) < x:        pascals_triangle.append([0])def pascals_tri_gen(rows):    blank_list_gen(rows)    for element in range(rows):        count = 1        while count < rows - element:            pascals_triangle[count + element].append(0)            count += 1    for row in pascals_triangle:        row.insert(0, 1)        row.append(1)    pascals_triangle.insert(0, [1, 1])    pascals_triangle.insert(0, [1])pascals_tri_gen(6)for row in pascals_triangle:    print(row)

哪个返回

[1][1, 1][1, 0, 1][1, 0, 0, 1][1, 0, 0, 0, 1][1, 0, 0, 0, 0, 1][1, 0, 0, 0, 0, 0, 1][1, 0, 0, 0, 0, 0, 0, 1]

但是,我不知道从这里去哪里。几个小时我一直在撞墙。我想强调,我不希望你为我做这件事;朝正确的方向推动我。作为清单,我的代码返回

[[1], [1, 1], [1, 0, 1], [1, 0, 0, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1]]

谢谢。

编辑:我采取了一些好的建议,并且我完全重写了我的代码,但是现在我遇到了另一个问题。这是我的代码。

import mathpascals_tri_formula = []def combination(n, r):    return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r)))def for_test(x, y):    for y in range(x):        return combination(x, y)def pascals_triangle(rows):    count = 0    while count <= rows:        for element in range(count + 1):            [pascals_tri_formula.append(combination(count, element))]        count += 1pascals_triangle(3)print(pascals_tri_formula)

但是,我发现输出有点不可取:

[1, 1, 1, 1, 2, 1, 1, 3, 3, 1]

我怎样才能解决这个问题?

答案1

小编典典

确定代码查看:

import math# pascals_tri_formula = [] # don''t collect in a global variable.def combination(n, r): # correct calculation of combinations, n choose k    return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r)))def for_test(x, y): # don''t see where this is being used...    for y in range(x):        return combination(x, y)def pascals_triangle(rows):    result = [] # need something to collect our results in    # count = 0 # avoidable! better to use a for loop,     # while count <= rows: # can avoid initializing and incrementing     for count in range(rows): # start at 0, up to but not including rows number.        # this is really where you went wrong:        row = [] # need a row element to collect the row in        for element in range(count + 1):             # putting this in a list doesn''t do anything.            # [pascals_tri_formula.append(combination(count, element))]            row.append(combination(count, element))        result.append(row)        # count += 1 # avoidable    return result# now we can print a result:for row in pascals_triangle(3):    print(row)

印刷品:

[1][1, 1][1, 2, 1]

帕斯卡三角形的解释:

这是“
n选择k”的公式(即,从n项的有序列表中有多少种不同的方式(不考虑顺序),我们可以选择k项):

from math import factorialdef combination(n, k):     """n choose k, returns int"""    return int((factorial(n)) / ((factorial(k)) * factorial(n - k)))

一个评论者问这是否与itertools.combinations有关-确实如此。“ n select k”可以通过组合中元素列表的长度来计算:

from itertools import combinationsdef pascals_triangle_cell(n, k):    """n choose k, returns int"""    result = len(list(combinations(range(n), k)))    # our result is equal to that returned by the other combination calculation:    assert result == combination(n, k)    return result

让我们看看这个演示:

from pprint import pprintptc = pascals_triangle_cell>>> pprint([[ptc(0, 0),],             [ptc(1, 0), ptc(1, 1)],             [ptc(2, 0), ptc(2, 1), ptc(2, 2)],            [ptc(3, 0), ptc(3, 1), ptc(3, 2), ptc(3, 3)],            [ptc(4, 0), ptc(4, 1), ptc(4, 2), ptc(4, 3), ptc(4, 4)]],           width = 20)[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]

我们可以避免使用嵌套列表理解来重复自己:

def pascals_triangle(rows):    return [[ptc(row, k) for k in range(row + 1)] for row in range(rows)]>>> pprint(pascals_triangle(15))[[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], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1], [1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1], [1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1], [1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1], [1, 13, 78, 286, 715, 1287, 1716, 1716, 1287, 715, 286, 78, 13, 1], [1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1]]

递归定义:

我们可以使用三角形所示的关系来递归定义(效率较低,但数学上可能更优雅的定义):

 def choose(n, k): # note no dependencies on any of the prior code     if k in (0, n):         return 1     return choose(n-1, k-1) + choose(n-1, k)

有趣的是,您可以看到每一行的执行时间逐渐变长,因为每一行必须重新计算上一行中的几乎每个元素两次:

for row in range(40):    for k in range(row + 1):        # flush is a Python 3 only argument, you can leave it out,        # but it lets us see each element print as it finishes calculating        print(choose(row, k), end='' '', flush=True)     print()11 11 2 11 3 3 11 4 6 4 11 5 10 10 5 11 6 15 20 15 6 11 7 21 35 35 21 7 11 8 28 56 70 56 28 8 11 9 36 84 126 126 84 36 9 11 10 45 120 210 252 210 120 45 10 11 11 55 165 330 462 462 330 165 55 11 11 12 66 220 495 792 924 792 495 220 66 12 11 13 78 286 715 1287 1716 1716 1287 715 286 78 13 11 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 11 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 11 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 11 17 136 680 2380 6188 12376 19448 24310 24310 19448 12376 6188 2380 680 136 17 11 18 153 816 3060 8568 18564 31824 43758 48620 43758 31824 18564 8568 3060 816 ...

厌倦了Ctrl-C退出时,它会变得非常慢非常快…

7-4 jmu-python-判断是否构成三角形 (10 分)

7-4 jmu-python-判断是否构成三角形 (10 分)

7-4 jmu-python-判断是否构成三角形 (10 分)
 

输入三角形的三边,判断是否能构成三角形。若能构成输出yes,否则输出no。

输入格式:

在一行中直接输入3个整数,3个整数之间各用一个空格间隔,没有其他任何附加字符。

输出格式:

直接输出yes或no,没有其他任何附加字符。

输入样例1:

3 4 5

输出样例1:

yes

输入样例2:

1 2 3

输出样例2:

no

a,b,c=input().split()
a,b,c=eval(a),eval(b),eval(c)
if a+b>c and a+c>b and b+c>a:
    print("yes")
else:
    print("no")

  

ipython parallel的Python名称空间问题

ipython parallel的Python名称空间问题

我开始尝试使用IPython并行工具并遇到问题。我用以下命令启动python引擎:

ipcluster start -n 3

然后,以下代码运行良好:

from IPython.parallel import Clientdef dop(x):    rc = Client()    dview = rc[:]    dview.block=True    dview.execute(''a = 5'')    dview[''b''] = 10    ack = dview.apply(lambda x: a+b+x, x)    return ackack = dop(27)print ack

会按原样返回[42,42,42]。但是,如果我将代码分成不同的文件:dop.py:

from IPython.parallel import Clientdef dop(x):    rc = Client()    dview = rc[:]    dview.block=True    dview.execute(''a = 5'')    dview[''b''] = 10    print dview[''a'']    ack = dview.apply(lambda x: a+b+x, x)    return ack

并尝试以下操作:

from dop import dopack = dop(27)print ack

我从每个引擎收到错误:

[0:apply]: NameError: global name ''a'' is not defined[1:apply]: NameError: global name ''a'' is not defined[2:apply]: NameError: global name ''a'' is not defined

我不明白…为什么我不能将函数放入另一个文件中并导入呢?

答案1

小编典典

快速回答:与装饰你的功能@interactiveIPython.parallel.util[1]如果你希望它有机会获得发动机的全局命名空间:

从IPython.parallel.util导入交互式f =交互式(lambda x:a + b + x)ack = dview.apply(f,x)

实际说明:

IPython用户名称空间本质上是模块__main__。当您执行此操作时,将在此处运行代码execute(''a = 5'')

如果以交互方式定义函数,则其模块也是__main__

lam = lambda x:a + b + xlam .__ module__''__主要__''

当引擎反序列化一个函数时,它会在该函数模块的相应全局命名空间中进行反序列化,因此__main__,您在客户端中定义的函数也在__main__引擎上定义,因此可以访问a

将其放入文件并导入后,这些功能将不再附加到__main__,而是模块dop

从dop导入dopdop .__ module__''dop''

该模块中常规定义的所有函数(包括lambda)都将具有该值,因此在引擎上解压缩它们时,其全局名称空间将是该dop模块的全局名称空间, 而不是
该模块的全局名称空间__main__,因此您的“ a”不可访问。

出于这个原因,IPython提供了一个简单的@interactive装饰器__main__,无论该函数实际定义在哪里,它都会像在中定义的那样对任何函数进行解包。

有关差异的示例,请执行以下操作dop.py

从IPython.parallel导入客户端从IPython.parallel.util导入交互式a = 1def dop(x):    rc = Client()    dview = rc [:]    dview [''a''] = 5    f =λx:a + x    返回dview.apply_sync(f,x)def idop(x):    rc = Client()    dview = rc [:]    dview [''a''] = 5    f =交互式(lambda x:a + x)    返回dview.apply_sync(f,x)

现在,dop将在dop模块中idop使用“ a”,并在引擎名称空间中使用“
a”。两者之间的唯一区别是传递给apply的函数包装在@interactive

从dop导入dop,idop打印dop(5)#6打印idop(5)#10

[1]:在IPython> = 0.13(即将发行的版本)中,@interactive它也from IPython.parallel importinteractive应该作为,应该总是存在。

java – pascal三角形算法的时间复杂度

java – pascal三角形算法的时间复杂度

负责解决以下问题(Pascal Triangle),看起来像这样.
[
     [1],[1,1],2,3,4,6,1]
]

我已经成功实现了代码(见下文),但我很难搞清楚这个解决方案的时间复杂度.列表的操作次数是1 2 3 4 …. n操作次数减少到n ^ 2数学如何工作并转换为Big-O表示法?

我认为这类似于高斯公式n(n 1)/ 2所以O(n ^ 2)但我可能是错的任何帮助非常感谢

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        if(numRows < 1) return new ArrayList<List<Integer>>();;
        List<List<Integer>> pyramidVal = new ArrayList<List<Integer>>();

        for(int i = 0; i < numRows; i++){
            List<Integer> tempList = new ArrayList<Integer>();
            tempList.add(1);
            for(int j = 1; j < i; j++){
                tempList.add(pyramidVal.get(i - 1).get(j) + pyramidVal.get(i - 1).get(j -1));
            }
            if(i > 0) tempList.add(1);
            pyramidVal.add(tempList);
        }
        return pyramidVal;
    }
}

解决方法

复杂度是O(n ^ 2).

代码中每个元素的计算都是在恒定时间内完成的. ArrayList访问是常量时间操作,也是插入,分摊的常量时间. Source:

The size,isEmpty,get,set,iterator,and listIterator operations run
in constant time. The add operation runs in amortized constant time

你的三角形有1 2 …… n个元素.这是arithmetic progression,总和为n *(n 1)/ 2,其为O(n ^ 2)

java – Pascal的三角格式

java – Pascal的三角格式

作业是创建Pascal的三角形而不使用数组.我有一个生成下面三角形值的方法.该方法接受用户希望打印的最大行数的整数.
public static void triangle(int maxRows) {
    int r,num;
    for (int i = 0; i <= maxRows; i++) {
        num = 1;
        r = i + 1;
        for (int col = 0; col <= i; coL++) {
            if (col > 0) {
                num = num * (r - col) / col;    
            }
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

我需要格式化三角形的值,使其看起来像一个三角形:

我不能为我的生活找出如何做到这一点.请记住,我是Java编程的初学者.

谢谢!

@H_301_10@

解决方法

这是一个很好的开始,在那里做功课,我会休息给你:
int maxRows = 6;
int r,num;
for (int i = 0; i <= maxRows; i++) {
    num = 1;
    r = i + 1;
    //pre-spacing
    for (int j = maxRows - i; j > 0; j--) {
        System.out.print(" ");
    }
    for (int col = 0; col <= i; coL++) {
        if (col > 0) {
            num = num * (r - col) / col;
        }
        System.out.print(num + " ");
    }
    System.out.println();
}
@H_301_10@ @H_301_10@

总结

以上是小编为你收集整理的java – Pascal的三角格式全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

今天的关于Pascal的Python三角形python 三角形的分享已经结束,谢谢您的关注,如果想了解更多关于7-4 jmu-python-判断是否构成三角形 (10 分)、ipython parallel的Python名称空间问题、java – pascal三角形算法的时间复杂度、java – Pascal的三角格式的相关知识,请在本站进行查询。

本文标签: