我已经写了一个程序,读取一个由10对数字组成的文件,然后将这两个文件分开,产生混合部分,然后将其添加到原始文档。但是,我希望错误消息与对的顺序相同。我的文件包括:追加到文件和消息出现在错误的顺序python
66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
98 21
,我的计划是这样的:
from fractions import gcd
x=0
y=0
global index
index=0
wordlist=[]
with open('topheavy.txt','r') as f:
for line in f:
for word in line.split():
print(word)
wordlist.append(word)
print (wordlist)
print (len(wordlist))
def mixedfraction():
global index
while index<len(wordlist):
global x
global y
x=wordlist[index]
y=wordlist[index+1]
neg=False
with open ('topheavy.txt','a') as g:
try:
float(x)
except ValueError:
g.write ('x is not a number.\n')
global index
index+=2
mixedfraction()
try:
float(y)
except ValueError:
g.write ('y is not a number.\n')
global index
index+=2
mixedfraction()
#the above code checks if its a number.
x=int(x)
y=int(y)
orx=0
ory=0
orx+=x
ory+=y
if x==0 or y==0:
with open ('topheavy.txt','a') as g:
g.write ('you cant divide by 0!\n')
global index
index+=2
mixedfraction()
#this is to make sure you dont get a divide by 0 error.
if x<0 and not y<0:
neg=True
x*=-1
elif y<0 and not x<0:
neg=True
y*=-1
if 1==1:
xy=(x//y)
modxy=(x%y)
modxy=round(modxy,0)
xy=round(xy,0)
y=round(y,0)
xdivisor=gcd(modxy, y)
modxy//=xdivisor
y//=xdivisor
#the above 3 lines reduce the fraction, as do the similar 3 lines in the other bit of code.
with open ('topheavy.txt','a') as g:
if modxy!=0 and xy!=0:
b= ('{}/{}={} and {}/{}\n'.format(orx,ory,xy, modxy, y ))
if neg==True:
b=(' {}/{}=-{} and {}/{}\n'.format(orx,ory,xy, modxy, y ))
g.write (b)
elif modxy==0 and xy!=0:
b= ('{}/{}={} \n'.format(orx,ory,xy))
if neg==True:
b=(' {}/{}=-{} \n'.format(orx,ory,xy))
g.write (b)
elif xy==0:
b=('{}/{}={}/{} \n'.format(orx,ory,modxy, y))
if neg==True:
b=('{}/{}=-{}/{} \n'.format(orx,ory,modxy, y))
g.write (b)
#this if clause stops the program from saying '5 and 0/5' or a similar thing.
global index
index=index+2
mixedfraction()
当我运行它,我得到这个:
66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
98 2166/556=33/278
-56/78=-28/39
43/76=43/76
6/5=1 and 1/5
98/76=1 and 11/38
4/2=2
66/54=1 and 2/9
98/21=4 and 2/3
x is not a number.
98/3=32 and 2/3
you cant divide by 0!
0/5=32 and 2/3
的 '你不能除以0' 消息在错误的地方,'x不是数字'的信息也是如此。我不知道如何让他们去正确的地方。然后在最后添加一些奇怪的随机行,这不应该在那里。我已经找遍了,找不到解决方案。谢谢你的帮助。
我要的是:
66 556
-56 78
43 76
0 5
6 5
a 4
98 76
4 2
66 54
66/556=answer
-56/78=answer
43/76=answer
you cant divide by 0!
6/5=answer
x is not a number!
98/76=answer
4/2= answer
66/54=answer
请提供您期望的例子。 – Alderven 2014-10-31 12:35:54
我加了。谢谢 – Sawyer 2014-10-31 13:05:27
为什么你不能划分0 \ 5?只有在5 \ 0的情况下才能分割。 – Alderven 2014-10-31 13:12:05