So I am trying to make a program that take in input for a flight, and stores it in arrays based on each type of input. Here are the arrays that I use to do this:
airline = []
flightNumbers = []
destination = []
gate = []
status = []
Here is the issue that I am having. After the user goes through and adds 1 flight, I want the program to print a flight status board in the console. For example if I enter:
"Delta", "Dl1480", "Atlanta", "E11", "Ontime"
"American", "AA367", "New York City", "H10", "Delayed"
"United", "UA3411", "Louisville, KY", "F25", "Cancelled"
this is what I want to see output by the program:
airline: | flight number: | destination: | gate: | status:
--------------------------------------------------------------------
Delta | DL1480 | Atlanta | E11 | Ontime
American | AA367 | New York City | H10 | Delayed
United | UA3417 | Louisville,KY | F25 | Cancelled
Here is what I tried to use to get this to print:
def showAll(self):
print("Airline | Flight Number | Destination | Gate | Status")
x = 0
while x < len(a.airline):
print(a.airline + [" | "] + a.flightNumbers + [" | "] + a.destination + [" | "] + a.gate + [" | "]+ a.status + ["\n"])
x += 1
but I get this as output if I enter 2 random entries:
Airline | Flight Number | Destination | Gate | Status
['delta', 'delta', ' | ', '001', '002', ' | ', 'Los angeles, ca', 'atlanta', ' | ', 'a1', 'a3', ' | ', 'ontime', 'ontime', '\n']
['delta', 'delta', ' | ', '001', '002', ' | ', 'Los angeles, ca', 'atlanta', ' | ', 'a1', 'a3', ' | ', 'ontime', 'ontime', '\n']
Can some suggest a way I can fix this, or a better way of going about this entirely? Here is the code for the entire program:
class FSB:
# arrays to store flight information
airline = []
flightNumbers = []
destination = []
gate = []
status = []
input = ""
def addFlight(self):
while input != "bye":
# get inputs
air = input("Enter an airline name >> ")
fn = input("Enter a flight number >> ")
dest = input("Enter a destination >> ")
g = input("Enter a gate number >> ")
stat = input("Enter a flight status >> ")
self.air = air
self.fn = fn
self.dest = dest
self.g = g
self.stat = stat
# add inputs to appropiate arrays
a.airline.append(self.air)
a.flightNumbers.append(self.fn)
a.destination.append(self.dest)
a.gate.append(self.g)
a.status.append(self.stat)
print("Data stored sucessfully.\n")
a.showAll()
def showAll(self):
print("Airline | Flight Number | Destination | Gate | Status")
x = 0
while x < len(a.airline):
print(a.airline + [" | "] + a.flightNumbers + [" | "] + a.destination + [" | "] + a.gate + [" | "]+ a.status + ["\n"])
x += 1
go = input("To add a new entry, enter 1.\nTo reprint list, enter 2.\nTo exit, enter 3.\n")
if go == "1":
a.addFlight()
elif go == "2":
for x in range(1,26):
print(" ")
a.showAll()
elif go == "3":
exit()
if __name__ == "__main__":
a = FSB()
a.addFlight()
You're trying to concatenate a string "|" to your list. Please try doing ["|"]instead.
I ended up iterating through each array manually, and this is what I got:
def showAll(self):
print("Airline\t\t\t" +"| Flight Number\t\t" +"| Destination\t\t" +"| Gate \t\t" +"| Status")
for x in range(len(a.airline)):
print("-------------------------------------------------------------------------------------------------------------------")
print(str(a.airline[x] + "\t\t") + str(a.flightNumbers[x] + "\t\t") + str(a.destination[x] + "\t\t\t\t") + str(a.gate[x] + "\t\t") + str(a.status[x]))
Thank you to everyone who suggested an answer, I appreciate it!
Related
Note: I want to achieve this without using any modules.
My goal is to put all text from a list, and put a table around it. I want to find out how many spaces it needs depending on the length of the word or something like that. I want to know how big the width and height has to be etc. To find out what the width should be, I could find out what the longest word in the list is and and do "─" * len(longestWord). To find out what the height should be, I could find out how many items are in the list and do this
amountInLst = len(lst)
for i in range(0, amountInList):
print(f"│{lst[i]}│")
But the only thing I don't know how to do is calculate the spaces so theres always 2 spaces left from the left side and right side. If anyone has any ideas or code then please help me.
For example:
Input:
lst = ["England", "France", "Sweden", "Norway", "Russia"]
output:
┌────────────┐
│ England │
│ France │
│ Sweden │
│ Norway │
│ Russia │
└────────────┘
To print "border" around words in your list you can do:
lst = ["England", "France", "Sweden", "Norway", "Russia"]
max_len = max(len(w) for w in lst)
f = "{:<" + str(max_len) + "}"
print("┌" + ("─" * (max_len + 2)) + "┐")
for w in lst:
print("| " + f.format(w) + " |")
print("└" + ("─" * (max_len + 2)) + "┘")
Prints:
┌─────────┐
| England |
| France |
| Sweden |
| Norway |
| Russia |
└─────────┘
Use the tabulate module.
from tabulate import tabulate
lst = [
["Milan", 14, "Male"],
["Alex", 482, "Male"],
["John", 12, "Male"],
["Jake", 36, "Male"],
["James", 12, "Male"]
]
print(tabulate(lst, headers=["Name", "Age", "Gender"]))
Solution
You can use the following custom code to display tables without using any other package. However, why reinvent the wheel? If you can, you should either use one of the following:
tabulate
pandas.Dataframe.to_markdown
pandas.Dataframe.to_string
To use the code given below, run this:
_ = maketable(data=lst, headers=headers, headersep='-', showtable=True)
## Output:
| Name | Age | Gender |
|-------|-----|--------|
| Milan | 14 | Male |
| Alex | 482 | Male |
| John | 12 | Male |
| Jake | 36 | Male |
| James | 12 | Male |
Extended Example of Code Usage
lst = [
["Milan", 14, "Male"],
["Alex", 482, "Male"],
["John", 12, "Male"],
["Jake", 36, "Male"],
["James", 12, "Male"]
]
headers = ['Name', 'Age', 'Gender']
tabeltext = maketable(
data = lst, # the data to create the table
headers = headers, # list of headers
bufferlen = 1, # length of buffers spaces to use around each table-cell-value
headersep = '-', # seperator-line-character to use between hear row and the rest of the table
data_has_header = False, # if `data` parameter has headers or not
showtable = True # whether to print the table or not
)
Code
from typing import List
def get_column_widths(
data: List[List],
headers: List[str] = None,
num_cols: int = None) -> List[int]:
"""returns column widths from the table data.
Example:
lst = [
["Milan", 14, "Male"],
["Alex", 482, "Male"],
["John", 12, "Male"],
["Jake", 36, "Male"],
["James", 12, "Male"]
]
headers = ['Name', 'Age', 'Gender']
get_column_widths(data=lst, headers=headers, num_cols=None)
"""
if (num_cols is None) and (headers is None):
num_cols = len(data[0])
if headers:
num_cols = len(headers)
_data = [headers] + data
else:
_data = data.copy()
col_widths = [0 for _ in range(num_cols)]
for ridx, line in enumerate(_data):
for cidx, e in enumerate(line):
col_width = len(str(e))
if col_width > col_widths[cidx]:
col_widths[cidx] = col_width
return col_widths
def pad(text: str, length: int) -> str:
return text + ' '*length
def wraptext(text: str, length: int) -> str:
return text[:length] + '\n' + text[length:]
def pad_or_wrap(text: str, length: int = 10) -> str:
n = len(text)
if n > length:
text = wraptext(text=text, length=length)
elif n < length:
text = pad(text=text, length=length-n)
return text
def maketable(
data: List[List],
headers: List[str] = None,
bufferlen: int = 1,
headersep: str = '-',
data_has_header: bool = False,
showtable: bool=True) -> str:
"""Returns the table as a string.
Example:
lst = [
["Milan", 14, "Male"],
["Alex", 482, "Male"],
["John", 12, "Male"],
["Jake", 36, "Male"],
["James", 12, "Male"]
]
headers = ['Name', 'Age', 'Gender']
tabeltext = maketable(
data = lst, # the data to create the table
headers = headers, # list of headers
bufferlen = 1, # length of buffers spaces to use around each table-cell-value
headersep = '-', # seperator-line-character to use between hear row and the rest of the table
data_has_header = False, # if `data` parameter has headers or not
showtable = True # whether to print the table or not
)
"""
tablerows = []
bufferlen = 1
buffertext = '' if bufferlen == 0 else ' ' * bufferlen
if headers:
num_cols = len(headers)
if not data_has_header:
_data = [headers] + data
else:
if data_has_header:
headers = data[0]
num_cols = len(headers)
_data = data.copy()
col_widths = get_column_widths(data = _data)
for ridx, line in enumerate(_data):
tablerows.append(
'|' + '|'.join(
buffertext + \
pad_or_wrap(text = str(e),
length = col_widths[cidx]) + \
buffertext \
for cidx, e in enumerate(line)
) + '|'
)
if headers or data_has_header:
if ridx == 0:
tablerows.append(
'|' + '|'.join(
[headersep * (col_widths[cidx] + 2 * bufferlen) \
for cidx in range(num_cols)]
) + '|'
)
tabletext = '\n'.join(tablerows)
if showtable:
print(tabletext)
return tabletext
below is c.txt
CO11 CSE C1 8
CO12 ETC C1 8
CO13 Electrical C2 12
CO14 Mech E 5
my program needs to print a course summary on screen and save that summary into a file
named cr.txt. Given the above c.txt, your program output should look like
below. The content of course_report.txt should also be the same, except the last line. Course
names in the second column use * to indicate a compulsory course and – to indicate an elective
course. The fourth column is the number of students enrolled in that course. The fifth column is the average score of the course.
CID Name Points. Enrollment. Average.
----------------------------------
CO11 * CSE 8 2 81
CO12 * ETC 8 10 71
CO13 * Electrical 12 8 61
CO14 - Mech 5 4 51
----------------------------------
poor-performing subject is CO14 with an average 51.
cr.txt generated!
below is what I've tried:
def read(self):
ctype = []
fi = open("c.txt", "r")
l = fi.readline()
while l != "":
fields = l.strip().split(" ")
self.c.append(fields)
l = fi.readline().strip()
f.close()
# print(f"{'CID'}{'Name':>20}{'Points.':>16}{'Enrollment.':>18}{'Average.':>10}")
# print("-" * 67, end="")
print()
for i in range(0, len(self.c)):
for j in range(len(self.c[i])):
obj = self.c[i][j]
print(obj.ljust(18), end="")
print()
print("-" * 67, end="")
print()
you can try use 'file.read' or 'file.readlines' after use 'open' function, if you choose 'file.readlines' you'll have to use 'for row in file.readlines()' look my example with 'file.read':
headers = ['CID', 'Name', 'Points.', 'Enrollment.', 'Average.']
compulsory_course = ['CO11', 'CO12', 'CO13']
elective_course = ['CO14']
count = 0
with open('c.txt', 'r') as file_c:
file_c.seek(0, 0)
file_string = file_c.read().replace('\n', ' ')
fields = file_string.split(' ')
with open('cr.txt', 'w') as file_cr:
for field in headers:
file_cr.write(f'{field} ')
file_cr.write('\n')
for v in fields:
if count == 4:
file_cr.write('\n')
count = 0
count += 1
if v in compulsory_course:
file_cr.write(f'{v} * ')
continue
elif v in elective_course:
file_cr.write(f'{v} - ')
continue
elif count == 3:
file_cr.write(f' ')
continue
file_cr.write(f'{v} ')
I am trying to create relationships on a graph I have on neo4j. When i run the python code, it runs through the excel file and for every row it created a relationship based on the two id columns. However not all of them are created.
For example when I run one excel file that has 33k rows, only 7.5k edges are created in the database.
I have checked that the process is running correctly, that the correct values are passed each time on the correct function/var so I really can't think of what is the issue here.
Below there are my code as well as a screen from the excel file so that you can see its structure.
Code:
my_set = set()
graph = Graph(url,password=password)
tx = graph.begin()
rels = list()
filename = input('Give file name --- ')
df = pd.read_csv(filename, header=None)
df.columns = ['Timestamp', 'id1', 'id2']
if filename.startswith('attack'):
rel_type = 'ATTACKS'
elif filename.startswith('trade'):
rel_type = 'TRADES'
else:
rel_type = 'MESSAGES'
row_cnt = 0
for index,row in df.iterrows():
row_cnt = row_cnt + 1
if row_cnt%1000 == 0 : print('Computed '+ str(row_cnt))
t1 = datetime.now()
ts = int(row['Timestamp'])
formatted_ts = datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
splitted_ts = formatted_ts.split()
date = splitted_ts[0]
time = splitted_ts[1]
node1 = graph.evaluate('MATCH (n:User) WHERE n.id={id} RETURN n', id=int(row["id1"]))
node2 = graph.evaluate('MATCH (n:User) WHERE n.id={id} RETURN n', id=int(row['id2']))
rels.append(Relationship(node1, rel_type, node2, date=date, time=time))
print('FileFInished************')
print('Computed ' + str(row_cnt))
edge_cnt = 0
for v in rels:
edge_cnt = edge_cnt + 1
if edge_cnt%1000==0: print('edge count: ', edge_cnt)
tx.create(v)
tx.commit()
print('edges: ' + str(edge_cnt))
Excel file(3 columns, could not post picture sorry):
____________________________
|Timestamp| userId1 | userId2|
------------------------------
|123342312| 3123 | 12312 |
|33121123 | 332 | 21231 |
thanks for reading this post. I want to make an advanced TicTacToe game with AI and other stuff. I need to pass the spots(s1-s9) variable between different functions. I have been researching for quite a bit now, and I would like to meet an answer. Here is part of the code I need to execute:
def set_spots(s1, s2, s3, s4, s5, s6, s7, s8, s9):
return s1,s2,s3,s4,s5,s6,s7,s8,s9
def print_spots():
print('\n')
print(str(s1) + ' | ' + str(s2) + ' | ' + str(s3))
print('--+---+--')
print(str(s4) + ' | ' + str(s5) + ' | ' + str(s6))
print('--+---+--')
print(str(s7) + ' | ' + str(s8) + ' | ' + str(s9))
def game_loop():
set_spots(1,2,3,4,5,6,7,8,9)
print_spots()
game_loop()
I want to be able to set the spots in any function like if I had a turnX function. Like if I had:
def turnx(): #This isnt in this code though
#if stuff == other stuff (just example):
set_spots('X','O',3,4,5,6,7,8,9)
But the output is:
NameError: name 's1' is not defined
So basically, I need the program to ask the user where their x or o would be placed on the board (which you don't have to worry about) then have that value stored to be printed out. Like if I change 1 to X in the game, it needs to be stored so it can be printed out.
i believe you should try using the variables from set spots, on print spots:
def print_spots(s1, s2, s3, s4, s5, s6, s7, s8, s9):
return s1,s2,s3,s4,s5,s6,s7,s8,s9):
print('\n')
print(str(s1) + ' | ' + str(s2) + ' | ' + str(s3))
print('--+---+--')
print(str(s4) + ' | ' + str(s5) + ' | ' + str(s6))
print('--+---+--')
print(str(s7) + ' | ' + str(s8) + ' | ' + str(s9))
def game_loop():
print_spots(1,2,3,4,5,6,7,8,9)
print_spots()
game_loop()
if that doesen't work then i'm not sure
You can do this without the need of the unnecessary set_spots() function.
All you need is an array:
def turnx(s):
if 1 == 1: # (a condition):
s = ['X','O',3,4,5,6,7,8,9]
return s
def print_spots(s):
print('\n')
print(str(s[0]) + ' | ' + str(s[1]) + ' | ' + str(s[2]))
print('--+---+--')
print(str(s[3]) + ' | ' + str(s[4]) + ' | ' + str(s[5]))
print('--+---+--')
print(str(s[6]) + ' | ' + str(s[7]) + ' | ' + str(s[8]))
def game_loop():
spots = [1,2,3,4,5,6,7,8,9] # Use an array
print_spots(spots)
spots = turnx(spots)
print_spots(spots)
game_loop()
This outputs:
1 | 2 | 3
--+---+--
4 | 5 | 6
--+---+--
7 | 8 | 9
X | O | 3
--+---+--
4 | 5 | 6
--+---+--
7 | 8 | 9
do yourself a favor and represent the spots as a list. Then store that list in a variable when you call set spots and pass it on to print:
def set_spots(s1, s2, s3, s4, s5, s6, s7, s8, s9):
return [s1,s2,s3,s4,s5,s6,s7,s8,s9]
def print_spots( spots ):
s1,s2,s3,s4,s5,s6,s7,s8,s9 = spots
print('\n')
print(str(s1) + ' | ' + str(s2) + ' | ' + str(s3))
print('--+---+--')
print(str(s4) + ' | ' + str(s5) + ' | ' + str(s6))
print('--+---+--')
print(str(s7) + ' | ' + str(s8) + ' | ' + str(s9))
def game_loop():
spots = set_spots(1,2,3,4,5,6,7,8,9)
print_spots(spots )
game_loop()
I have a question of while in python.
How to collect the result values using while?
ColumnCount_int = 3
while ColumnCount_int > 0 :
ColumnCount_text = str('<colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCount_int) + '">')
Blank_text = ""
Blank_text = Blank_text + ColumnCount_text
ColumnCount_int = ColumnCount_int - 1
print(Blank_text)
result shows as below
<colspec colnum="3" colname="3">
<colspec colnum="2" colname="2">
<colspec colnum="1" colname="1">
but i want to collect all result like as below
<colspec colnum="3" colname="3"><colspec colnum="2" colname="2"><colspec colnum="1" colname="1">
Would you tell me which part wrong is ?
You can fix the code by following where Blank_text = "" is moved before while loop and print(Blank_text) is called after the loop.
(Note: since Blank_text accumulates, variable name changed to accumulated_text as suggested in the comment):
ColumnCount_int = 3
accumulated_text = "" # variable name changed, used instead of Blank_text
while ColumnCount_int > 0 :
ColumnCount_text = str('<colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCount_int) + '">')
accumulated_text = accumulated_text + ColumnCount_text
ColumnCount_int = ColumnCount_int - 1
print(accumulated_text)
Result:
<colspec colnum="3" colname="3"><colspec colnum="2" colname="2"><colspec colnum="1" colname="1">
Update:
However, same result can be from following in little compact way with .join:
result = ''.join('<colspec colnum="{0}" colname="{1}">'.format(i,i) for i in range(3,0,-1))
print(result)
Try appending it to the new list i created l, then do ''.join(l) to output it in one line :
l = []
ColumnCount_int = 3
while ColumnCount_int > 0 :
ColumnCount_text = str('<colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCount_int) + '">')
Blank_text = ColumnCount_text
ColumnCount_int = ColumnCount_int - 1
l.append(Blank_text)
print(''.join(l))
Output:
<colspec colnum="3" colname="3"><colspec colnum="2" colname="2"><colspec colnum="1" colname="1">
Shorter Way
Also try this:
l = []
ColumnCount_int = 3
while ColumnCount_int > 0 :
l.append(str('<colspec colnum="'+str(ColumnCount_int)+'"'' ''colname="'+str(ColumnCount_int)+'">'))
ColumnCount_int-=1
print(''.join(l))
Output:
<colspec colnum="3" colname="3"><colspec colnum="2" colname="2"><colspec colnum="1" colname="1">