Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append float to list?

I want to append float to list, but I got an error like this:

<ipython-input-47-08d9c3f8f180> in maxEs()
     12    Es = lists[0]*0.3862 + lists[1]*0.3091 + lists[2]*0.4884
     13    aaa = []
---> 14    Es.append(aaa)
     15 

 AttributeError: 'float' object has no attribute 'append'

I guess I can't append float to list. Can I add floats to list another way?

This is my code:

import math

def maxEs():
    for a in range(1, 101):
        for b in range(1,101):
            for c in range(1,101):
                if a+b+c == 100 :
                  lists = []
                  lists.append(a*0.01)
                  lists.append(b*0.01)
                  lists.append(c*0.01)
                  Es = lists[0]*0.3862 + lists[1]*0.3091 + lists[2]*0.4884
                  aaa = []
                  Es.append(aaa)
like image 786
SunHu Kim Avatar asked Feb 15 '26 14:02

SunHu Kim


2 Answers

I don't know what you want, but you are trying to append a list to a float not the other way round.

Should be

aaa.append(Es)
like image 189
user3684792 Avatar answered Feb 17 '26 04:02

user3684792


The other answer already explained the main problem with your code, but there is more:

  • as already said, it has to be aaa.append(Es) (you did it right for the other list)
  • speaking of the other list: you don't need it at all; just use the values directly in the formula
  • aaa is re-initialized and overwritten in each iteration of the loop; you should probably move it to the top
  • you do not need the inner loop to find c; once you know a and b, you can calculate c so that it satisfies the condition
  • you can also restrict the loop for b, so the result does not exceed 100
  • finally, you should probably return some result (the max of aaa maybe?)

We do not know what exactly the code is trying to achieve, but maybe try this:

def maxEs():
    aaa = []
    for a in range(1, 98 + 1):
        for b in range(1, 99-a + 1):
            c = 100 - a - b
            Es = 0.01 * (a * 0.3862 + b * 0.3091 + c * 0.4884)
            aaa.append(Es)
    return max(aaa)
like image 38
tobias_k Avatar answered Feb 17 '26 05:02

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!