Python家庭作业 - 完美正方形的总和

时间:2016-02-07 00:00:39

标签: python

我需要有关python作业问题的帮助。

"假设有一个变量,h已经与正整数值相关联。编写计算小于h的完美正方形之和所需的代码,从1开始。(完美正方形是一个整数,如9,16,25,36,等于另一个整数的平方(在此情况3 * 3,4 * 4,5 * 5,6 * 6)。)将计算的总和与变量q相关联。例如,如果h为19,则将q分配给q,因为小于h的正方形(从1开始)是:1,4,9,16和30 == 1 + 4 + 9 + 16。 #34;

到目前为止,我已经非常接近正确但它总是会增加一个额外的数量。例如,投入19,而不是停在1,4,9,16,它也增加了25。

到目前为止我的代码

h_i=input()
h=int(h_i)
s=0
q=0
total=s**2
while total<=h:
     s+=1
     total=s**2
     q+=total
     print(total)
print(q)

6 个答案:

答案 0 :(得分:1)

我将使用更加“Pythonic”的列表理解方式建议一种不同的方法:

>>> highest = 19 # in your case this is h
lst = list (n**2 for n in range(1, highest + 1))
lst
[1, 4, 9, 16]
>>> print '\n'.join(str(p) for p in lst)
1
4
9
16

答案 1 :(得分:1)

我建议您修改代码以提高可读性和间距。此外,您可以从1(i = 1)开始计数,因为您必须指定正整数。

h = int(input('insert positive integer: '))
i = 1
total = 0

while total <= h:
    total += i ** 2
    i += 1

print(total)

答案 2 :(得分:1)

现在......对于完全不同的东西:

h = int(input())
n = int((h - 1) ** 0.5)
q = n * (n + 1) * (2*n + 1) // 6
print(q)

答案 3 :(得分:0)

您需要在循环结束时放置s+=1total=s**2,以便之前检查条件(我认为应该是total<h) >它被添加到q

h_i=input()
h=int(h_i)
s=0
q=0
total=s**2
while total<h:
     q+=total
     print(total)
     s+=1
     total=s**2
print(q)

答案 4 :(得分:0)

您关心的是n**2的当前值小于h。因此,请确保测试该值。

h = 19
n = 1
q = 0

while n**2 <= h:
    q += n**2
    n += 1

print("Sum of squares less than {} is: {}".format(h, q))

答案 5 :(得分:-1)

虽然我喜欢简单,但这是我的需要,我已经在实验室测试过,它有效:

q=0
n=0
while n*n<h:
q+=n*n
n+=1