我是编程和python的新手。我需要帮助编写一个几何级数,用于计算进展1,2,4,8,16 ......这是我到目前为止所做的:
def work_calc (days_worked, n):
temp=int(1)
if days_worked<2:
print (1)
else:
while temp <= days_worked:
pay1 = (temp**2)
pay = int(0)
pay += pay1
temp +=1
print ('your pay for ',temp-1,'is', pay1)
main()
现在它给了我这个输出:1, 4, 9, 16, 25
我需要:1,2,4,8,16,32...
Example:
Enter a number: 5
your value 1 is: 1
your value 2 is : 2
your value 3 is : 4
your value 4 is : 8
your value 5 is : 16
your total is: 31
提前感谢您的帮助和指导! P.S:在编程方面,我有时(大多数时候)就像一个愚蠢的金发女郎,所以感谢你的耐心......
答案 0 :(得分:2)
正如我所说,看起来你需要2
的力量:
def work_calc (days_worked, n):
for temp in range(days_worked):
print ('your pay for ', temp + 1, 'is', 2 ** temp)
如果你想打印字符串(不是你现在正在做的元组):
def work_calc (days_worked):
for temp in range(days_worked):
print 'your pay for {} is {}'.format(temp + 1, 2 ** temp)
>>> work_calc(5)
your pay for 1 is 1
your pay for 2 is 2
your pay for 3 is 4
your pay for 4 is 8
your pay for 5 is 16
请注意 - 您的代码正在计算temp
的平方,而不是2的幂,这就是为什么不起作用
答案 1 :(得分:2)
我知道这对你正在做的事情来说可能有些过分,你在其他答案中给出了很好的建议,如何解决你的问题,但是在这里介绍python的其他一些功能是其他一些方法: 列表理解:
def work_calc(days):
powers_of_two = [2**x for x in range(days)]
for i, n in enumerate(powers_of_two):
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(sum(powers_of_two)))
这是紧凑而整洁的但是会在内存中保存2 ^ n的整个列表,对于小n这不是问题但是对于大的可能是昂贵的。生成器表达式与列表推导非常相似,但推迟计算直到迭代结束。
def work_calc(days):
powers_of_two = (2**x for x in range(days))
total = 0
for i, n in enumerate(powers_of_two):
total += n
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(total))
必须将总计移动到滚动计算并且每次仍然计算2 ** n,生成器函数将避免功率计算:
import itertools
def powers_of_two():
n = 1
while True:
yield n
n *= 2
def work_calc(days):
total = 0
for i, n in enumerate(itertools.islice(powers_of_two(), days)):
total += n
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(total))
正如我所说的过度杀伤,但希望介绍python的其他一些功能。
答案 2 :(得分:0)
这是一个功课问题吗? (评论不足)
在序列1,2,4,8,16,32
中,每个术语是前一个术语的两倍。
所以,你可以保留上一学期的记录,并将其翻倍以获得下一学期。
正如其他人所提到的,这与计算2 ^ n相同(不像我之前所说的那样,n ^ 2),其中n是术语数。
print ('your pay for 1 is' 1)
prevpay = 1
while temp <= days_worked:
pay1 = prevpay*2
pay = int(0)
pay += pay1
temp +=1
prevpay = pay1
print ('your pay for ',temp-1,'is', pay1)