Dividing an array in a for loop? - python

I have been given a task by my teacher and one of the questions wants me to divide everything in the array by 26.22(A full marathon). I have been working on this all day and am totally stuck could someone please show me how to make this work?
this is what I have so far
import string
forename = []
surname = []
distance = []
farthest_walk = []
marathon = []
#Opening the text file and sorting variables
data = open("members.txt","r")
for line in data:
value = line.split(',')
forename.append(value[0])
surname.append(value[1])
distance.append(value[2])
#Closing the text file
data.close()
Results = open("Results.txt","w+")
Results.write("The number of whole marathons walked be each member is:\n")
for count in range(len(distance)):
if float(distance[count])/ 26.22 = temp:
marathon.append
Results.write(forename[count]+":")
Results.write(surname[count]+":")
Results.write(marathon[count])
Results.close()
It is supposed to end up as Forename, Surname, WholeMarathosRun but I don't see how it could get there.

You almost got there.
For each name, you need to compute how many marathons he ran, which can be achieved with the following operation:
temp = float(distance[count])/ 26.22
This doesn't need to be in an if statement.
Then you need to write this value in the output file after the names:
Results.write(forename[count]+":")
Results.write(surname[count]+":")
Results.write(temp)
# line break such that each result stay in one line
Results.write("\n")
All those lines go inside the last for loop that you already have.

Related

Python: list index out of range even if I am looking at element with index 0

sorry if this question has already been asked but I can't find any answer that solves my problem.
I am using Python 3.8 with PyCharm on Mac (if that information can help).
I just started learning python and have a solid C and MatLab background.
My goal here is to read some information about train stations from a file in the format
and then ask the user for a station and give out the names of the stations that are connected by trains. Here is my code:
fin = open('trains', 'r')
string = fin.read()
lines = string.split('\n')
print(lines)
station = input("Insert station name\n")
from_station = [] #stations from which trains arrive at the user's station
to_station = [] #stations to which trains arrive from user's station
for i in range(0,len(lines)):
words = lines[i].split()
for i in range(0,4):
print(words[i]) #put to check if the words list actually stores the different words
if words[0] == station:
to_station.append(words[2])
if words[2] == station:
from_station.append(words[0])
print("Trains arriving from stations: ")
print(from_station)
print("Trains going to stations: ")
print(to_station)
fin.close()
I keep getting the Index out of bounds error for print(words[i]) in line 17 even if my complier (or interpreter) manages to print the right informartions without any problem.
I cannot manage to compile the code after the end of the for.
Thank you in advance for your help
EDIT: Even if I make that correction you suggested - I didn't notice in the inner loop that mistake - I still keep getting that error. I get that error even if I remove that inner loop altogether.
issue is in this line
words = lines[i].split()
you need to check the len(words) each time and need to confirm that len(words) is in bound of your indices range
exactly viewing your data can resolve the issue
Use another variable in the inner loop other than 'i'.
The problem comes from your inner loop and also the iterator on the list words. You may have a list of two words then can have a Index out of bounds error.
fin = open('trains', 'r')
string = fin.read()
lines = string.split('\n')
print(lines)
station = input("Insert station name\n")
from_station = [] #stations from which trains arrive at the user's station
to_station = [] #stations to which trains arrive from user's station
for i in range(0,len(lines)):
words = lines[i].split()
for j in range(0,len(words)):
print(words[j]) #put to check if the words list actually stores the different words
if words[0] == station:
to_station.append(words[2])
if words[2] == station:
from_station.append(words[0])
print("Trains arriving from stations: ")
print(from_station)
print("Trains going to stations: ")
print(to_station)
fin.close()

Rewriting Single Words in a .txt with Python

I need to create a Database, using Python and a .txt file.
Creating new items is no Problem,the inside of the Databse.txt looks like this:
Index Objektname Objektplace Username
i.e:
1 Pen Office Daniel
2 Saw Shed Nic
6 Shovel Shed Evelyn
4 Knife Room6 Evelyn
I get the index from a QR-Scanner (OpenCV) and the other informations are gained via Tkinter Entrys and if an objekt is already saved in the Database, you should be able to rewrite Objektplace and Username.
My Problems now are the following:
If I scan the Code with the index 6, how do i navigate to that entry, even if it's not in line 6, without causing a Problem with the Room6?
How do I, for example, only replace the "Shed" from Index 4 when that Objekt is moved to f.e. Room6?
Same goes for the Usernames.
Up until now i've tried different methods, but nothing worked so far.
The last try looked something like this
def DBChange():
#Removes unwanted bits from the scanned code
data2 = data.replace("'", "")
Index = data2.replace("b","")
#Gets the Data from the Entry-Widgets
User = Nutzer.get()
Einlagerungsort = Ort.get()
#Adds a whitespace at the end of the Entrys to seperate them
Userlen = len(User)
User2 = User.ljust(Userlen)
Einlagerungsortlen = len(Einlagerungsort)+1
Einlagerungsort2 = Einlagerungsort.ljust(Einlagerungsortlen)
#Navigate to the exact line of the scanned Index and replace the words
#for the place and the user ONLY in this line
file = open("Datenbank.txt","r+")
lines=file.readlines()
for word in lines[Index].split():
List.append(word)
checkWords = (List[2],List[3])
repWords = (Einlagerungsort2, User2)
for line in file:
for check, rep in zip(checkWords, repWords):
line = line.replace(check, rep)
file.write(line)
file.close()
Return()
Thanks in advance
I'd suggest using Pandas to read and write your textfile. That way you can just use the index to select the approriate line. And if there is no specific reason to use your text format, I would switch to csv for ease of use.
import pandas as pd
def DBChange():
#Removes unwanted bits from the scanned code
# I haven't changed this part, since I guess you need this for some input data
data2 = data.replace("'", "")
Indexnr = data2.replace("b","")
#Gets the Data from the Entry-Widgets
User = Nutzer.get()
Einlagerungsort = Ort.get()
# I removed the lines here. This isn't necessary when using csv and Pandas
# read in the csv file
df = pd.read_csv("Datenbank.csv")
# Select line with index and replace value
df.loc[Indexnr, 'Username'] = User
df.loc[Indexnr, 'Objektplace'] = Einlagerungsort
# Write back to csv
df.to_csv("Datenbank.csv")
Return()
Since I can't reproduce your specific problem, I haven't tested it. But something like this should work.
Edit
To read and write text-file, use ' ' as the seperator. (I assume all values do not contain spaces, and your text file now uses 1 space between values).
reading:
df = pd.read_csv('Datenbank.txt', sep=' ')
Writing:
df.to_csv('Datenbank.txt', sep=' ')
First of all, this is a terrible way to store data. My suggestion is not particularily well code, don't do this in production! (edit
newlines = []
for line in lines:
entry = line.split()
if entry[0] == Index:
#line now is the correct line
#Index 2 is the place, index 0 the ID, etc
entry[2] = Einlagerungsort2
newlines.append(" ".join(entry))
# Now write newlines back to the file

How to read off of a specific line in a text file using python

Looking to have my code read one text file and store the line number of a user input as num and then use the variable num to read the same line on another file.
currently, the code for the first step of reading the first text file is working and has been tested but the second part doesn't display anything after being executed. I have changed multiple things but am still stuck. Help would be much appreciated.
here is my code:
print("Check Stock")
ca = input("Check all barcodes?")
if ca == "y":
for x in range(0,5):
with open ("stockbarcodes.txt") as f:
linesa = f.readlines()
print(linesa[x])
with open ("stockname.txt") as f:
linesb = f.readlines()
print(linesb[x])
print(" ")
else:
bc = input("Scan barcode: ")
f1 = open ("stockname.txt")
for num, line in enumerate(f1, 1):
if bc in line:
linesba = f1.readlines()
print(linesba[num])
As user Ikriemer points, it seems that you want to retrieve the stock name based on the barcode. For that kind of task you rather create a normalized Data Base, which discribes Entities, Properties and relationships. As you can se here there are a lot of things to take into account.
This code was tested on Mac OS, but considering OP's comment (who seems to be using windows), it is ok if the dtype is not specified.
Considering that the above solution may not be as quick as you like, you also have two options.
First option
As I can not check the content of your example files, the strategy that you show in your code makes me believe that your assuming both files are ordered, in a way that first line of the barcode file corresponds to first item in the stock name file. Given that, you can query the index of an element (barcode) in an array like data structure, and retrieve the element of another array (name) stored in the same position. Code below:
import numpy as np
print("Check Stock")
ca = input("Check all barcodes? (y/n): ")
if ca == "y":
for x in range(0, 5):
with open("stockbarcodes.txt") as f:
linesa = f.readlines()
print(linesa[x], sep="")
with open("stockname.txt") as f:
linesb = f.readlines()
print(linesb[x], sep="")
print(" ")
else:
try:
codes = np.genfromtxt("stockbarcodes.txt").tolist()
names = np.genfromtxt("stockname.txt", dtype=np.str).tolist()
bc = input("Scan barcode: ")
index = codes.index(int(bc))
print(names[index])
except IndexError:
print("Bar code {} not found".format(bc))
Second option
This option could be considered a workaround method to a data base like file. You need to store your data in some way that you can search the values associated with an specific entry. Such kind of tasks could be done with a dictionary. Just replace the else clause with this:
else:
try:
codes = np.genfromtxt("stockbarcodes.txt").tolist()
names = np.genfromtxt("stockname.txt", dtype=np.str).tolist()
table = {k: v for k, v in zip(codes, names)}
bc = input("Scan barcode: ")
print(table[int(bc)])
except KeyError:
print("Bar code {} not found".format(bc))
Again, in the dictionary comprehension we are assuming both files are ordered. I strongly suggest you to validate this assumption, to warranty that the first bar code corresponds to the first stock, second to second, and so on. Only after that, you may like to store the dictionary as a file, so you can load it and query it as you please. Check this answer fot that purpose.

Python: Writing peoples scores to individual lines

I have a task where I need to record peoples scores in a text file. My Idea was to set it out like this:
Jon: 4, 1, 3
Simon: 1, 3, 6
This has the name they inputted along with their 3 last scores (Only 3 should be recorded).
Now for my question; Can anyone point me in the right direction to do this? Im not asking for you to write my code for me, Im simply asking for some tips.
Thanks.
Edit: Im guessing it would look something like this: I dont know how I'd add scores after their first though like above.
def File():
score = str(Name) + ": " + str(correct)
File = open('Test.txt', 'w+')
File.write(score)
File.close()
Name = input("Name: ")
correct = input("Number: ")
File()
You could use pandas to_csv() function and store your data in a dictionary. It will be much easier than creating your own format.
from pandas import DataFrame, read_csv
import pandas as pd
def tfile(names):
df = DataFrame(data = names, columns = names.keys())
with open('directory','w') as f:
f.write(df.to_string(index=False, header=True))
names = {}
for i in xrange(num_people):
name = input('Name: ')
if name not in names:
names[name] = []
for j in xrange(3):
score = input('Score: ')
names[name].append(score)
tfile(names)
Simon Jon
1 4
3 1
6 3
This should meet your text requirement now. It converts it to a string and then writes the string to the .txt file. If you need to read it back in you can use pandas read_table(). Here's a link if you want to read about it.
Since you are not asking for the exact code, here is an idea and some pointers
Collect the last three scores per person in a list variable called last_three
do something like:
",".join(last_three) #this gives you the format 4,1,3 etc
write to file an entry such as
name + ":" + ",".join(last_three)
You'll need to do this for each "line" you process
I'd recommend using with clause to open the file in write mode and process your data (as opposed to just an "open" clause) since with handles try/except/finally problems of opening/closing file handles...So...
with open(my_file_path, "w") as f:
for x in my_formatted_data:
#assuming x is a list of two elements name and last_three elems (example: [Harry, [1,4,5]])
name, last_three = x
f.write(name + ":" + ",".join(last_three))
f.write("\n")# a new line
In this way you don't really need to open/close file as with clause takes care of it for you

Having trouble with my python program

I'm having a bit of trouble. So, for my assignment, my teacher wants us to read in data and output the data into another file. Now, the data we are reading in are Students name(Line one), and their grades(Line 2). Now, he wants us to read them in, then write them into another file. Write them in two lines. Line one, being the students name, and line two, being their average. Then, write the averages into a list and run the whole list through mean, median, and standard deviation. Here's an example of some data from the file.
Aiello,Joseph
88 75 80
Alexander,Charles
90 93 100 98
Cambell,Heather
100 100
Denniston,Nelson
56 70 65
So, as you see, it's last name first, separated by a comma, then first. Then, on line two, their grades. He wants us to find the average of them and then write them under the students name. That's the part I'm having trouble on. I know how to find an average. Add the grades up, then divide by the number of grades they got. But how do I put that into python? Can anyone help? Also, I already have a mean, median, standard deviation program. How would I put the averages I get from the first part into a list, then putting the whole list through the mean, median, standard devation program.And back to my original question. Is there anything wrong with what I have so far? Anything I need to add/change? Here's my code.
def main():
input1 = open('StudentGrades.dat', 'r')
output = open('StudentsAvg', 'w')
for nextLine in input1:
output.write(nextLine)
list1 = nextLine.split()
count = int(list1[3])
for p in range(count):
nextLine = input1.readlin()
output.write(nextLine)
list2 = nextLine.split()
name = int(list2[1])
grades = list2[2]
pos = grades.index(grade)
avg =
It seems like there's a few problems here. The first is that what everything you're reading from the file is a string, not a number. Secondly, you should probably be doing all of this within the same for loop wherein you read the lines. (One more point - use the with statement to allow your file objects to be automatically destructed when you're done with them.) So, you could modify your code as follows:
def main():
with open('StudentGrades.dat', 'r') as input1, open('StudentsAvg.txt', 'w') as output:
counter = 0
student_name = ''
for nextLine in input1:
if counter % 2 == 0:
student_name = nextLine
else:
grades = [int(x) for x in nextLine.split()]
avg = sum(grades) / len(grades)
print(student_name, file=output)
print(str(avg), file=output)
counter += 1
Note that print(str, file) is the current, preferred method for writing to a file.
Some improvements made to the original code:
def averagMarksCalculator(): # Learn to name your functions "Meaningfully"
# Using with clause - Learn to love it as much as you can!
with open('StudentGrades.dat') as input1, open('StudentsAvg.txt', 'w') as output:
for nextLine in input1:
strToWrite = nextLine; # Write student's name
output.write(nextLine) # Print student name
list1 = (input1.readline()).split() # split them into individual strings
avg = 0 # initialise
list1 = [int(x) for x in list1]
avg = sum(list1)/len(list1)
output.write("Average marks........"+str(avg)+"\r\n") # avg marks of student
input1.close()
output.close()
Note that the "\r\n" is to make sure you have a line gap after a student's name and average marks printed on the result file. If you don't need the empty new line as a separator, please use "\r" only.

Categories

Resources