Converting a list to integers - python-3.x

here is the problem:
Write a program that computes and prints the average of the numbers in a text file. You should make use of two higher-order functions to simplify the design.
An example of the program input and output is shown below:
Enter the input file name: numbers.txt
The average is 69.83333333333333
here are the numbers in numbers.txt:
45 66 88
100 22 98
and here is my code:
file = input("Enter the input file name: ")
with open(file) as f:
from functools import reduce
def add(x, y): return x + y
data = [45, 66, 88, 100, 22, 98]
total = reduce(add, data)
avg = total / len(data)
print("The average is: ", avg)
if __name__ == "__main__":
main()
the problem is, this works fine when I manually enter items in a list, but when I added the line.strip function and tried to put it in a list, and then convert it using map, this is my code:
file = input("Enter the input file name: ")
with open(file) as f:
for line in f:
line = line.strip()
data = [line]
data = list(map(int, data))
from functools import reduce
def add(x, y): return x + y
total = reduce(add, data)
avg = total / len(data)
print("The average is: ", avg)
if __name__ == "__main__":
main()
I am getting this error:
Traceback (most recent call last):
File "average.py", line 15, in <module>
main()
File "average.py", line 7, in main
data = list(map(int, data))
ValueError: invalid literal for int() with base 10: '100 22 98'
I am terrible at coding, can you please help me understand 1) what the error is 2) is there something wrong with the list not converting the strings to integers?
Thank you!

You have problem with below line of code, this is not spliting the line and adding each item to list. it is adding whole line as an string in list.
data = [line]
e.g.
data = [line]
['11 12 123 123']
data = line.split()
['11', '12', '123', '123']
You need to change your code like below and it should work.
file = input("Enter the input file name: ")
with open(file) as f:
for line in f:
line = line.strip()
data = line.split()
data = list(map(int, data))
from functools import reduce
def add(x, y): return x + y
total = reduce(add, data)
avg = total / len(data)
print("The average is: ", avg)

Related

Why won't my program define the variable even after using a return statement?

I am currently doing a challenge on hackerrank.com (https://www.hackerrank.com/challenges/finding-the-percentage/problem) about finding a percentage given a student's grade.
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
over = len(scores)
def average_score():
average = 0
if query_name == _ in name:
for scores in student_marks:
for grade in scores:
average = average + grade
return average
average_score()
print(average / over)
I'm having a hard time making sense as to why the program won't recognize the variable (average) even after using a return statement.
Traceback (most recent call last):
File "Solution.py", line 22, in <module>
print(average / over)
NameError: name 'average' is not defined
Whenever I try to run the program, a NameError pops up.
You are not storing the result of the call to average_score. Change it to this:
average = average_score()

'map' object is not subscriptable

I am trying to execute the codes from this link
https://zulko.github.io/blog/2014/06/21/some-more-videogreping-with-python/
import re # module for regular expressions
def convert_time(timestring):
""" Converts a string into seconds """
nums = map(float, re.findall(r'\d+', timestring))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
with open("Identity_2003.srt") as f:
lines = f.readlines()
times_texts = []
current_times , current_text = None, ""
for line in lines:
times = re.findall("[0-9]*:[0-9]*:[0-9]*,[0-9]*", line)
if times != []:
current_times = map(convert_time, times)
elif line == '\n':
times_texts.append((current_times, current_text))
current_times, current_text = None, ""
elif current_times is not None:
current_text = current_text + line.replace("\n"," ")
print (times_texts)
from collections import Counter
whole_text = " ".join([text for (time, text) in times_texts])
all_words = re.findall("\w+", whole_text)
counter = Counter([w.lower() for w in all_words if len(w)>5])
print (counter.most_common(10))
cuts = [times for (times,text) in times_texts
if (re.findall("please",text) != [])]
from moviepy.editor import VideoFileClip, concatenate
video = VideoFileClip("Identity_2003.mp4")
def assemble_cuts(cuts, outputfile):
""" Concatenate cuts and generate a video file. """
final = concatenate([video.subclip(start, end)
for (start,end) in cuts])
final.to_videofile(outputfile)
assemble_cuts(cuts, "please.mp4")
But the assemble_cuts function is not working . I am using python3.x
it is giving me an error
Traceback (most recent call last):
File "<ipython-input-64-939ee3d73a4a>", line 47, in <module>
assemble_cuts(cuts, "please.mp4")
File "<ipython-input-64-939ee3d73a4a>", line 44, in assemble_cuts
for (start,end) in cuts])
File "<ipython-input-64-939ee3d73a4a>", line 43, in <listcomp>
final = concatenate([video.subclip(start, end)
File "<ipython-input-64-939ee3d73a4a>", line 6, in convert_time
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
TypeError: 'map' object is not subscriptable
Could you help me to solve this problem?
Fixed it.
def convert_time(timestring):
""" Converts a string into seconds """
nums = list(map(float, re.findall(r'\d+', timestring)))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000

Python IDLE TypeError: int object not subscriptible

I am making a code that makes a map (not visible), and you can move in it.
I have been working on this code for a week now.
It has a TypeError.
import map
def basicRealm():
player=[0,0]#this is you
Home=[0,0]
Shops=[2,7]
Park=[8,2]
locations = [Home, Shops, Park]
desternation=Park
RealmSize = grid(10)
choice = input("Move north, south, east, or west?[north/south/east/west]")
no = int(input("Number of spaces to move: "))
if choice=='north':
axis=y
elif choice=='south':
axis=y
elif choice=='east':
axis==x
elif choice=='west':
axis=x
else:
pass
nothing=''
if choice=='south' or choice=='east':
no = 0 - no
else:
pass
you_are_here = move(no, player, axis)
basicRealm()
And my map module to run it is :
def atDesternation(location):
global desternation
if desternation==location:
return True
else:
return False
def atLocation(Object,locations):
pos = position(Object)
for i in locations:
if pos==i:
return i
else:
return None
def position(Object):
pos = (Object[0], Object[1])
return pos
def grid(size):
size = ListRange(0, size)
return size
def move(spaces, thing, axis):
here= position(thing)
pos = here[axis] + spaces
return pos
The Output is as follows:
Move north, south, east, or west?[north/south/east/west]north
Number of spaces to move: 1
Traceback (most recent call last):
File "C:\Users\lewis\Desktop\Map1.py", line 35, in <module>
basicRealm()
File "C:\Users\lewis\Desktop\Map1.py", line 29, in basicRealm
print(position(you_are_here))
File "C:\Users\lewis\Desktop\map.py", line 13, in position
pos = (Object[0], Object[1])
TypeError: 'int' object is not subscriptable
>>>
How do I solve this error? Please help.
I am newish to Python and find it very hard to slove Errors.

How can i adjust this code to python 3 for palindrome numbers?

# Python program to count and
# print all palindrome numbers in a list.
def palindromeNumbers(list_a):
c = 0
# loop till list is not empty
for i in list_a:
# Find reverse of current number
t = i
rev = 0
while t > 0:
rev = rev * 10 + t % 10
t = t / 10
# compare rev with the current number
if rev == i:
print (i),
c = c + 1
print
print ("Total palindrome nos. are" + str(c))
print
def main():
list_a = [10, 121, 133, 155, 141, 252]
palindromeNumbers(list_a)
list_b = [ 111, 220, 784, 565, 498, 787, 363]
palindromeNumbers(list_b)
if __name__ == "__main__":
main() # main function call
This code, obtained from
https://www.geeksforgeeks.org/all-palindrome-numbers-in-a-list/, has been written in Python 2.
When I run this program in Python 3.6 it returns the value as 0 for both lists.
Can someone tell me how to change it to be compatible with Python 3?
One of the important changes between Python2 and Python3 is integer division, that in Python2 returns a truncated, integer result while in Python3 returns a floating point number. To have a real integer division you have to use a double slash, "//".
In summary, change the line t = t/10 to t = t//10.
Ok, so I have changed the code a bit using a different method to check if the number is the same reversed... I tried not to change too much of your code...
The function reverse() just returns the string given to it reversed...
If I'm not mistaken the function makes a list out of the str by split function then [::-1] gives the list reversed...
def reverse(str):
return str[::-1]
def palindromeNumbers(list_a):
c = 0
# loop till list is not empty
for i in list_a:
# Find reverse of current number
t = i
t = int(reverse((str(t))))
if t == i:
c += 1
print ("Total palindrome nos. are " + str(c))
def main():
list_a = [10, 121, 133, 155, 141, 252]
palindromeNumbers(list_a)
list_b = [ 111, 220, 784, 565, 498, 787, 363]
palindromeNumbers(list_b)
if __name__ == "__main__":
main() # main function call
Try it out! I hope you find this helpful...
I first converted the number to an iterable string str(i). Then I shortened the for loop by only comparing the first half of the number t[a] to the second half of the number t[~a], and then using all() to check that all of the comparisons were true. (using Python 3.6.8)
for i in list_a:
# convert interger to iterable string
t = str(i)
# compare first half of the number to second half of the number
if all([t[a]==t[~a] for a in range(len(t)//2)]):
print (i),
c = c + 1

Calculating the average by inputing values in a file, code produces wrong output

'''This simple program will calculate the average using files'''
num = 3
try: #set an exception in case of a file Error
while num >=0: '''read in values and place them in a file'''
value = int(input("Enter values: "))
my_file = open('my_data.txt', 'w+')
my_file.write(str(value))
numbers = my_file.readlines()
num -=1
my_file.close()
except IOError:
print('FILE FAILURE')
'''iterate to find the sum of the values in a file'''
total = 0
for ln in numbers:
total += int(ln)
'''Calculate the average'''
avg = total/len(numbers)
print("The average is %d"%(avg))#FIXME: does not calculate average
You are opening a file for write, then read from it, and assign it to a variable numbers. However this variable is not a list, although you treat it as a list when you do for ln in numbers.
Furthermore, you should end a line written to file with \n
Based on how I understand your code, you want to:
Get user input, and write it to file
From the file, read the numbers
From the numbers calculate the average
There is a statistics module, with the function mean, which will do the calculation part for you. The rest, you could (should) structure like the three bullet points above, something like this:
from statistics import mean
def inputnumbers(itterations, filename):
with open(filename, 'w') as openfile:
while itterations > 0:
try:
value=int(input("value->"))
except ValueError:
print('Numbers only please')
continue
openfile.write(str(value) + '\n')
itterations -= 1
def getaveragefromfile(filename):
numbers = []
with open(filename, 'r') as openfile:
for line in openfile.readlines():
numbers.append(int(line.replace('\n','')))
return mean(numbers)
def main():
filename = r'c:\testing\my_data.txt'
itterations = int(input('how many numbers:'))
inputnumbers(itterations, filename)
average = getaveragefromfile(filename)
print(average)
if __name__ == '__main__':
main()

Resources