So I have an assignment that I am working on in python, where I can only splice using the : splice method (i.e group= strg [:index]). For some reason splice refuses to see anything past 2 digits when its numbers. Words are fine but digits are being clipped.
here is my code:
import sys
# set up for for loop
length = len(sys.argv)
for i in range(1, length):
strg = sys.argv[i]
#finds name
index = strg.find(':')
name = strg[:index]
strg = strg[index+1:]
index = strg.find(',')
total = 0
count = 0
while (index != -1):
group = strg[:index]
try:
num = int(group)
except:
break
else:
print(num)
total = total+num
count = count+1
strg = strg[index+1:]
print(count)
avg = total/count
print(name+", average:", avg)
input: Neda:90,80,70,90,50 John:80,100,30 Mary:20,100,90,80
my output:
90
80
70
90
50
5
Neda, average: 76.0
80
10
2
John, average: 45.0
20
10
2
Mary, average: 15.0
intended output:
90
80
70
90
50
5
Neda, average: 76.0
80
100
30
3
John, average: 70.0
20
100
90
80
4
Mary, average: 72.5
A simple fix would be to move
index = strg.find(',')
into the inner loop and test its result to determine how to extract the next number:
import sys
for string in sys.argv[1:]:
# find name
index = string.find(':')
name = string[:index]
total = 0
count = 0
while index != -1:
string = string[index+1:]
index = string.find(',')
if index == -1:
text = string[index+1:]
else:
text = string[:index]
try:
number = int(text)
except ValueError:
break
print(number)
total = total + number
count = count + 1
print(count)
avg = total/count
print(name + ", average:", avg)