-1

I have a text file (s1.txt) containing the following information. There are some lines that contain only one number and others that contain two numbers separated by a hyphen.

1
3-5
10
11-13
111
113-150
1111
1123-1356

My objective is to write a program that reads the file line by line, subtracts each number from one, replaces hyphens with colons, and prints the output on one single line. The following is my expected outcome.

{0 2:4 9 10:12 110 112:149 1110 1122:1355}

Using the following code, I am receiving an output that is quite different from what I expected. Please, let me know how I can correct it.

    s1_file = input("Enter the name of the S1 file: ")
    s1_text = open(s1_file, "r")
    # Read contents of the S1 file to string
    s1_data = s1_text.read()
    for atoms in s1_data.split('\n'):
        if atoms.isnumeric():
            qm_atom = int(atoms) - 1
            #print(qm_atom)
        else:
           qm_atom = atoms.split('-')
        print(qm_atom)
  • 1
    what output do you see when you run your code? – ACarter Feb 14 '23 at 13:00
  • the output is 0 ['3', '5'] 9 ['11', '13'] 110 ['113', '150'] 1110 ['1123', '1356'] [''] – Mehdi Irani Feb 14 '23 at 13:20
  • Please read about [how to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). You can also use [Python Tutor](http://www.pythontutor.com/visualize.html#mode=edit) to run your code line-by-line. Lastly, after debugging your code, create a [mre] of a ***specific*** problem you found in the process and ask about that – Tomerikoo Feb 14 '23 at 14:11
  • Comparing the output you get with your expected output. what do you feel is the main difference? In which execution branch does this difference comes from? What do you think you can (or need) to do to close that gap? Did you think of what could be the cause? Did you try to do something to fix it that failed? To further guide you: your current output has lists of strings. It looks like you want to convert the strings to numbers, subtract one, and then ***join*** them with a hyphen. All those steps are already answered on SO. You just need to break down your problem and solve each sub-problem – Tomerikoo Feb 14 '23 at 14:16
  • [Convert all strings in a list to int](https://stackoverflow.com/q/7368789/6045800) ; [How to concatenate (join) items in a list to a single string](https://stackoverflow.com/q/12453580/6045800) – Tomerikoo Feb 14 '23 at 14:17

3 Answers3

0

If your goal is to output directly to the screen as a single line you should add end=' ' to the print function. Or you can store the values in a variable and print everything at the end.

Regardless of that, you were missing at the end to subtract 1 from the values and then join them with the join function. The join function is used on a string where it creates a new string with the values of an array (all values must be strings) separated by the string on which the join method is called.

For example ', '.join(['car', 'bike', 'truck']) would get 'car, bike, truck'.

s1_file = input("Enter the name of the S1 file: ")
s1_text = open(s1_file, "r")
# Read contents of the S1 file to string

s1_data = s1_text.read()
output = []
for atoms in s1_data.split('\n'):
    if atoms.isnumeric():
        qm_atom = int(atoms) - 1
        output.append(str(qm_atom))
    else:
        qm_atom = atoms.split('-')
        # loop the array to subtract 1 from each number
        qm_atom_substrated = [str(int(q) - 1) for q in qm_atom]
        # join function to combine int with :
        output.append(':'.join(qm_atom_substrated))

print(output)
0

An alternative way of doing it could be:

s1_file = input("Enter the name of the S1 file: ")
with open (s1_file) as f:
    output_string = ""
    for line in f:
        elements = line.strip().split('-')
        elements = [int(element) - 1 for element in elements]
        elements = [str(element) for element in elements]
        elements = ":".join(elements)
        output_string += elements + " "

print(output_string)
bigkeefer
  • 576
  • 1
  • 6
  • 13
0

why are you needlessly complicating a simple task by checking if a element is numerical then handle it else handle it differently. Also your code gave you a bad output because your else clause is incorrect , it just split elements into sub lists and there is no joining of this sub list with ':'

anyways here is my complete code

f=open(s1_file,'r')
t=f.readlines()#reading all lines
for i in range(0,len(t)):
 t[i]=t[i][0:-1]#removing /n
 t[i]=t[i].replace('-',':') #replacing - with :
 try:t[i]=int(t[i])-1 #convert str into int & process
 except:
  t[i]=f"{int(t[i].split(':')[0])-1}:{int(t[i].split(':')[1])-1}" #if str case then handle
print(t)
Vishnu Balaji
  • 175
  • 1
  • 11