'Take char and numbers from file separately
I'm working on a program where I need to take numbers from a file and perform certain actions such as inserting, deleting, or searching for them in a binary search tree. The files are formatted as such:
S 11
I 26
S 28
D 1
S 7
Q 5
I 17
D 22
S 11
Where 'S' stands for search, 'I' Insert, and 'D' delete. Any other character is to be considered an invalid action.
I am having trouble reading from the file and getting the numbers separate from the characters. My idea to go about this is to get the characters into one array and the numbers into another. Once I do that I figure I can just iterate through both arrays and each number should align with its corresponding action and I can go from there. I'm just unsure how to get one array of just the letters and another array of just the numbers.
Any help would be much appreciated! Thanks!
Solution 1:[1]
When you have this kind of .txt file, the answer by Sandra Naddaf is for sure the best solution, but when you don't know where the chars and the ints are...
with open("file.txt", 'r') as file:
data = file.read()
data = data.split()
for i, v in enumerate(data):
try:
data[i] = int(v)
except ValueError:
pass
Solution 2:[2]
Write discrete functions for handling the Search, Insert and Delete operations. Read the file one line at a time and split each line into two tokens. Do this within a try/except in case there are any lines in the file that don't conform with the expected format. Match the first token against the known/wanted values (S/I/D)
def doSearch(v):
pass
def doInsert(v):
pass
def doDelete(v):
pass
with open('file.txt') as infile:
for line in infile:
try:
a, v, *_ = line.split()
match a:
case 'S':
doSearch(v)
case 'I':
doInsert(v)
case 'D':
doDelete(v)
case _:
pass
except ValueError:
pass
Obviously, match is only available in Python 3.10+ so here's a different approach for Python 3.8+
funcMap = {'S': doSearch, 'I': doInsert, 'D': doDelete}
with open('file.txt') as infile:
for line in infile:
try:
a, v, *_ = line.split()
if (func := funcMap.get(a)):
func(v)
except ValueError:
pass
Solution 3:[3]
I think this would work:
nums=[]
chars=[]
with open('file.txt') as f:
for l in f:
c,n = l.split()
nums.append(int(n))
chars.append(c)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | FLAK-ZOSO |
| Solution 2 | |
| Solution 3 |
