Reading an unknown number of lines in a file - python

I wrote the code below, but it specifies the number of lines in the file. I'm wondering how I can change it so that it will read an unknown number of lines?
n = int(input("instance: "))
tp, tn, fp, fn = 0
for i in range(n):
real, predicted = map(int, input().split(' '))
for num in i:
if real == 1 and predicted == 1:
tp += 1
elif real == 0 and predicted == 0:
tn += 1
elif real == 1 and predicted == 0:
fn += 1
else:
fp += 1
pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)
My code reads these lines and compares numbers on each line with each other, but not with numbers on the other lines.
The input looks like this:
1 1
0 0
0 1
0 1
1 0
0 1
0 0
1 1
0 0
0 0
0 0
0 0
1 1

Keep reading until EOFError is thrown:
tp, tn, fp, fn = 0
i = 0
try:
while True:
real, predicted = map(int, input().split(' '))
for num in i:
if real == 1 and predicted == 1:
tp += 1
elif real == 0 and predicted == 0:
tn += 1
elif real == 1 and predicted == 0:
fn += 1
else:
fp += 1
i += 1
except EOFError:
pass
pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)
Your code has errors too:
multiple variables can't be assigned to the same value using unpacking.
range needs to be used if you want to count up to a number.
This should fix them:
tp = tn = fp = fn = 0
i = 0
try:
while True:
real, predicted = map(int, input().split(' '))
for num in range(i):
if real == 1 and predicted == 1:
tp += 1
elif real == 0 and predicted == 0:
tn += 1
elif real == 1 and predicted == 0:
fn += 1
else:
fp += 1
i += 1
except EOFError:
pass
pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)

Related

Program doesn't work after making exe file by pyinstaller

I made a Python program using numpy, sympy, sys which worked well in IDE. Here is the code...
import numpy as np
from sympy import *
import sys
f = open("result.txt", 'w+')
for line in sys.stdin:
f.write(line)
f.close()
f = open("result.txt", 'r')
data = f.read().split("\n")
i = 0
while i < len(data):
data[i] = data[i].split(' ')
i += 1
print(data)
amount = int(data[0][0])
print(amount)
matrix = np.zeros((amount, amount))
i = 0
j = 0
while i < amount:
while j < amount:
matrix[i, j] = int(data[i + 1][j])
j += 1
j = 0
i += 1
i = 0
j = 0
counter = 0
formula = 1
while i < amount:
while j < amount:
if matrix[i, j] == 1:
x = symbols(str(i + 1))
y = symbols(str(j + 1))
if counter == 0:
formula = (~x | ~y)
counter += 1
else:
formula = formula & (~x | ~y)
j += 1
j = 0
i += 1
formula_to_string = pycode(simplify_logic(formula, form='dnf', force=True))
massive_to_parse = formula_to_string.split("or")
k = 1
i = 0
while i < len(massive_to_parse):
print("{", end='')
while k < amount + 1:
try:
massive_to_parse[i].index(str(k))
except ValueError:
print("V",k, sep='', end='')
finally:
k += 1
print("}-максимальное внутренне устойчивое множество")
k = 1
i += 1
Then I made an exe file using pyinstaller with this command...
pyinstaller main.py
but when i launch it, this errors appear.
How can I fix this problem? Because I need exe file for university to launch it from other program on C

PYTHON 3.0 Negative numbers aren't working as inputs

I'm trying to make a factoring program, but it doesn't seem to work with negative number a-, b- and c-inputs.
from fractions import gcd
factor = -1
opp = 0
number = 1
success = 0
a = int(input("a-value: "))
b = int(input("b-value: "))
c = int(input("c-value: "))
factors = []
d = 0
e = 0
while number <= abs(a*c):
#Checking for multiples
if abs(a*c) % number == 0:
factor += 1
factors.append(number)
number += 1
while (factor-opp) >= 0:
#Checking for actual factors
d = int(factors[factor])
e = int(factors[opp])
if (abs(d+e) or abs(d-e)) == abs(b):
success += 1
break
else:
factor -= 1
opp += 1
if success > 0:
if (d+e) == b:
e = e
elif (d-e) == b:
e -= 2*e
elif (e-d) == b:
d -= 2*d
elif (-d-e) == b:
d -= 2*d
e -= 2*e
#Figuring out the equation
if d % a == 0:
d /= a
f = 1
else:
f = a/gcd(d,a)
d /= gcd(d,a)
if e % a == 0:
e /= a
g = 1
else:
g = a/gcd(e,a)
e /= gcd(e,a)
#Displaying the answer
if d >= 0:
d = str("+" + str(int(d)))
if e >= 0:
e = str("+" + str(int(e)))
elif e < 0:
e = str(int(e))
else:
d = str(int(d))
if e >= 0:
e = str("+" + str(int(e)))
elif e < 0:
e = str(int(e))
if f == 1:
if g == 1:
print ("(x" + d + ")(x" + e + ")")
else:
g = str(int(g))
print ("(x" + d + ")(" + g + "x" + e + ")")
elif g == 1:
f = str(int(f))
print ("(" + f + "x" + d + ")(x" + e + ")")
else:
f = str(int(f))
g = str(int(g))
print ("(" + f + "x" + d + ")(" + g + "x" + e + ")")
else:
print("This equation cannot be factored into integers.")
More specifically, the problem is somewhere within this block, I think. I've tested it out with print statements:
while (factor-opp) >= 0:
#Checking for actual factors
d = int(factors[factor])
e = int(factors[opp])
if (abs(d+e) or abs(d-e)) == abs(b):
success += 1
break
else:
factor -= 1
opp += 1
I've searched everywhere: my programming textbook, online searches about inputting negatives, everything. What am I doing wrong here?
Ok I am able to reproduce your issue for a simple testcase like - a=1 , b=0, c=-4 .
The issue is in the line -
if (abs(d+e) or abs(d-e)) == abs(b):
This does not check whether abs(b) is equal to abs(d+e) or abs(d-e) , instead it first evaluates the result of (abs(d+e) or abs(d-e)) , which would return the first non-zero result , and then compare that against abs(b) , so for negative numbers this does not evaluate the result correctly. Change that condition to -
if abs(d+e) == abs(b) or abs(d-e) == abs(b):
or you can also use a set -
if abs(b) in {abs(d+e), abs(d-e)}: #Though I doubt if using set would give any performance improvement because of the overhead of creating a set.
Demo after changes -
a-value: 1
b-value: 0
c-value: -4
(x+2)(x-2)
a-value: 1
b-value: -1
c-value: -6
(x-3)(x+2)
One more thing, there is something you have not considered , when a=-1 , b=-4 , c=-4 , the result should come to -(x+2)(x+2) , but the current program results in (x+2)(x+2) .

print values after each 1000 step

I want to print value after every certain interval (1000) on last line of code than every single value.
DARTS=200000
hits = 0
throws = 0
rangen = RanGenerator()
pi = 0
avg = 0
mu = 0
var = 0
dev = 1
for i in range (1, DARTS):
throws += 1
x = rangen.rand()
y = rangen.rand()
z = rangen.rand()
tt = x**2 + y**2 + z**2
dist = sqrt(tt)
if dist <= 1.0:
hits = hits + 1.0
pi = 6 * (hits / throws)
avg = avg + pi
mu = avg/throws
var = (var+(mu-pi)**2)/throws
dev = sqrt(var)
print("%d: %s" % (i,dev))
This is easy with the modulo operator - it will print the values only when i is divisible by 1000:
if i % 1000 == 0:
print("%d: %s" % (i,dev))

Need help in adding binary numbers in python

If I have 2 numbers in binary form as a string, and I want to add them I will do it digit by digit, from the right most end. So 001 + 010 = 011
But suppose I have to do 001+001, how should I create a code to figure out how to take carry over responses?
bin and int are very useful here:
a = '001'
b = '011'
c = bin(int(a,2) + int(b,2))
# 0b100
int allows you to specify what base the first argument is in when converting from a string (in this case two), and bin converts a number back to a binary string.
This accepts an arbitrary number or arguments:
>>> def bin_add(*bin_nums: str) -> str:
... return bin(sum(int(x, 2) for x in bin_nums))[2:]
...
>>> x = bin_add('1', '10', '100')
>>> x
'111'
>>> int(x, base = 2)
7
Here's an easy to understand version
def binAdd(s1, s2):
if not s1 or not s2:
return ''
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) + int(s2[i])
if s == 2: #1+1
if carry == 0:
carry = 1
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
elif s == 1: # 1+0
if carry == 1:
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
else: # 0+0
if carry == 1:
result = "%s%s" % (result, '1')
carry = 0
else:
result = "%s%s" % (result, '0')
i = i - 1;
if carry>0:
result = "%s%s" % (result, '1')
return result[::-1]
Can be simple if you parse the strings by int (shown in the other answer). Here is a kindergarten-school-math way:
>>> def add(x,y):
maxlen = max(len(x), len(y))
#Normalize lengths
x = x.zfill(maxlen)
y = y.zfill(maxlen)
result = ''
carry = 0
for i in range(maxlen-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
# r can be 0,1,2,3 (carry + x[i] + y[i])
# and among these, for r==1 and r==3 you will have result bit = 1
# for r==2 and r==3 you will have carry = 1
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(maxlen)
>>> add('1','111')
'1000'
>>> add('111','111')
'1110'
>>> add('111','1000')
'1111'
It works both ways
# as strings
a = "0b001"
b = "0b010"
c = bin(int(a, 2) + int(b, 2))
# as binary numbers
a = 0b001
b = 0b010
c = bin(a + b)
you can use this function I did:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
#a = int('10110', 2) #(0*2** 0)+(1*2**1)+(1*2**2)+(0*2**3)+(1*2**4) = 22
#b = int('1011', 2) #(1*2** 0)+(1*2**1)+(0*2**2)+(1*2**3) = 11
sum = int(a, 2) + int(b, 2)
if sum == 0: return "0"
out = []
while sum > 0:
res = int(sum) % 2
out.insert(0, str(res))
sum = sum/2
return ''.join(out)
def addBinary(self, A, B):
min_len, res, carry, i, j = min(len(A), len(B)), '', 0, len(A) - 1, len(B) - 1
while i>=0 and j>=0:
r = carry
r += 1 if A[i] == '1' else 0
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
j -= 1
while i>=0:
r = carry
r += 1 if A[i] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
while j>=0:
r = carry
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
j -= 1
if carry == 1:
return '1' + res
return res
#addition of two binary string without using 'bin' inbuilt function
numb1 = input('enter the 1st binary number')
numb2 = input("enter the 2nd binary number")
list1 = []
carry = '0'
maxlen = max(len(numb1), len(numb2))
x = numb1.zfill(maxlen)
y = numb2.zfill(maxlen)
for j in range(maxlen-1,-1,-1):
d1 = x[j]
d2 = y[j]
if d1 == '0' and d2 =='0' and carry =='0':
list1.append('0')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='1':
list1.append('1')
carry = '1'
elif (d1 == '1' and d2 =='0' and carry =='0') or (d1 == '0' and d2 =='1' and
carry =='0') or (d1 == '0' and d2 =='0' and carry =='1'):
list1.append('1')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='0':
list1.append('0')
carry = '1'
else:
list1.append('0')
if carry == '1':
list1.append('1')
addition = ''.join(list1[::-1])
print(addition)
Not an optimal solution but a working one without use of any inbuilt functions.
# two approaches
# first - binary to decimal conversion, add and then decimal to binary conversion
# second - binary addition normally
# binary addition - optimal approach
# rules
# 1 + 0 = 1
# 1 + 1 = 0 (carry - 1)
# 1 + 1 + 1(carry) = 1 (carry -1)
aa = a
bb = b
len_a = len(aa)
len_b = len(bb)
min_len = min(len_a, len_b)
carry = 0
arr = []
while min_len > 0:
last_digit_aa = int(aa[len(aa)-1])
last_digit_bb = int(bb[len(bb)-1])
add_digits = last_digit_aa + last_digit_bb + carry
carry = 0
if add_digits == 2:
add_digits = 0
carry = 1
if add_digits == 3:
add_digits = 1
carry = 1
arr.append(add_digits) # will rev this at the very end for output
aa = aa[:-1]
bb = bb[:-1]
min_len -= 1
a_len_after = len(aa)
b_len_after = len(bb)
if a_len_after > 0:
while a_len_after > 0:
while carry == 1:
if len(aa) > 0:
sum_digit = int(aa[len(aa) - 1]) + carry
if sum_digit == 2:
sum_digit = 0
carry = 1
arr.append(sum_digit)
aa = aa[:-1]
else:
carry = 0
arr.append(sum_digit)
aa = aa[:-1]
else:
arr.append(carry)
carry = 0
if carry == 0 and len(aa) > 0:
arr.append(aa[len(aa) - 1])
aa = aa[:-1]
a_len_after -= 1
if b_len_after > 0:
while b_len_after > 0:
while carry == 1:
if len(bb) > 0:
sum_digit = int(bb[len(bb) - 1]) + carry
if sum_digit == 2:
sum_digit = 0
carry = 1
arr.append(sum_digit)
bb = bb[:-1]
else:
carry = 0
arr.append(sum_digit)
bb = bb[:-1]
else:
arr.append(carry)
carry = 0
if carry == 0 and len(bb) > 0:
arr.append(bb[len(bb) - 1])
bb = bb[:-1]
b_len_after -= 1
if carry == 1:
arr.append(carry)
out_arr = reversed(arr)
out_str = "".join(str(x) for x in out_arr)
return out_str

Python says: "IndexError: string index out of range."

I am making some practice code for a game similar to the board game, MasterMind-- and It keeps coming out with this error, and I can't figure out why it's doin it. Here's the code:
def Guess_Almost (Guess, Answer):
a = ''.join([str(v) for v in Answer])
g = str(Guess)
n = 0
am = 0
while n < 5:
if g[n] == a[0]:
am = am + 1
if g[n] == a[2]:
am = am + 1
if g[n] == a[3]:
am = am + 1
if g[n] == a[3]:
am = am + 1
n = n + 1
return(am)
Okay, the Guess is specified to be 4 integers, and the Answer is a list containing 4 numbers. They both have the same 'len' after the code, so i don't have a clue.
The point of this code is to turn the Answer into a string of 4 numbers, and see if any of those numbers match thoise of the guess, and return how many total matches there are.
See if this helps
def Guess_Almost (Guess, Answer):
a = ''.join([str(v) for v in Answer])
g = str(Guess)
n = 0
am = 0
if len(g) >= 5 and len(a) >=4:
while n < 5:
if g[n] == a[0]:
am = am + 1
if g[n] == a[2]:
am = am + 1
if g[n] == a[3]:
am = am + 1
if g[n] == a[3]:
am = am + 1
n = n + 1
return(am)

Categories