Brian
Brian

Reputation: 151

optimizing my Benfold's law program

lines=[]
count1 = 0
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0
allcount = 0

with open('city_all.txt', 'r') as file:
    for line in file:
        lines.append(line.strip())

for x in range(0,len(lines)):
    if lines[x].isdigit():
        allcount+=1
        string = lines[x]
        if string[0]=="1":
            count1+=1
        elif string[0]=="2":
            count2+=1
        elif string[0]=="3":
            count3+=1
        elif string[0]=="4":
            count4+=1
        elif string[0]=="5":
            count5+=1
        elif string[0]=="6":
            count6+=1
        elif string[0]=="7":
            count7+=1
        elif string[0]=="8":
            count8+=1
        elif string[0]=="9":
            count9+=1

print(count1/allcount)
print('{:.1%}'.format(count1/allcount))

Wondering if there is anyway to not have to declare all my variables, and compact all the if statements?Trying to make a program to help compute Benfold's law, so I am putting a txt file into a list, then going through each element and checking what the starting digit is.

Upvotes: 0

Views: 62

Answers (1)

Hyperboreus
Hyperboreus

Reputation: 32439

You can simplify it a bit:

counts = [0 for _ in range (10) ]

with open('city_all.txt', 'r') as f:
    for line in (x.strip () for x in f):
        if line.isdigit():
            allcount += 1
            try: counts[int(line)] += 1
            except IndexError: pass

Upvotes: 2

Related Questions