im writing a python function to do the following, add numbers from each line, so i can then find the average. this is what my file looks like:
-2.7858521
-2.8549764
-2.8881847
2.897689
1.6789098
-0.07865
1.23589
2.532461
0.067825
-3.0373958
Basically ive written a program that does a for loop for each line, incrementing the counter of lines and setting each line to a float value.
counterTot = 0
with open('predictions2.txt', 'r') as infile:
for line in infile:
counterTot += 1
i = float(line.strip())
now is the part i get a lil stuck
totalSum =
mean = totalSum / counterTot
print(mean)
As you can tell im new to python, but i find it very handy for text analysis work, so im getting into it.
Extra function
I was also looking into an extra feature. but should be a seperate function as above.
counterTot = 0
with open('predictions2.txt', 'r') as infile:
for line in infile:
counterTot += 1
i = float(line.strip())
if i > 3:
i = 3
elif i < -3:
i = -3
As you can see from the code, the function decides if a number is bigger than 3, if so, then make it 3. If number is smaller than -3, make it -3. But im trying to output this to a new file, so that it keeps its structure in tact. For both situations i would like to keep the decimal places. I can always round the output numbers myself, i just need the numbers intact.
You can do this without loading the elements into a list by cheekily using fileinput and retrieve the line count from that:
import fileinput
fin = fileinput.input('your_file')
total = sum(float(line) for line in fin)
print total / fin.lineno()
You can use enumerate here:
with open('predictions2.txt') as f:
tot_sum = 0
for i,x in enumerate(f, 1):
val = float(x)
#do something with val
tot_sum += val #add val to tot_sum
print tot_sum/i #print average
#prints -0.32322842
I think you want something like this:
with open('numbers.txt') as f:
numbers = f.readlines()
average = sum([float(n) for n in numbers]) / len(numbers)
print average
Output:
-0.32322842
It reads your numbers from numbers.txt, splits them by newline, casts them to a float, adds them all up and then divides the total by the length of your list.
Do you mean you need to change 5.1234 to 3.1234 and -8.5432 to -3.5432 ?
line = " -5.123456 "
i = float(line.strip())
if i > 3:
n = int(i)
i = i - (n - 3)
elif i < -3:
n = int(i)
i = i - (n + 3)
print(i)
it give you
-3.123456
Edit:
shorter version
line = " -5.123456 "
i = float(line.strip())
if i >= 4:
i -= int(i) - 3
elif i <= -4:
i -= int(i) + 3
print(i)
Edit 2:
If you need to change 5.1234 to 3.0000 ("3" and 4x "0") and -8.7654321 to -3.0000000 ("-3" and 7x "0")
line = " -5.123456 "
line = line.strip()
i = float(line)
if i > 3:
length = len(line.split(".")[1])
i = "3.%s" % ("0" * length) # now it will be string again
elif i < -3:
length = len(line.split(".")[1])
i = "-3.%s" % ("0" * length) # now it will be string again
print(i)
Here is a more verbose version. You could decide to replace invalid lines (if any) by a neutral value instead of ignoring it
numbers = []
with open('myFile.txt', 'r') as myFile:
for line in myFile:
try:
value = float(line)
except ValueError, e:
print line, "is not a valid float" # or numbers.append(defaultValue) if an exception occurred
else:
numbers.append(value)
print sum(numbers) / len(numbers)
For your second request here is the most straightforward solution (more solutions here)
def clamp(value, lowBound, highBound):
return max(min(highBound, value), lowBound)
Applying it to our list:
clampedValues = map(lambda x: clamp(x, -3.0, 3.0), numbers)
Related
Basically, this is my task. Extract numbers from a text file and then calculate the sum of them.
I wrote the code successfully and but it doesn't work fine with 2 or more digit numbers and negative numbers. What should i do?
f = open('file6.txt', 'r')
suma = 0
file = f.readlines()
for line in file:
for i in line:
if i.isdigit() == True:
suma += int(i)
print("The sum is ", suma)
file6.txt:
1
10
Output:
The sum is 2
In your case, you are going line by line first through the loop and looking at every digit ( in second loop ) to add.
And /n at the end of elements make the .isDigit() function disabled to find the digits.
So your updated code should be like this :
f = open('file6.txt', 'r')
suma = 0
file = f.readlines()
for line in file:
if line.strip().isdigit():
suma += int(line)
print("The sum is ", suma)
Hope it helps!
Use re.split to split the input into words on anything that is not part of a number. Try to convert the words into numbers, silently skip if this fails.
import re
sum_nums_in_file = 0
with open('file6.txt') as f:
for line in f:
for word in re.split(r'[^-+\dEe.]+', line):
try:
num = float(word)
sum_nums_in_file += num
except:
pass
print(f"The sum is {sum_nums_in_file}")
This works for example on files such as this:
-1 2.0e0
+3.0
So I'm trying to calculate the sum and average of a text document filled with 10000 numbers.ยจ
This is my code:
with open("\\Users\\saksa\\python_courses\\1DV501\\assign3\\file_10000integers_A.txt", "r") as f:
total = 0
number_of_ints = 0
for line in f:
for i in line:
if i.isdigit() == True:
total += int(i)
number_of_ints +=1
print (total)
print (number_of_ints)
The document is formated like: 215, 631, 731, 225, 315, etc in multiple lines
The problem is that it reads every number 1 by 1. So 100 becomes 1 + 0 + 0.
I think I need to use split to make it work but I cant figure out how to.
You can iterate over each line in a file.
And you can split each line by a ',' and add each number
with open("\\Users\\saksa\\python_courses\\1DV501\\assign3\\file_10000integers_A.txt", "r") as f:
total = 0
number_of_ints = 0
for line in f:
print(line)
for num in line.split(','):
print(num)
total += int(num)
number_of_ints += 1
print(total)
print(number_of_ints)
You will need to add some logic to ensure the numbers are numbers
You should use split() function:
line = "110, 23400, 34569, 23567"
line.replace(" ", "") # Get rid of unnecessary spacebars
total = 0
number_of_ints = 0
for i in line.split(","):
# Here you can do whatever you want
try:
i = int(i)
total += int(i)
number_of_ints += 1
except:
pass
I have written a code that extracts floating point numbers from a
text file and produces a list of the numbers.
My challenge is summing the consecutive numbers and finding the
average of the numbers.
I am not allowed to use the sum function and I am new to python ..
this the code I have written so far ,
what can I do to add through the list
fh = open(fname)
for line in fh:
if line.startswith("X-DSPAM-Confidence:") : continue
# print(line)
count = 0
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
count = count + 1
# print(count)
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
# print(line)
xpos = line.find(' ')
# print(xpos)
num = line[xpos : ]
# print(float(num))
fnum = float(num)
# print(fnum)
total = 0
for i in fnum:
total += int(i)
print(total)
Error:"float object not iterable on line 24" ... line 24 is the 4th for loop
First an open file is iterable only once, and your code shows 4 loops starting with for line in fh:. After first loop, the file pointer will reach the end of file, and the following loops should immediately return. For that reason with should be prefered.
Next somewhere in the loop you get a float value in fnum. Just initialize total before starting the loop, and add fnum when you get it:
total = 0
with open(fname) as fh:
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
# print(line)
xpos = line.find(' ')
# print(xpos)
num = line[xpos : ]
# print(float(num))
fnum = float(num)
# print(fnum)
total += fnum
# print(total)
with ensures that the file will be cleanly closed at the end of the loop.
fnum is a float. It's not an array, therefore it's not iterable and cannot be iterated in a for loop.
You probably don't need an array to determine the total and the average:
fname = "c:\\mbox-short.txt"
fh = open(fname)
count = 0
total = 0
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
xpos = line.find(' ')
num = line[xpos : ]
fnum = float(num)
total += fnum
count += 1
print("Total = " + str(total))
print("Average = " + str(total / count))
print("Number of items = " + str(count))
You don't have to use startsWith in this case. Better to use split for each line of the file. Each line will split all the words to a list. Then using the indexes you look for, X-DSPAM-Confidence:. If it exists then take the corresponding value of interest. In this case it is index number 1. Below is the code:
total = 0
number_of_items = 0
with open("dat.txt", 'r') as f:
for line in f:
fields = line.split()
if fields != []:
if fields[0] == "X-DSPAM-Confidence:":
number_of_items += 1
total += float(fields[1])
print(total)
print(number_of_items)
avg = (total/number_of_items)
print(avg)
I saved your data in a text file names, "dat.txt".
Hope it helps !!!
def main():
infile = open('numbers.txt','r')
evenTotal = 0
oddTotal = 0
line = infile.readline()
while line != '':
total += int(line)
line = infile.readline()
print('The total for the even numbers is',evenTotal)
print('The total for the odd numbers is',oddTotal)
infile.close()
print('All done!')
main()
I trying to make it so that the program reads the numbers from a file in its directory and then separates, calculates and displays the total of the two sets. The thing I am having trouble with is the part in the middle with the identification of the odds and the evens. I do know that the while loop I have written in the middle calculates the total but I don't know how to modify it to make it so it does what I want it to do.
from itertools you can use the partition recipe to partition into even and odd and return the sum of those
from itertools import ifilterfalse,imap,ifilter,tee
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return ifilterfalse(pred, t1), ifilter(pred, t2)
def is_odd(x):
return bool(x%2)
list_of_ints = imap(int,filter(lambda x:x.strip().isdigit(),infile))
odds, evens= partition(is_odd,list_of_ints)
print sum(evens),sum(odds)
it will likely be a little bit slower than freddies answer ...
but it is a good pattern to know
or as #JonClements pointed out in chat
r = range(11)
d = dict.fromkeys([0, 1], 0)
for i in r: d[i % 2] += i
is a neat way to do it
In order to check if a number is odd or even, you should use the modulus operator.
if an integer is evenly divisible by 2, it will be even, otherwise, it is odd.
So...
while line != '':
if int(line) % 2 == 0:
evenTotal += int(line)
else
oddTotal += int(line)
line = infile.readline()
use this for even number
def even_numbers(maximum):
return_string = ""
for x in range(2,maximum+1,2):
return_string += str(x) + " "
return return_string.strip()
# With this program in Python you will check a document for even and odd numbers and
# also it skips any text
# It also writes 2 extra files Oddfile and Evenfile
import re
fhand = open('numbers.txt') # file with numbers odd/even or even filled with text
text = fhand.read()
y = re.findall('[0-9]+', text)
sumeven = 0
sumodd = 0
Even = []
Odd = []
Oddfile=open('Oddfile.txt','w')
Evenfile=open('Evenfile.txt','w')
for number in y:
if (int(number) % 2) == 0:# Checks if the number is even
sumeven = sumeven + int(number)
Even.append(int(number))
Evenfile.write(str(number) + '\n')
if (int(number) % 2) == 1:# Checks if the number is odd
sumodd = sumodd + int(number)
Odd.append(int(number))
Oddfile.write(str(number) + '\n')
print("Even List is : ", Even)
print("Odd List is : ", Odd)
I'm trying to get my code to go through and pop-out after some math has been done. The file being summed is just lists of numbers on separate lines. Could you give me some pointers to make this work because I am stumped.
EDIT:
I'm trying to get the transition from the main function to Checker function working correctly. I also need some help with slicing. The numbers being imported from the file are like this:
136895201785
155616717815
164615189165
100175288051
254871145153
So in my Checker funtion I want to add the odd numbers from left to right together. For example, for the first number, I would want to add 1, 6, 9, 2, 1, and 8.
Full Code:
def checker(line):
flag == False
odds = line[1 + 3+ 5+ 9+ 11]
part2 = odds * 3
evens = part2 + line[2 + 4 +6 +8 +10 +12]
part3 = evens * mod10
last = part3 - 10
if last == line[-1]:
return flag == True
def main():
iven = input("what is the file name ")
with open(iven) as f:
for line in f:
line = line.strip()
if len(line) > 60:
print("line is too long")
elif len(line) < 10:
print("line is too short")
elif not line.isdigit():
print("contains a non-digit")
elif check(line) == False:
print(line, "error")
To get the odd numbers:
odds = line[1::2]
and the evens:
evens = part2 + line[::2]
Unfortunately none of the parts of your checker function work. It seems you probably need something like this:
def check_sums(line):
numbers = [int(ch) for ch in line] # convert text string to a series of integers
odds = sum(numbers[1::2]) # sum of the odd-index numbers
evens = sum(numbers[::2]) # sum of the even-index numbers
if numbers[-1] == (odds * 3 + evens) % 10:
return True
else:
return False
numbers[1::2] says "get the slice of numbers from 1 until the end with step 2", while numbers[::2] says "get the slice of numbers from the beginning until the end with step 2". (See this question or the documentation for more explanation.)
Note that the operator for a modulus is x % 10. I assume that's what you're trying to do with evens * mod10. In your original code you also subtract 10 (last = part3 - 10), but that makes no sense so I have omitted that step.
This returns the following for the input lines you mention:
print(check_sums('136895201785')) # >>> False
print(check_sums('155616717815')) # >>> True
print(check_sums('164615189165')) # >>> True
print(check_sums('100175288051')) # >>> False
print(check_sums('254871145153')) # >>> False
Your main function is fine except that it refers to the function as check when you had named it checker.