Related
I have a list which looks like this: [1 H 1.0079, 2 He 4.0026, 3 Li 6.941, 4 Be 9.01218, ...]
I want to ask the user of the program for the corresponding atomic number to the atom. So the program will take a random atomic symbol and ask the user what's the atoms atomic number.
Code so far:
class Atom:
def __init__(self, number, weight, atom):
self.number = nummer
self.atom = atom
self.weight = weight
def __str__(self):
return self.atom + " " + str(self.weight)
def __repr__(self):
return str(self.number) + " " + self.atom + " " + str(self.weight)
def atom_listan():
atom_file = open('atomer2.txt', 'r')
atom_lista = []
number = 1
for line in atom_fil:
data = line
weight = float(data.split()[1])
atom = data.split()[0]
new_atom1 = Atom(number, weight, atom)
atom_lista.append(new_atom1)
atom_lista.sort(key=lambda x: x.vikt)
atom_lista[17], atom_lista[18] = atom_lista[18], atom_lista[17]
atom_lista[26], atom_lista[27] = atom_lista[27], atom_lista[26]
atom_lista[51], atom_lista[52] = atom_lista[52], atom_lista[51]
atom_lista[89], atom_lista[90] = atom_lista[90], atom_lista[89]
atom_lista[91], atom_lista[92] = atom_lista[92], atom_lista[91]
atom_fil.close()
for i in range(len(atom_lista)):
atom_lista[i].number = i + 1
return atom_lista
Code so far where I create a list consisting of the elements information. I have tried using the random.choice module but I don't really know how to get only the atomic symbol from the list with random.choice and also have the corresponding atomic number to the random atom be the correct answer.
You can get the atomic symbol like this if you have the list of elements as you mentioned in the question.
import random
a=["1 H 1.0079", "2 He 4.0026", "3 Li 6.941", "4 Be 9.01218"]
random_choice = random.choice(a)
random_atom = random_choice.split(" ")[1]
print(random_atom)
Try this. Clearly you could put it into a loop. I just used a part of your List.
import random
elements = ['1 H 1.0079', '2 He 4.0026', '3 Li 6.941', '4 Be 9.01218']
choose = random.choice(elements)
splitted = choose.split(' ')
print('The element symbol is : ', splitted[1])
attempt = input('Enter the Atomic Number ')
if (attempt == splitted[0]):
print('Correct')
else:
print('Wrong')
To get to the point, here is my input.txt file:
Variable 1,Variable 2,Variable 3,Variable 4
Test anxiety,Worry,Emotionality,28
ERS,Reppraisal,Suppression,33
Calling,Money,Love, 69
Here is my code:
class Psych:
def __init__(self, des1, des2, des3, value):
self.__des1 = des1
self.__des2 = des2
self.__des3 = des3
self.__value = value
def getDes1(self):
return str(self.__des1)
def getDes2(self):
return str(self.__des2)
def getDes3(self):
return str(self.__des3)
def getValue(self):
return round(float(self.__value),2)
#Import data
filePath='input.txt'
file=open(filePath)
data=file.readlines()
file.close()
#Remove first row
data2 = data[1:]
#Strip /n
data3 = []
for i in data2:
data3.append(i.strip())
#Pop, Split, Create and Append Psych objects into listOfVariables
listOfVariables=[]
#Variable 1
var1 = data3.pop(0)
var1 = var1.split(",")
var1 = Psych(var1[0],var1[1],var1[2],float(var1[3]))
listOfVariables.append(var1)
#Variable 2
var2 = data3.pop(0)
var2 = var2.split(",")
var2 = Psych(var2[0],var2[1],var2[2],float(var2[3]))
listOfVariables.append(var2)
#Variable 3
var3 = data3.pop(0)
var3 = var3.split(",")
var3 = Psych(var3[0],var3[1],var3[2],float(var3[3]))
listOfVariables.append(var3)
#Printing function
def printVariables(var):
print(var.getDes1())
print(var.getDes2())
print(var.getDes3())
print(var.getValue())
#Navigation Menu
print("\nVariable 1")
print("--------------")
print("Variable Details:")
printVariables(var1)
print()
usrInput=input("Press 'N' to see the next variable\nPress 'P' to see the previous variable")
Essentially, using the Navigation Menu as the default, I am struggling to write a code that prints out
Variable 2
Variable Details:
output from printVariables(var2)
when usrInput=="N" and prints out
Variable 3
Variable Details:
output from printVariables(var3)
when usrInput=="P".
Similarly, when printVariables(var2) is already executed, usrInput=="N" should print out
Variable 3
Variable Details:
output from printVariables(var3)
and usrInput=="P" should print out
Variable 1
Variable Details:
output from printVariables(var1)
Further issue:
While attempting to solve this problem, I tried
test = listOfVariables[-2]
test1 = test[0]
print(test1.getDes1())
and encountered this error: TypeError: 'Psych' object is not subscriptable
What does this error mean? Sorry I am very new to programming (as can be seen from my codes) so please give a layperson explanation
Thank you in advance
Here is a simple solution that loads the CSV file, prints out the first row of the CSV, then prompts the user for N=Next, P=Previous, or X=Exit. It cycles through the CSV rows.
import csv
FILENAME_CSV = 'input.csv'
COLUMNS = ['Variable 1', 'Variable 2', 'Variable 3', 'Variable 4']
def print_variable(variables, index):
print('Variable:', index + 1)
for col in COLUMNS:
print('\t', variables[index][col])
def load_variables(filename):
with open(filename) as csv_data:
csv_reader = csv.DictReader(csv_data)
return list(csv_reader)
index = 0
choice = ''
variables = load_variables(FILENAME_CSV)
while choice.upper() != 'X':
print_variable(variables, index)
choice = input('Press N for Next, P for Previous, X to exit: ')
if choice.upper() == 'N':
index = (index + 1) % len(variables)
elif choice.upper() == 'P':
index = (index - 1) % len(variables)
Hi I am reading data from file in the class Patients and passing the content to appointment class method.
when the content is split such that content[0] has ['130', 'Ali', 'Male', '22', 'Cough'] so I am putting these values and setting the Patient class properties. This is done in for loop so all objects from file read are added to list of Patient class. But in doing so it is repetitively adding only one row of data.
Below is the code:
//Text file Data:
ID PatientName Gender Age Disease
130 Ali Male 22 Cough
132 Annile Female 23 Corona
133 sam Male 24 Fever
I want list of patients to store 130-132-133 but instead it stores only 133 at all three positions of list. Dont know if object creation or passing for Patient class is an issue
//Patient.py
class Patients:
def __init__(self):
self.patient_id = ""
self.patient_name = ""
self.patient_age = ""
self.patient_gender = ""
self.patient_disease = ""
def read_patient_file(self):
with open('PatientRecord.txt') as f:
content = f.readlines()
content = [x.strip() for x in content]
del content[0] // first row is of column names so removing it
return content
//Appointment.py
def patientProgram(list_patient):
Flag = True
pat1 = Patients()
while Flag:
print("\nPress 1. To Create Patient Record ")
print("Press 2. To View Patient Records ")
print("Press 6. To Read Patient Record From File ")
x = int(input("Please input from Menu Displayed Above which Operation to perform:"))
if x == 1:
list_patient.append(AddPatient())
elif x == 2:
print("**********")
print("Total Records in Memory for Patients:" + str(len(list_patient)))
for pat in list_patient:
print(f'patient_id = {pat.patient_id} for object {pat}')
elif x == 6: // this condition gives issue
content = []
content = pat1.read_patient_file() // content gets 3 rows of data from text file
j = 0
for i in content:
pat_id, name, gender, age, disease = str(content[j]).split()
print("FirstID: " + str(j)+ str(pat_id))
pat1.set_patient_record(pat_id, name, gender, age, disease)
list_patient.append(pat1)
j=j+1
print("Total Records for Patients in memory : " + str(len(list_patient)))
from Patients import Patients
if __name__ == "__main__":
list_patient = []
Flag = True
while Flag:
print("\nPress 1. For Patient Options ")
print("Press 2. For Doctor Options ")
print("Press 3. To Exit Program ")
x = int(input("Please Select From Menu:"))
if x == 1:
patientProgram(list_patient)
elif x==3:
break
You're only creating one Patients object. For each record in the file, you modify the pat1 object and append it to the list_patient list. So all the list elements are the same object.
You need to create a new object for each record in the file, not one object at the beginning.
Also, the read_patient_file() function should be a class method, since it doesn't use self for anything.
class Patients:
def __init__(self):
self.patient_id = ""
self.patient_name = ""
self.patient_age = ""
self.patient_gender = ""
self.patient_disease = ""
#classmethod
def read_patient_file(cls):
with open('PatientRecord.txt') as f:
content = f.readlines()
content = [x.strip() for x in content]
del content[0] // first row is of column names so removing it
return content
def patientProgram(list_patient):
Flag = True
while Flag:
print("\nPress 1. To Create Patient Record ")
print("Press 2. To View Patient Records ")
print("Press 6. To Read Patient Record From File ")
x = int(input("Please input from Menu Displayed Above which Operation to perform:"))
if x == 1:
list_patient.append(AddPatient())
elif x == 2:
print("**********")
print("Total Records in Memory for Patients:" + str(len(list_patient)))
for pat in list_patient:
print(f'patient_id = {pat.patient_id} for object {pat}')
elif x == 6: // this condition gives issue
content = []
content = Patients.read_patient_file() // content gets 3 rows of data from text file
j = 0
for i in content:
pat1 = Patients()
pat_id, name, gender, age, disease = str(content[j]).split()
print("FirstID: " + str(j)+ str(pat_id))
pat1.set_patient_record(pat_id, name, gender, age, disease)
list_patient.append(pat1)
j=j+1
print("Total Records for Patients in memory : " + str(len(list_patient)))
I am reading data from file, like listed below, it is a .dat file:
1
Carmella Henderson
24.52
13.5
21.76
2
Christal Piper
14.98
11.01
21.75
3
Erma Park
12.11
13.51
18.18
4
Dorita Griffin
20.05
10.39
21.35
The file itself contains 50 records. From this data I need the person number, name and the first number, like so:
1 #person number
Marlon Holmes #Name
18.86 # First number
13.02 # Second Number
13.36 # Third Number
I already have code to read the data however I unable to get the top 10 results based on the #First number
The #First number in the Top 10 currently is in centimeters but needs to be converted to inches, I am unsure on how to combine the top 10 and conversion into one alongside the reading of the data
Code that reads the data:
with open('veggies_2016.txt', 'r') as f:
count = 0
excess_count = 0
for line in f:
if count < 3:
print(line)
count += 1
elif count == 3 and excess_count < 1:
excess_count += 1
else:
count = 0
excess_count = 0
As mentioned the code reads the file, like so #Person number, #name and #first number, but #first number needs to be converted to inches and then all of the data needs to be sorted to find the top 10
This process will also have to be repeated for #second number and #third number however they are separate in terms of their code from #first number
I have tried to read the data then append to a list and sort it and convert it from that but with no success, any help would be appreciated
Whole code:
from collections import OrderedDict
from operator import itemgetter
import pprint
def menu():
exit = False
while not exit:
print("To enter new competitior data, type new")
print("To view the competition score boards, type Scoreboard")
print("To view the Best Overall Growers Scoreboard, type Podium")
print("To review this years and previous data, type Data review")
print("Type quit to exit the program")
choice = raw_input("Which option would you like?")
if choice == 'new':
new_competitor()
elif choice == 'Scoreboard':
scoreboard_menu()
elif choice == 'Podium':
podium_place()
elif choice == 'Data review':
data_review()
elif choice == 'quit':
print("Goodbye")
raise SystemExit
"""Entering new competitor data: record competitor's name and vegtables lengths"""
def competitor_data():
global competitor_num
l = []
print("How many competitors would you like to enter?")
competitors = raw_input("Number of competitors:")
num_competitors = int(competitors)
for i in range(num_competitors):
name = raw_input("Enter competitor name:")
Cucumber = raw_input("Enter length of Cucumber:")
Carrot = raw_input("Enter length of Carrot:")
Runner_Beans = raw_input("Enter length of Runner Beans:")
l.append(competitor_num)
l.append(name)
l.append(Cucumber)
l.append(Carrot)
l.append(Runner_Beans)
competitor_num += 1
return (l)
def new_competitor():
with open('veggies_2016.txt', 'a') as f:
for item in competitor_data():
f.write("%s\n" %(item))
def scoreboard_menu():
exit = False
print("Which vegetable would you like the scoreboard for?")
vegetable = raw_input("Please type either Cucumber, Carrot or Runner Beans:")
if vegetable == "Cucumber":
Cucumber_Scoreboard()
elif vegetable == "Carrot":
Carrot_Scoreboard()
elif vegetable == "Runner Beans":
Runner_Beans_Scoreboard()
def Cucumber_Scoreboard():
exit = True
print("Which year would you like the Scoreboard from?")
scoreboard = raw_input("Please type a year:")
if scoreboard == "2015":
cucumber_veg_2015()
elif scoreboard == "2014":
cucumber_veg_2014()
elif scoreboard == "2016":
cucumber_veg_2016()
def cucumber_veg_2016(cm):
return float(cm) / 2.54
names = OrderedDict([('Competitor Number', int),
('Competitor Name', str),
('Cucumber', cucumber_veg_2016),
('Carrot', float),
('Runner Bean', float)])
data = []
with open('veggies_2016.txt') as fobj:
while True:
item = {}
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
pprint.pprint(sorted(data, key=itemgetter('Cucumber'))[:10])
Solution
Reading the data into a list of dictionaries would work:
from collections import OrderedDict
from operator import itemgetter
import pprint
def to_inch(cm):
return float(cm) / 2.54
names = OrderedDict([('person_number', int),
('name', str),
('first', to_inch),
('second', float),
('third', float)])
data = []
with open('veggies_2016.txt') as fobj:
while True:
item = {}
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
pprint.pprint(sorted(data, key=itemgetter('first'))[:10])
Output:
[{'first': 4.76771653543307,
'name': 'Erma Park',
'person_number': 3,
'second': 13.51,
'third': 18.18},
{'first': 5.897637795275591,
'name': 'Christal Piper',
'person_number': 2,
'second': 11.01,
'third': 21.75},
{'first': 7.893700787401575,
'name': 'Dorita Griffin',
'person_number': 4,
'second': 10.39,
'third': 21.35},
{'first': 9.653543307086613,
'name': 'Carmella Henderson',
'person_number': 1,
'second': 13.5,
'third': 21.76}]
In Steps
This helper function converts centimeters into inches:
def to_inch(cm):
return float(cm) / 2.54
We use an ordered dictionary to hold the names for the different items we want to read in order. The value is a function that we use to convert the read value for each item:
names = OrderedDict([('person_number', int),
('name', str),
('first', to_inch),
('second', float),
('third', float)])
We start with an empty list:
data = []
And open our file:
with open('veggies_2016.txt') as fobj:
We do something without a defined end and create a new dictionary item each time:
while True:
item = {}
We try to read from the file until it is finished, i.e. until we get a
StopIteration exception:
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
We go through the keys and values of our order dictionary names and call each
value, i.e. the function func() on the next line we retrieve with next().
This converts the entry into the desired datatype and does the cm-inch conversion for first. After reading all items for one person, we append the dictionary to the list data.
Finally, we sort by the key first and print out the 10 to entries
(my example file has less than 10 entries):
pprint.pprint(sorted(data, key=itemgetter('first'))[:10])
Integration with your code:
You need to put the code into the function podium_place():
def cucumber_veg_2016(cm):
return float(cm) / 2.54
def podium_place():
names = OrderedDict([('Competitor Number', int),
('Competitor Name', str),
('Cucumber', cucumber_veg_2016),
('Carrot', float),
('Runner Bean', float)])
data = []
with open('veggies_2016.txt') as fobj:
while True:
item = OrderedDict()
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
sorted_data = sorted(data, key=itemgetter('Cucumber'), reverse=True)
for entry in sorted_data[:10]:
for key, value in entry.items():
print key, value
print
menu()
At the end you need to call menu(). Also, if top mean largest first, you need sort reverse (see above).
I would read them as a record at a time. You can put that functionality in a function that you call several times with the same file. It can return a None when you reach the end of the file. It will return a tuple with all values for a given record (including conversions). You can then use sorted to sort the list of records using any one of the values from each record.
def read_record(fid):
id = fid.readline()
# At the end of the file
if id is None:
return None
name = fid.readline()
# Perform the conversion
number1_inches = float(fid.readline()) / 2.54
number2 = float(fid.readline())
number3 = float(fid.readline())
return (id, name, number1_inches, number2, number3)
with open('filename.txt', 'r') as fid:
records = list()
while True
new_record = read_record(fid)
# Stop if we hit the end of the file
if new_record is None:
break
records.append(new_record)
# Now sort the records based on the value of number1
records = sorted(records, key=lambda x: x[2])
while True:
try:
file = input("Enter a filename: ")
fi = open(file, "r")
infile = fi.read()
grid = [list (i) for i in infile.split()] #Puts the sudoku puzzle into a list in order to check that the total number is valid
check = len(grid)
print("The total number in this puzzle is:",check) #Counts the amount of numbers in the sudoku puzzle
break
except FileNotFoundError:
print ("The inputted file does not exist")
def check(infile):
count = 0
for j in range (0,9):
for n in range(0,9):
if infile[j].count(infile[j][n]) <= 1:
count = count + 0
else:
count = count + 1
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
leg = 0
for i in range(0,9):
for j in range(0,9):
if cols[i].count(cols[i][j]) <= 1:
leg = leg + 0
else:
leg = leg + 1
angel = []
for t in range(3):
ang = infile[t]
for u in range(3):
angel.append(ang[u])
foot = 0
for be in range(9):
if angel.count(angel[be]) <= 1:
foot = foot + 0
else:
foot = foot + 1
if count + leg + foot == 0:
print("Valid")
else:
print ("Invalid")
def inputs():
x = raw_input()
ls = []
while x != '':
x1 =x.split(' ')
ls.append(x1)
if len(infile) >=9:
print (check(infile))
infile = []
x = raw_input()
inputs()
actual error:
Traceback (most recent call last):
File "E:/Computer Programming/Assignment/check 2.py", line 22, in <module>
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
File "E:/Computer Programming/Assignment/check 2.py", line 22, in <listcomp>
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
File "E:/Computer Programming/Assignment/check 2.py", line 22, in <listcomp>
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
IndexError: string index out of range
Why does it give an output to say that my string index is out of range, is there another way to create a sudoku 9x9 checker to check if there are any reoccurring numbers. I need to make sure that there are 9 numbers in each column and that they are between the numbers 1 and 9
first, a few comments:
never do:
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
but do:
cols = [[row[i] for row in infile] for i in range(0,9)]
never call a variable the same name as a function you've defined in your code check and check()
don't write code at the module level, but embed everything in functions, and call the entry point function at the end of the file after the if __name__ == "__main__" condition (so in case you want to import your module in another module, you don't execute module level code).
don't open files without closing them, instead use the context manager: with open('myfile', 'r') as f: ...
your code features an useless use of while... or at least a wrong use (do you really mean to loop forever on an exception?) use command line arguments instead, that will make the shell help your user choose a file that does actually exists.
now I've made all that clear, here's about your actual question:
infile is a file object (if I can read correctly your mis-indented python code), thus every line - called row here - of infile is just a string.
So if you have an empty line or a line that is less than 9 columns, you're likely to get row[i] out of boundaries.
here's a take at refactoring your code, though I've left a number of wrong design over:
def check(infile):
count = 0
for j in range (0,9):
for n in range(0,9):
if infile[j].count(infile[j][n]) <= 1:
count = count + 0
else:
count = count + 1
def inputs():
x = raw_input()
ls = []
while x != '':
x1 =x.split(' ')
ls.append(x1)
if len(infile) >=9:
print (check(infile))
infile = []
x = raw_input()
def check_grid():
cols = [[row[i] for row in infile] for i in range(0,9)]
leg = 0
for i in range(0,9):
for j in range(0,9):
if cols[i].count(cols[i][j]) <= 1:
leg = leg + 0
else:
leg = leg + 1
angel = []
for t in range(3):
ang = infile[t]
for u in range(3):
angel.append(ang[u])
foot = 0
for be in range(9):
if angel.count(angel[be]) <= 1:
foot = foot + 0
else:
foot = foot + 1
if count + leg + foot == 0:
print("Valid")
else:
print ("Invalid")
inputs()
def sudoku_checker():
try:
file = input("Enter a filename: ")
fi = open(file, "r")
infile = fi.read()
grid = [list (i) for i in infile.split()] #Puts the sudoku puzzle into a list in order to check that the total number is valid
# Counts the amount of numbers in the sudoku puzzle
print("The total number in this puzzle is:",len(grid))
check_grid()
except FileNotFoundError:
print ("The inputted file does not exist")
if __name__ == "__main__":
sudoku_checker()