Your list results
has two elements. You iterate over it, but on each iteration, you update both the heads and tails counts, so they get updated twice (once on each iteration). Remove your for slot in results
and just unindent the code inside it so it only runs once.
Why are the values being added on to my list twice each time? Issue in python
Frage
I'm having trouble getting the list for the heads and tails code I'm trying to write.
import random
list4heads=[]
maximums=[]
base=10
list4tails=[]
percent4heads=[]
percent4tails=[]
for exponent in range (1,6):
ranges=base**exponent
results=[0,0]
maximums.append(ranges)
for num in range (1,ranges+1):
flip=random.randint(0,num)
if flip%2==0:
results[0]+=1
elif flip%2 != 0:
results[1]+=1
for slot in results:
list4heads.append(results[0])
list4tails.append(results[1])
hp= results[0]/(results[0]+results[1])
tp= results[1]/(results[0]+results[1])
percent4heads.append(hp)
percent4tails.append(tp)
print(list4heads, '\n', list4tails)
print()
print()
print(percent4heads, '\n', percent4tails)
I need each value to be added on once, but my output is looking like this.
[6, 6, 54, 54, 502, 502, 5053, 5053, 49746, 49746]
[4, 4, 46, 46, 498, 498, 4947, 4947, 50254, 50254]
[0.6, 0.6, 0.54, 0.54, 0.502, 0.502, 0.5053, 0.5053, 0.49746, 0.49746]
[0.4, 0.4, 0.46, 0.46, 0.498, 0.498, 0.4947, 0.4947, 0.50254, 0.50254]
Why is each value being added on twice? Thanks in advance!
Lösung
Andere Tipps
You do
for slot in results:
and results has 2 elements.
This means that these two lines are called twice:
list4heads.append(results[0])
list4tails.append(results[1])
Remove this line:
for slot in results:
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow