split function
Bengt Richter
bokr at oz.net
Tue Aug 23 18:07:34 EDT 2005
On Mon, 22 Aug 2005 22:14:55 +0200, Mohammed Altaj <mohammed at aims.ac.za> wrote:
>
>Dear all
>
>Sorry , I confused between two things , what i said in the last e-mail i
>already managed to do using C code , But what i need to do using python
>is : my input data :
>
>0 2 3 4
>1 2 4
>2 3
>3 4
>
>what i suppose to do is , using the first line and start searching
>number by number ,first i have 0 search in the rest of lines if there is
>0 print out the all numbers except 0 , after that , start searching
>using the 2ed element in the first line which is 2 , in the 2ed line we
>have 1 , 4 . in the 3rd line we have 3 , in the 4th line we do not have
>2. And so on for 3 and 4 , and also for the 2nd , 3rd lines , so the
>output should be
>
>0 2 1 4 3 3 2 4 4 1 2 3
>1 2 3 4 3
>2 3
>3 4
>
>And i managed to do this , but i did in the case of no space between
>numbers,when i am reading from file , like
>0234
>124
>23
>34
>
>I want my code be able to deal with the space between numbers , and this
>is my code again
>def belong_to(x,a):
> c=-1
> for i in range(len(a)-1):
> if x==int(a[i]):
> c=i
> return c
>
>def list_belong(x,a): # This function to check if this line
> c=-1 # line has been searched before or not
> for i in range(len(a)):
> if a[i]==x:
> c=1
> break
> return c
>
>x=0
>occur=[]
>
>in_file=open('data.dat','r')
>out_file=open('result.dat','w')
>fileList = in_file.readlines()
>for k in fileList:
> v=k
> occur.append(k)
> n=len(v)-1
> for i in range(n):
> temp=int(v[i])
> print temp,
> out_file.write(str(temp))
> for line in fileList:
> if v!=line:
> if list_belong(line,occur)!=1:
> if belong_to(temp,line) != -1:
> j=belong_to(temp,line)
> for i in range(len(line)-1):
> if i!=j:
> print line[i],
> out_file.write(line[i])
>
>
>
> print
> out_file.write("\n")
>
>out_file.close()
>in_file.close()
>
>
>Thanks
>
Does this do what you want? (except that it writes to stdout and doesn't print)?
(note that I get 234 instead of 23 on the 3rd line of output)
>>> # test with string file input and stdout output
... import StringIO
>>> in_file = StringIO.StringIO("""\
... 0 2 3 4
... 1 2 4
... 2 3
... 3 4
... """)
>>> import sys
>>> out_file = sys.stdout
>>>
>>> lines = [''.join(line.split()) for line in in_file] # clean out spaces and '\n'
>>> for i, line in enumerate(lines):
... for digit in line:
... out_file.write(digit)
... for followingline in lines[i+1:]:
... if digit not in followingline: continue
... line_sans_digit = followingline.replace(digit,'')
... out_file.write(line_sans_digit)
... out_file.write("\n")
...
021433244123
12343
234
34
Also note that I eliminated all duplicate digits from a selected line, rather than just the
first match. Easy to change.
Regards,
Bengt Richter
More information about the Python-list
mailing list