Why aren't the values from my arrays passing though my full bit adder - python-3.x

# 8-bit-binary adder
#if you have questions about the code just ask
# arrays and funtions
Array1 = []
Array2 = []
#Input A and Validation
def vaildNumberA():
a = int(input("Enter your A value:"))
if (a < 0):
print("Please Enter A Valid Number For Input A")
elif (a > 255):
print("Please Enter A Valid Number For Input A")
else:
Array1 = [int(x) for x in list('{0:08b}'.format(a))]
#Input B and Validation
def vaildNumberB():
b = int(input("Enter your B value:"))
if (b < 0):
print("Please Enter A Valid Number For Input B")
elif (b > 255):
print("Please Enter A Valid Number For Input B")
else:
Array2 = [int(x) for x in list('{0:08b}'.format(b))]
# and gate
# AND Gate
def AND (a,b):
if (a == 1 and b == 1):
return 1
else:
return 0
# or gate
#OR Gate
def OR(a,b):
if (a == 1 or b == 1):
return 1
else:
return 0
# XOR GATEE
#XOR Gate
def XOR (a,b):
if (a == b):
return 0
else:
return 1
#carry formula
def carryformula(a,b,c,d):
return OR(AND(a,b), AND(c,d))
# this is where the calculation should be done
#formula for sum
def calculateSum(Array1,Array2):
carry = ""
sumof = []
for index, in range(len(Array1)):
list2 = Array2[index]
sec_xor_form = XOR(Array1[index],Array2[index])
sumof.append(XOR(sec_xor_form,carry))
carry = carryformula(Array1[index],Array2[index],sec_xor_form,carry)
return list(reversed(sumof))
calculateSum(Array1,Array2)
def main(Array1,Array2):
vaildNumberA()
vaildNumberB()
while True:
a = Array1
b = Array2
total = calculateSum(list(reversed(Array1)),list(reversed(Array2)))
print(total)
quit = input("if want to quit type q: ")
if quit == 'q':
break
main(Array1,Array2)
in the send it prints 0

The only problem in your code is that you need to return Array1 and Array2 from your functions and assign them inside the while true loop, once you do that the code works fine.
The updated code will be
# 8-bit-binary adder
#if you have questions about the code just ask
# arrays and funtions
Array1 = []
Array2 = []
#Input A and Validation
def vaildNumberA():
Array1 = []
a = int(input("Enter your A value:"))
if (a < 0):
print("Please Enter A Valid Number For Input A")
elif (a > 255):
print("Please Enter A Valid Number For Input A")
else:
Array1 = [int(x) for x in list('{0:08b}'.format(a))]
#Return the array
return Array1
#Input B and Validation
def vaildNumberB():
Array2 = []
b = int(input("Enter your B value:"))
if (b < 0):
print("Please Enter A Valid Number For Input B")
elif (b > 255):
print("Please Enter A Valid Number For Input B")
else:
Array2 = [int(x) for x in list('{0:08b}'.format(b))]
#Return the array
return Array2
# AND Gate
def AND (a,b):
if (a == 1 and b == 1):
return 1
else:
return 0
#OR Gate
def OR(a,b):
if (a == 1 or b == 1):
return 1
else:
return 0
#XOR Gate
def XOR (a,b):
if (a == b):
return 0
else:
return 1
#carry formula
def carryformula(a,b,c,d):
return OR(AND(a,b), AND(c,d))
# this is where the calculation should be done
#formula for sum
def calculateSum(Array1,Array2):
carry = ""
sumof = []
for index in range(len(Array1)):
list2 = Array2[index]
sec_xor_form = XOR(Array1[index],Array2[index])
sumof.append(XOR(sec_xor_form,carry))
carry = carryformula(Array1[index],Array2[index],sec_xor_form,carry)
return list(reversed(sumof))
#No need of a main function
while True:
#Call the function from within the while True loop
Array1 = vaildNumberA()
Array2 = vaildNumberB()
total = calculateSum(list(reversed(Array1)),list(reversed(Array2)))
print(total)
quit = input("if want to quit type q: ")
if quit == 'q':
break
And the output will look like
Enter your A value:5
Enter your B value:5
[0, 0, 0, 0, 1, 0, 1, 1]
if want to quit type q: 7
Enter your A value:9
Enter your B value:8
[0, 0, 0, 1, 0, 0, 0, 1]
....

Related

I've tried running the code but it says list index is out of range

from typing import List
# You are given an integer n, denoting the no of people who needs to be seated, and a list of m integer seats, where 0 represents a vacant seat. Find whether all people can be seated, provided that no two people can sit together
When I run this code in geeks for geeks for submission I get a error that List index is out of range.
but seems to work fine when I run it as a script.
class Solution:
def is_possible_to_get_seats(self, n: int, m: int, seats: List[int]) -> bool:
vacant_seats = 0
if len(seats) == 2:
if seats[0] or seats[1] == 1:
print(seats)
return False
else:
print(seats)
return True
else:
for x in range(len(seats)):
if x == 0:
if seats[x] == 0 and seats[x+1] == 0:
seats[x] = 1
vacant_seats += 1
elif x == len(seats)-1:
if seats[x] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
else:
if seats[x] == 0:
if seats[x+1] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
if vacant_seats < n:
return False
else:
return True
# {
# Driver Code Starts
class IntArray:
def __init__(self) -> None:
pass
def Input(self, n):
arr = [int(i) for i in input().strip().split()] # array input
return arr
def Print(self, arr):
for i in arr:
print(i, end=" ")
print()
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
m = int(input())
seats = IntArray().Input(m)
obj = Solution()
res = obj.is_possible_to_get_seats(n, m, seats)
result_val = "Yes" if res else "No"
print(result_val)
# } Driver Code Ends

How to search for the index of the number from the last of list to first?

I was checking the documentation to find the index of the number from last to first.
I could use - list.index(number, start, end). In my example, if I omit the start and end I don't get any exception. However, I get an exception when I change the start to the last index and end to the first element index i.e. 0. I am sure I am doing something wrong but I am unable to think about what is going wrong here.
def nonConstructibleChange(coins):
# o(log n) - sorting
coins.sort() # O(log n)
max_amount = sum(coins)
print(max_amount)
# range is [start, end)
if len(coins) == 0:
return 1
for change in range(1, max_amount+1):
if change == 1:
if 1 not in coins:
return 1
else:
max_limit = change - 1
while max_limit not in coins and max_limit != -1:
max_limit -=1
print(coins.index(max_limit, len(coins)-1, 0)) # throws exception
print(coins.index(max_limit)) # this works
if __name__ == '__main__':
coins = [5, 7, 1, 1, 2, 3, 22]
nonConstructibleChange(coins)
You can find the index of the last occurrence of an element by applying index function on the reversed list. In your case this would be:
print(coins[::-1].index(max_limit))
def nonConstructibleChange(coins):
# o(log n) - sorting
coins.sort() # O(log n)
max_amount = sum(coins)
num = None
#print(coins)
#print(max_amount)
# range is [start, end)
if len(coins) == 0:
return 1
for change in range(1, max_amount+1):
if change == 1:
if 1 not in coins:
return 1
else:
max_limit = change
while max_limit not in coins and max_limit != -1:
max_limit -=1
right_index = coins.index(max_limit)
while 1:
try:
# the last index is not included therefore len(coins)
right_index = coins.index(max_limit, right_index +1 , len(coins))
except ValueError:
# print(f'final right_index = {right_index}')
break
print(f'right_index = {right_index}')
print(f'change = {change}')
print(f'max_limit = {max_limit}')
num = change
for idx in reversed(range(right_index + 1)):
if coins[idx] > num:
#print(f'coins[idx] = {coins[idx]} and num = {num}')
continue
#print(f'idx = {idx}')
num = num - coins[idx]
#print(f'num = {num}')
if (num in coins[0:idx-1] or num == 0) and idx != 0:
#print(f'Setting num = {num}')
num = 0
break
if num != 0:
return change
return max_amount + 1
if __name__ == '__main__':
coins = [5, 7, 1, 1, 2, 3, 22]
#coins = [1, 1, 1, 1, 1]
print(nonConstructibleChange(coins))

Appending results from a list to a string

Heavy python beginner here. I want to create a simple function for a PIN guessing game that receives two 4-digit lists ( [guess], [answer] ) and returns a string with 4 letters stating how close I am to guessing the correct [answer] sequence (eg. Higher, True, Lower, Higher)
However, I get a new list for each string:
def checkNumbers(guess,right):
for n in range(4):
result = []
if guess[n] == right[n]:
result.append("T") #true
elif guess[n] < right[n]:
result.append("H") #higher
elif guess[n] > right[n]:
result.append("L") #lower
else:
result.append("F") #false
print (result)
return
checkNumbers([1,2,3,5],[2,2,1,6])
The result should look like this:
checkNumbers([1,2,3,4], [2, 2, 1 , 6]) #call function with ([guess], [answer])
'HTLH' #returns a string stating how accurate [guess] is to [answer] list
Result looks like this however:
checkNumbers([1,2,3,5],[2,2,1,6])
['H']
['T']
['L']
['H']
Thanks very much in advance for any help I could get.
you can use string instead of list or "".join()
def checkNumbers(guess, right):
result = ""
for n in range(4):
if guess[n] == right[n]:
result += "T" # true
elif guess[n] < right[n]:
result += "H" # higher
elif guess[n] > right[n]:
result += "L" # lower
else:
result += "F" # false
print(result)
but... maybe you want to use zip function
def checkNumbers(guess, right):
result = ""
for g, r in zip(guess, right):
if g == r:
result += "T" # true
elif g < r:
result += "H" # higher
elif g > r:
result += "L" # lower
else:
result += "F" # false
print(result)
Funny bonus here:
def checkNumbers(guess, right):
print("".join("THL"[(g > r) + (g != r)] for g, r in zip(guess, right)))
I don't get why you need else part...
Initiate the list and print the result outside of the loop:
def checkNumbers(guess, right):
result = []
for n in range(4):
# do loopy stuff
print (result)
return # not strictly necessary
If you do it inside, you are creating a new list on every iteration.

Counting weighted average doesn't work properly sometimes

I've made a program that counts weighted average and required weighted value to average being equal to our preference. If I want the average be equal to 85 from (the first value in the list is the weight of next values) [[4,72,78],[3,56],[6,93]] and x value of 6 weight it does not output the right value.
def choice(x):
c = 0
Choice = True
choices = []
while Choice:
if choices == []:
if x != 0:
fill = "weight of required value"
else:
fill = "weight of next values"
else:
if x != 0:
fill = "value of wanted weighted average"
else:
fill = "value"
try:
c = input("Give {}\n" .format(fill))
except:
continue
if isinstance(c, str):
if c == "":
Choice = False
if choices == []:
choices = False
break
else:
try:
choices.append(float(c))
except:
continue
if x != 0 and len(choices) == x:
break
c = 0
return choices
def av(x):
c = 0
alist = x[:]
alist.pop(0)
for a in alist:
c += a*x[0]
return c
def average(k,args):
c = 0
n = 0
for y in range(len(args)):
for a in range(len(args)):
c += (av(args[a]))/2
for b in range(len(args)):
n += (args[b][0]*(len(args[b])-1))/2
if k == 1:
return ([float("{0:.2f}".format(c/n)),c,n])
else:
j = float("{0:.2f}".format(c/n))
print("Weighted average {} from {}" .format(j,args))
def rmark(q,args):
alist = average(1,args)
a = float("{:.2f}" .format((((q[1]*(alist[2]+q[0]))-alist[1])/q[0])))
print("To get weighted average {}, u have to add the value equal to {} of weight {}" .format(q[1],a,q[0]))
# return a
Continue = True
list_choices = []
while Continue:
x = 0
x = choice(0)
if isinstance(x, list):
list_choices.append(x)
elif x == False:
break
print(list_choices)
rmark(choice(2),list_choices)
average(0,list_choices)
Let me break it down for you.
av function is reducing the size of your lists (x1, x2 and x3) to 1 by popping (alist.pop(0)) one element.
Hence, value of len(x1)-1 is 0, which means value of all multipliers in the denominator of (av(x1) + av(x2) + av(x3))/((x1[0]*(len(x1)-1)) + (x2[0]*(len(x2)-1)) + (x3[0]*(len(x3)-1))) is 0. Thus, the error divide by zero.

Recursively calling a second function inside a function

I have this code that counts up -3, -2, -1. I have also written another that counts down 3, 2, 1. If the condition is true for another after an input, the program should stop. For Example, The input i enter -3 for negatives it gives -3, -2, -1, if i enter positive number like 3, the result should be 3, 2, 1 in a single combined code.
I have tried to put a function into an if statement of the first function but fails with "NameError: name 'countdown' is not defined" for count down but count up works.
print('+=+=+=+=+=+=+=+=+=+=+=+=+ F1')
#count up
def countup(n):
if (n >= 0):
print('Hello')
if n==0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
else:
print(n)
nth = n + 1
countup(nth)
result = int(input('Enter Number: '))
countup(result)
Have you tried replacing the second else with elif? And fixing the indenting? The resulting code should be this:
print('+=+=+=+=+=+=+=+=+=+=+=+=+ F1')
#count up
def countup(n):
if (n >= 0):
print('Hello')
if n==0:
print('Blastoff!')
elif (condition):
print(n)
countdown(n-1)
else:
print(n)
nth = n + 1
countup(nth)
result = int(input('Enter Number: '))
countup(result)
I solve the problem by doing this code below:
def countup(n):
if (n >= 0):
print('Blastoff 1')
else:
print(n)
nth = n + 1
return countup(nth);
def zero(n):
if (n==0):
print('You have erntered 0 program exiting')
exit()
def countdown(n):
if (n <= 0):
print('explode 2')
else:
print(n)
nth = n - 1
return (countdown(nth))
num = int(input("Enter number: "));
if (num <= 0):
print(countup(num))
elif num == 0:
print(zero(num))
else:
print(countdown(num))
The output is either negative or positive, regardless of what integer you fuse in

Resources