[MicroPython] Beginner, program with lists - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: [MicroPython] Beginner, program with lists (/thread-22349.html) |
[MicroPython] Beginner, program with lists - Hellon - Nov-09-2019 Hello So here I am a beginner in Python and I have an exercise that asks me to replace the repetition with the list but I can't understand how to use it Here is the code : from random import * from math import * n=int(input("n=")) a=0 b=0 c=0 d=0 e=0 f=0 g=0 h=0 j=0 k=0 l=0 for i in range(1,n+1): r=randint(1,6)+randint(1,6) if r==2: a=a+1 if r==3: b=b+1 if r==4: c=c+1 if r==5: d=d+1 if r==6: e=e+1 if r==7: f=f+1 if r==8: g=g+1 if r==9: h=h+1 if r==10: j=j+1 if r==11: k=k+1 if r==12: l=l+1 print("2:"+str(a)) print("3:"+str(b)) print("4:"+str(c)) print("5:"+str(d)) print("6:"+str(e)) print("7:"+str(f)) print("8:"+str(g)) print("9:"+str(h)) print("10:"+str(j)) print("11:"+str(k)) print("12:"+str(l))So i have this idea : from random import * from math import * n=int(input("n=")) list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]But I don't know how to use the list for the rest of the program RE: [MicroPython] Beginner, program with lists - ichabod801 - Nov-09-2019 First of all, don't name your list 'list'. That is a built-in function, and using it as a name may block code from using it. Second, you can assign by index in the list. So if you rename your list to 'counts', then counts[0] += 1 increases the first item in the list by 1. Also, counts[1] gives you the second item in the list.
RE: [MicroPython] Beginner, program with lists - Hellon - Nov-09-2019 Ok ! But what about the rest ? for i in range(1,n+1): r=randint(1,6)+randint(1,6) if r==2: a=a+1 if r==3: b=b+1 if r==4: c=c+1 if r==5: d=d+1 if r==6: e=e+1 if r==7: f=f+1 if r==8: g=g+1 if r==9: h=h+1 if r==10: j=j+1 if r==11: k=k+1 if r==12: l=l+1 print("2:"+str(a)) print("3:"+str(b)) print("4:"+str(c)) print("5:"+str(d)) print("6:"+str(e)) print("7:"+str(f)) print("8:"+str(g)) print("9:"+str(h)) print("10:"+str(j)) print("11:"+str(k)) print("12:"+str(l))How can I reduce that :/ Ok, so I managed to do that, is it ok or can I reduce/optimise it more ? from random import * from math import * n=int(input("n=")) sommes = [0]*11 for i in range(1,n+1): r=randint(1,6)+randint(1,6) if r==2: sommes[0] += 1 if r==3: sommes[1] += 1 if r==4: sommes[2] += 1 if r==5: sommes[3] += 1 if r==6: sommes[4] += 1 if r==7: sommes[5] += 1 if r==8: sommes[6] += 1 if r==9: sommes[7] += 1 if r==10: sommes[8] += 1 if r==11: sommes[9] += 1 if r==12: sommes[10] += 1 print(sommes) RE: [MicroPython] Beginner, program with lists - ichabod801 - Nov-10-2019 Look at all those ifs. Look what r is being compared to, and what index you are using with sommes. See a pattern? |