import numpy as np
def AND(x1, x2):
x = np.array(x1,x2)
w = np.array(0.5,0.5)
b = -0.7
tmp = np.sum(w*x) + b
if tmp <= 0:
return 0
else:
return 1
def NAND(x1, x2):
x = np.array([x1, x2])
w = np.array([-0.5, -0.5])
b = 0.7
tmp = np.sum(w*x) + b
if tmp <= 0:
return 0
else:
return 1
print(NAND(1,0))
print(NAND(1,1))
def OR(x1, x2):
x = np.array([x1, x2])
w = np.array([0.5, 0.5])
b = -0.2
tmp = np.sum(w*x) + b
if tmp <= 0:
return 0
else:
return 1
print(OR(0,1))
print(OR(0,0))
def XOR(x1, x2):
s1 = NAND(x1,x2)
s2 = OR(x1,x2)
y = AND(s1,s2)
return y
print(XOR(0,1))
I completed AND, OR, NAND gate. and they all works really precisely as i expected. And finally i tried to make a XOR logic by combining NAND, OR, AND in sequence... But here comes the traceback error message i 've never expected like below. What should be modified to fulfill my original purpose.
TypeError: Cannot interpret '1' as a data type
The first (and second) line of AND is not the same as the first line of OR and NAND. That's the problem. See it?
Ironic that you had unit tests for OR and NAND, but not for AND.
I'm given a problem that explicitly asks me to not use either numpy or pandas
Problem :
Given two set of data points in the form of list of tuples like
Red =[(R11,R12),(R21,R22),(R31,R32),(R41,R42),(R51,R52),..,(Rn1,Rn2)]
Blue=[(B11,B12),(B21,B22),(B31,B32),(B41,B42),(B51,B52),..,(Bm1,Bm2)]
and set of line equations(in the string format, i.e list of strings)
Lines = [a1x+b1y+c1,a2x+b2y+c2,a3x+b3y+c3,a4x+b4y+c4,..,K lines]
Note: You need to do string parsing here and get the coefficients of x,y and intercept.
Your task here is to print "YES"/"NO" for each line given. You should print YES, if all the red points are one side of the line and blue points are on other side of the line, otherwise you should print NO.
Ex:
Red= [(1,1),(2,1),(4,2),(2,4), (-1,4)]
Blue= [(-2,-1),(-1,-2),(-3,-2),(-3,-1),(1,-3)]
Lines=["1x+1y+0","1x-1y+0","1x+0y-3","0x+1y-0.5"]
Output:
YES
NO
NO
YES
Mathematically, you take the equation of the line say S
Suppose S(x)(y) = 1x+1y+0
Now take points (1,1) and (-6,-1)
S(1)(1) = 1(1)+ 1(1) = 2 >0
S(-6)(-1) = 1(-6)+(1)(-1) = -7 <0
Therefore, we can conclude that (1,1) and (-6,-1) lie on different sides of the line S.
Now in the given problem, given an equation S all red should be on one side of the equation and blue on the other side.
The issue here is that, I'm not sure how you substitute values of the points in the lists in the equation given in the form of a string using python.
Also, I'm falling short of coming up with a logic (how to use loops accroding to our requirement) for the code to solve the above to solve the above question.
Would appreciate insights on this question. Thanks in advance.
use your_string.replace() and eval() function,
replace x and y characters with it's values,
eval() to execute string as equation
for element in red:
equation=line.replace('x','*'+str(element[0]))
equation=equation.replace('y','*'+str(element [1]))
result=eval(equation)
if result > 0:
pass
else:
return "NO"
#code for blue
return "Yes"
Assuming you strings are always of the form
ax+by+c
(in that order), you could write
import re
for line in Lines:
a, b, c = [float(coef.strip()) for coef in re.split('x|y', line)]
...
Python3 program to check if two points lie on the same side
def pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2):
fx1 = 0 # Variable to store a * x1 + b * y1 - c
fx2 = 0 # Variable to store a * x2 + b * y2 - c
fx1 = a * x1 + b * y1 - c
fx2 = a * x2 + b * y2 - c
# If fx1 and fx2 have same sign
if ((fx1 * fx2) > 0):
return True
return False
Driver code
a, b, c = 1, 1, 1
x1, y1 = 1, 1
x2, y2 = 2, 1
if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)):
print("Yes")
else:
print("No")
#hemanth ravavarapu, re.split(x|y) will be splitting line equation based on x or y. i.e if you give space then it will split based on space same here also it splitting where ever it found x or y.
e1 = []
e2 = []
def points():
for k in Lines:
a=k[0];b=k[2]+k[3];c=k[5]+k[6]
n = [];m=[]
for i in Red:
x1=i[0];y1=i[1]
eq1 = int(a) * int(x1) + int(b) * int(y1)-int(c)
n.append(eq1)
e1.append(n)
for j in Blue:
x2=j[0];y2=j[1]
eq2 = int(a) * int(x2) + int(b) * int(y2)-int(c)
m.append(eq2)
e2.append(m)
print(e1)
print('----------------------------------------------------------------------')
print(e2)
print('----------------------------------------------------------------------')
p=[]
for i,j in zip(e1,e2):
q = []
for k,l in zip(i,j):
x=k*l
if x<0:
q.append(x)
p.append(q)
print(p)
for i in p:
if len(i)==5:
print('yes')
else:
print('No')
Red= [(1,1),(2,1),(4,2),(2,4),(-1,4)]
Blue= [(-2,-1),(-1,-2),(-3,-2),(-3,-1),(1,-3)]
Lines=["1x+1y+0","1x-1y+0","1x+0y-3","0x+1y-0.5"]
points()
For string parsing :
def getCor(s):
first = s.split('x')
a = float(first[0])
second = first[1].split('y')
b = float(second[0])
c = float(second[1])
return (a,b,c)
getCor('24x+1y-0.5')
Output :
(24.0, 1.0, -0.5)
import math
def getCor(s):
first = s.split('x')
a = float(first[0])
second = first[1].split('y')
b = float(second[0])
c = float(second[1])
return (a,b,c)
def getSide(t,p):
cal = (t[0] * p[0]) + (t[1] * p[1]) + (t[2])
if cal > 0:
return 1
elif cal < 0:
return -1
elif cal == 0:
return 0
return -2
def getAns(red,blue,line):
sign_red = getSide(getCor(line),red[0])
sign_blue = getSide(getCor(line),blue[0])
for j in range(len(red)):
if sign_red != getSide(getCor(line),red[j]):
return 'no'
for j in range(len(blue)):
if sign_blue != getSide(getCor(line),blue[j]):
return 'no'
return 'Yes'
Red= [(1,1),(2,1),(4,2),(2,4), (-1,4)]
Blue= [(-2,-1),(-1,-2),(-3,-2),(-3,-1),(1,-3)]
Lines=["1x+1y+0","1x-1y+0","1x+0y-3","0x+1y-0.5"]
for i in Lines:
ans = getAns(Red, Blue, i)
print(ans)
output:
Yes
no
no
Yes
import math
# write your python code here
# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given input strings
# you can free to change all these codes/structure
def i_am_the_one(red,blue,line):
# your code
for i in red:
eq=line.replace('x','*'+str(i[0]))
eq=eq.replace('y','*'+str(i[1]))
answer=eval(eq)
if answer>0:
pass
else:
return "NO"
# Code for Blue
for j in blue:
eq1=line.replace('x','*'+str(j[0]))
eq1=eq1.replace('y','*'+str(j[1]))
answer1=eval(eq1)
if answer1<0:
pass
else:
return "NO"
return "Yes"
Red= [(1,1),(2,1),(4,2),(2,4), (-1,4)]
Blue= [(-2,-1),(-1,-2),(-3,-2),(-3,-1),(1,-3)]
Lines=["1x+1y+0","1x-1y+0","1x+0y-3","0x+1y-0.5"]
for i in Lines:
yes_or_no = i_am_the_one(Red, Blue, i)
print(yes_or_no)
I have a function u_terme that computes values of the sequence 3u + 1. I would like a stop function reached(M) that returns the lowest u value at which a given functional value is reached.
However, my code below doesn't work: it exits immediately and prints a single 0. Help?
def u_terme(x):
i = 0
u = 0
while i < x:
u = (3 * u) + 1
i = i + 1
print(u)
def reached(M):
x = 0
f = 0
while f >= M:
f = u_terme(x)
x = x + 1
print(x)
ANALYSIS:
u_terme fails to return any value.
reached exits immediately: your while loop quits as soon as f < M.
You have that logic reversed: you want to continue while f <= M.
Also, please use meaningful variable names.
REPAIR:
Make u_term return the computed value:
def u_terme(x):
u = 0
for i in range(x):
u = 3*u + 1
# print x, u
return u
Make reached iterate properly and return its result:
def reached(limit):
val = 0
func_val = 0
while func_val < limit:
val += 1
func_val = u_terme(val)
print val, func_val
return val
print reached(50)
Output:
1 1
2 4
3 13
4 40
5 121
5
Output:
17
Unfortunately the question is so unclear that it is difficult to provide a definitive answer. For example, what are allowable values of M?
At the first look, however, it is obvious that your u_terme() function has no return value (well, that is, it always return None). This means that f in the reached() function after the first iteration will be None and the loop will terminate.
Just because back-in-forth in comments doesn't work to well, I think this is the correct simplified, more efficient version of the code:
def u_terme(u):
return (3 * u) + 1
def reached(M):
x = 0
u = 0
while u < M:
u = u_terme(u)
x += 1
return x
print(reached(50)) # 5
EDIT
To help with the confusion in the comments. This new u_terme doesn't do what the previous one did. The previous one took a number x and computed u x times. This new one just returns the next value based on the previous one. This avoids duplicate work.
This code shows how to use it to get the expected values:
def u_terme(u):
return (3 * u) + 1
u = 0
for i in range(5):
print(i, u)
u = u_terme(u)
# Output:
# 0 0
# 1 1
# 2 4
# 3 13
# 4 40
EDIT 2
Just for fun, here's another way to do this. Why this is correct is an exercise left to the reader. :-)
def reached(M):
u = 0
x = 0
while u < M:
u += 3**x
x += 1
return x
I'm a beginner in Python, and tried to take MIT 6.00, the page provided is the assignments page.
I'm at assignment 2, where i have to find a solution for Diophantine equation, i'm really not that great in math, so i tried to understand what it does as much as i can, and think of a solution for it.
Here's what i got to :
def test(x):
for a in range(1,150):
for b in range(1,150):
for c in range(1,150):
y = 6*a+9*b+20*c
if y == x:
print "this --> " , a, b, c
break
else : ##this to see how close i was to the number
if y - x < 3:
print a, b, c , y
The assignment states that there's a solution for 50, 51, 52, 53, 54, and 55, but unfortunately the script only gets the solution for 50, 53 and 55.
I'd be very grateful if someone explained what's wrong in my code, or if i'm not understanding Diophantine equation at all, please tell me what is it all about and how to find a solution for it, since i cant get the assignment's explanation into my head.
Thanks.
The assignment says:
To determine if it is possible to
buy exactly n McNuggets, one has to solve a Diophantine equation: find non-negative integer
values of a, b, and c, such that
6a + 9b + 20c = n.
It seems that you have to include zero in the ranges of your function. That way, you can find solutions for all the numbers you need.
A solution to
6*a+9*b+20*c = 51
with integers a, b, c must have at least one of the integers 0 or negative. Some solutions are
6*7 + 9*1 + 20*0 = 51
6*0 + 9*(-1) + 20*3 = 51
Depending on the constraints in the assignment, you need to include 0 or even negative numbers among the possible coefficients.
A solution for 51 is 5*9 + 1*6.
Hint: where's the 20? What does this mean for it's coefficient?
A solution for 54 is 3*20 + (-1)*6. You figure out the rest.
For a start, you can usefully exploit bounds analysis. Given
6a + 9b + 20c = n
0 <= a
0 <= b
0 <= c
we can systematically set pairs of {a, b, c} to 0 to infer the upper bound for the remaining variable. This gives us
a <= floor(n / 6)
b <= floor(n / 9)
c <= floor(n / 20)
Moreover, if you pick a strategy (e.g., assign c then b then a), you can tighten the upper bounds further, for instance:
b <= floor((n - 20c) / 9)
Also, the last variable to be assigned must be a function of the other variables: you don't need to search for that.
You can start your range for a,b,c from 0 to 150.
Actually even I am a beginner and have started out from MIt 6.00 only.
ON reading their problem ,I think 150 it the limit to the largest number which cannot be possible to take.
This is a solution in Perl. rather a hack by using Regex.
Following this blog post to solve algebraic equations using regex.
we can use the following script for 3x + 2y + 5z = 40
#!/usr/bin/perl
$_ = 'o' x 40;
$a = 'o' x 3;
$b = 'o' x 2;
$c = 'o' x 5;
$_ =~ /^((?:$a)+)((?:$b)+)((?:$c)+)$/;
print "x = ", length($1)/length($a), "\n";
print "y = ", length($2)/length($b), "\n";
print "z = ", length($3)/length($c), "\n";
output: x=11, y = 1, z = 1
the famous Oldest plays the piano puzzle ends up as a 3 variable equation
This method applies for a condition that the variables are actually positive and the constant is positive.
Check this one I adapted from yours. It seems to fixed your problem:
variables=range(0,10)
exams=range(51,56)
for total in exams:
for a in variables:
for b in variables:
for c in variables:
if total==4*a+6*b+20*c:
print a, 'four pieces', b, 'six pieces','and', c ,'twenty pieces', 'for a total of', total
The break function will only break out of the closest loop. The code below uses an indicator to break out of each loop.
n = 1 # n starting from 1
count = 0 # Count + 1 everytime we find a possible value.
# Reset = 0 after a non-possible value.
notPossibleValue = ()
while True:
ind = 0 # become 1 if int solutions were found
for c in range (0,n/20+1):
if ind == 1: break
for b in range (0,n/9+1):
if ind == 1: break
for a in range (0, n/6+1):
if (n-20*c) == (b*9+a*6):
count += 1
ind = 1
# print 'n=', n, a,b,c, 'count', count
break # Break out of "a" loop
if ind == 0:
count = 0
notPossibleValue += (n,)
# print notPossibleValue, 'count', count
if count == 6:
print 'The largest number of McNuggets that cannot be bought in exact quantity is', notPossibleValue[-1]
break
n += 1
n=1
a=0
b=0
c=0
mcnugget = []
for i in range (n,100):
for a in range (0,20):
if 6*a + 9* b +20*c ==i:
mcnugget.append(i)
break
else:
for b in range (0,12):
if 6*a + 9* b +20*c ==i:
mcnugget.append(i)
break
else:
for c in range(0,5):
if 6*a + 9* b +20*c ==i:
mcnugget.append(i)
break
else:
if i>8:
if mcnugget[-1]==mcnugget[-2]+1==mcnugget[-3]+2==mcnugget[-4]+3==mcnugget[-5]+4==mcnugget[-6]+5 and mcnugget[-6]>0 :
break
mcnugget = set (mcnugget)
mcnugget = list (mcnugget)
count = 0
for z in mcnugget:
count += 1
if mcnugget [count]==mcnugget [count-1]+1==mcnugget [count-2]+2==mcnugget [count-3]+3==mcnugget [count-4]+4==mcnugget[count-5]+5:
biggestN= mcnugget[count-6]
break
#print (mcnugget)
biggestN = str(biggestN)
print ('Largest number of McNuggets that cannot be bought in exact quantity: <'+ biggestN +'>')