I'm trying to create a logic gate simulation program in python so that a user can choose the type of logic gate they want to simulate. Once chosen, they can then enter the inputs and the program should return the value of the output from the chosen logic gate to the user.
This is what I have so far:
print ("Logic Gate Simulation")
def AND (a,b):
if a == 1 and b == 1:
return 1
else:
return 0
def NAND (a,b):
if a == 1 and b == 1:
return 0
else:
return 1
def OR(a,b):
if a == 1:
return 1
elif b == 1:
return 1
else:
return 0
def NOR (a,b):
if a != b:
return 1
else:
return 1
def Main():
question = input("what type of gate do you want to simulate - OR, AND or NAND? ")
if question == 'AND':
a = input("enter value for input 1")
b = input("enter value for input 2")
x= AND(a,b)
print (x)
else:
print ("")
Main()
When I run the program and enter AND, inputs 1 and 1 it still returns 0 and I cant see why.
this works:
def AND (a,b):
a=int(a)
b=int(b)
if a == 1 and b == 1:
return 1
else:
return 0
you have to tell python that a and b are integers - (there are better ways of doing that than the method shown)
This is my version of the code (I had to this for homework for AS Level, this may help you!) :
print("Logic Gate Calculator")
def AND(a, b): # AND Gate
a = int(a)
b = int(b)
if a == 1 and b == 1: # AND Gate logic
return 1
else:
return 0
def NAND(a, b): # NAND Gate
a = int(a)
b = int(b)
if a == 1 and b == 1: # NAND Gate logic
return 0
elif a == 1 and b == 0:
return 0
elif a == 0 and b == 1:
return 0
else:
return 1
def OR(a, b): # OR Gate
a = int(a)
b = int(b)
if a == 1: # OR Gate Logic
return 1
elif b == 1:
return 1
else:
return 0
def NOR(a, b): # NOR Gate
a = int(a)
b = int(b)
if a == 1 and b == 0: # NOR Gate Logic
return 1
elif a == 0 and b == 1:
return 1
elif a == 0 and b == 0:
return 1
else:
return 0
def XOR(a, b): # XOR Gate
a = int(a)
b = int(b)
if a == 1 and b == 0: # XOR Gate Logic
return 1
elif a == 1 and b == 1:
return 1
else:
return 0
def main(): # The main program
run = True
while run: # While loop
question = input("What type of gate do you want to use OR, AND, NOR, or NAND or (Q)uit") # Logic Gate chooser
if question == "AND" or question == "and" or question == "And": # If the user selects AND
a = input("Enter value for input 1 (1 or 0):") # Getting the Logic Gate's 1st input
b = input("Enter value for input 2 (1 or 0):") # Getting the Logic Gate's 2nd input
x = AND(a, b) # Calling the AND Function
print("The output will be:", x) # Output result
elif question == "OR" or question == "or" or question == "Or": # If the user selects OR
a = input("Enter value for input 1 (1 or 0):") # Getting the Logic Gate's 1st input
b = input("Enter value for input 2 (1 or 0):") # Getting the Logic Gate's 2nd input
x = OR(a, b) # Calling the OR Function
print("The output will be:", x) # Output result
elif question == "NOR" or question == "nor" or question == "Nor": # If the user selects NOR
a = input("Enter value for input 1 (1 or 0):") # Getting the Logic Gate's 1st input
b = input("Enter value for input 2 (1 or 0):") # Getting the Logic Gate's 2nd input
x = NOR(a, b) # Calling the NOR function
print("The output will be:", x) # Output result
elif question == "NAND" or question == "nand" or question == "Nand": # If the user selects NAND
a = input("Enter value for input 1 (1 or 0):") # Getting the Logic Gate's 1st input
b = input("Enter value for input 2 (1 or 0):") # Getting the Logic Gate's 2nd input
x = NAND(a, b) # Calling the NAND function
print("The output will be:", x) # Output result
elif question == "XOR" or question == "xor" or question == "Xor": # If the user selects XOR
a = input("Enter value for input 1 (1 or 0):") # Getting the Logic Gate's 1st input
b = input("Enter value for input 2 (1 or 0):") # Getting the Logic Gate's 2nd input
x = XOR(a, b) # Calling the XOR function
print("The output will be:", x) # Output result
elif question == "Q" or question == "q": # Quiting the program
run = False
else:
print("Please enter one of the shown logic gates") # Error handling
main()
a=True
b=True
output=a and b
print (output)
a=True
b=False
output=a and b
print (output)
Please try this
It works. Use
if a == 1:
if b == 1:
return 1
else
return 0
Related
I have a QtableView with data from a file. I added 3 columns with checkboxes, but now I need to know what checkbox is clicked (Row, column, data). This is working for the cell itself but when clicking the checkbox it gives the latest data or if no data it's -1 and None.
I tried to remove a lot of code so I hope this is not to much or to less.
self.model = TableModel([headers, newRows])
self.proxy_model.setSourceModel(self.model)
self.tableView.setModel(self.proxy_model)
self.tableView.clicked.connect(self.cellClicked)
def cellClicked(self):
try:
index = self.tableView.selectionModel().currentIndex()
row = index.row()
col = index.column()
data = index.data()
# print(index.sibling(row,col).data())
if isinstance(data, QtWidgets.QCheckBox):
print(f'Child: {index.child.row()}')
data = data.text()
print(data.isChecked())
print(f'Row:\t{row}\nColumn:\t{col}\nData:\t{data}\n')
except Exception as e:
print(e)
class TableModel(QAbstractTableModel):
def __init__(self, data):
super().__init__()
self.checks = {}
self.headers = data[0]
self.rows = data[1]
def data(self, index, role):
try:
if role == Qt.ItemDataRole.DisplayRole or role == Qt.ItemDataRole.EditRole:
return self.rows[index.row()][index.column()]
elif role == Qt.ItemDataRole.CheckStateRole and (index.column() == 0 or index.column() == 6 or index.column() == 7):
return self.checkState(QPersistentModelIndex(index))
def setData(self, index, value, role = Qt.ItemDataRole.EditRole):
if value is not None and role == Qt.ItemDataRole.EditRole:
self.rows[index.row()][index.column()] = value
# self.dataChanged.emit(index, index)
return True
elif not index.isValid():
return False
elif role == Qt.ItemDataRole.CheckStateRole:
self.checks[QPersistentModelIndex(index)] = value
return True
return False
def checkState(self, index):
if index in self.checks.keys():
return self.checks[index]
else:
return Qt.CheckState.Unchecked
def flags(self, index):
col = index.column()
if col == 0 or col == 6 or col == 7:
return Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsEditable | Qt.ItemFlag.ItemIsUserCheckable
else:
return Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEditable
I'm getting an error on line 3 "TypeError: 'int' object is not iterable," and its been bothering me. Any advice/fixes appreciated.
Example test: collatz_counts(4) → 3 # 4 -> 2 -> 1 (3 steps)
Code I have:
def collatz_counts(x):
num = 0
for i in (x):
if i == 1:
num += 1
return num
elif i % 2 == 0:
num(i) / 2
num += 1
num.append(i)
else:
num = (i*2) + 3
num += 1
num.append(i)
return num
This can be solved recursively:
def collatz_length(n):
if n == 1:
return 1
return 1 + collatz_length(3*n+1 if n%2 else n//2)
Which lends itself to be memoized if you are going to be calling for a range of numbers, e.g. in Py3
import functools as ft
#ft.lru_cache(maxsize=None)
def collatz_length(n):
if n == 1:
return 1
return 1 + collatz_length(3*n+1 if n%2 else n//2)
Which will run through the first million collatz sequences in about 2.31s vs about 28.6s for the iterative solution.
Use a while loop. Just modify x in place until you get to 1 and keep track of the number of steps each time you run a cycle.
def collatz_counts(x):
steps = 0
while x != 1:
if x % 2:
x = x * 3 + 1
else:
x = x // 2
steps += 1
return steps
Ok so I'm trying to make a working napier numeral calculator. I have gone through most of the steps I need to make it work. I need 2 more steps the function and converting it back to napier numbers. Currently I'm stuck on getting the functions to work. It just seems to skip that step. From what I can tell it should work and not be skipped. Could anyone tell me if I missed a step in the process of making the function.
def main():
response = 'y'
while response == 'y' or response == 'Y':
nap1 = getNapier()
num1 = napToInt(nap1)
print(num1)
nap2 = getNapier()
num2 = napToInt(nap2)
print(num1, num2)
operator = getOperator
result = doMath(num1, num2, operator)
response = input("Try another[y/n]")
def doMath(num1, num2, operator):
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "*":
answer = num1 * num2
else:
if operator == "/":
answer = num1 / num2
return doMath
def getOperator():
op = input("Enter operator: ")
while op not in "+-*/":
op = input("Error!!!! Enter operator: ")
return op
def napToInt(n):
result = 0
for ch in n:
result += 2 ** (ord(ch) - ord('a'))
return result
def getNapier():
nap = input("Enter Napier number: ")
while not nap.isalpha():
nap = input("Error!!! Enter Napier number: ")
return nap
main()
this is the result I get as you can see it gets the napier numbers and just stops
Enter Napier number: asdf
262185
Enter Napier number: adsf
262185 262185
Try another[y/n]
your line operator = getOperator should be operator = getOperator()
Without thinking in C# I tried to compare three objects. It failed, and explained why [since (typeof("A == B") == bool) and (typeof(C) != bool) it was an invalid comparison]. Do any languages support short circuiting logic like this?
There are several languages that let you do multiple conditionals like this.
But the first I could think of was Python
Example:
a = 5
b = 5
c = 5
if(a == b == c):
print "yes"
else:
print "no"
Will print "yes" in the console.
It works with other types as well, like this:
a = ["A",1]
b = ["A",1]
c = ["A",1]
d = ["A",1]
if(a == b == c == d):
print "YES"
else:
print "NO"
Now the reason for C# (And other C like languages) doesn't support this is that they evaluate comparison expressions down to a true / false, so what your compiler sees when you do (5 == 5 == 5) is ((5 == 5) == 5) which yields: (true == 5) which invalid since you cannot compare a Boolean to an integer, you could actually write (a == b == c) if c is a Boolean, so (5 == 5 == true) would work.
I'm trying to sum all numbers from 1 to 1000 that are either divisible by 3 or 5.
The first attempt is straight forward:
ans1 = 0
for x in 3:999
ans1 += x % 3 == 0 || x % 5 == 0 ? x : 0
end
When I try the same approach using function chaining, it fails to return the answer I expect, it instead returns 0.
ans2 = [3:999] |> x -> x % 3 == 0 || x % 5 == 0 ? x : 0 |> sum
I believe the problem is the center function, since the code below prints all values within the range of 3 to 999. So i know there is no problem with iteration.
[3:999] |> x -> println(x)
Could anyone please help me.
I discovered the reason was because I did not understand the type being parsed. Here is an example:
[3:999] |> println(typeof(x)) # Array{Int64,1}
Meaning the value being parsed is an array of integer64. So evaluating the following:
[1:999] % 3 == 0 # false
So my answer was to instead use the filter function, here is an example:
ans3 = sum(filter(x -> x % 3 == 0 || x % 5 == 0,[1:999]))
The final answer using function chaining is:
ans4 = [1:999] |> x -> filter(y -> y % 3 == 0 || y % 5 == 0,x) |> sum
Which evaluates to the expected answer.