Sum binary numbers using selective structures and loops? PYTHON - python

I need to sum 2 binary numbers (max len 8 and min 1) using only selective structures (if, elif, else) and loops (for, while).
You need to know in the binary sum:
0 + 1 = 1
1 + 0 = 1
1 + 1 = 0 (with carry 1)
The result must be the sum of these two numbers.
Also, show the partial results that are generated by adding two digits and carrying
I know you could easily do this, but the idea is use only selective structure and loops.
a = input("first binary: ")
b = input("second binary: ")
c = bin(int(a,2) + int(b,2))
OUTPUT example:
sum:
11001011
10001011
=========
101010110
Partial results:
digit = 0 Carry = 1
digit = 1 Carry = 1
digit = 1 Carry = 0
digit = 0 Carry = 1
digit = 1 Carry = 0
digit = 0 Carry = 0
digit = 1 Carry = 0
digit = 0 Carry = 1
This question is different to the others made, because none of the others answer just using selective and repetitive structures

If you are allowed to use slicing, you can do this:
num1 = '11001011' # you can replace these with input() calls
num2 = '10001011'
# reverse the strings as we will be doing the operations from the left, otherwise you will need to pass reversed strings in the for loop iterator
num1 = num1[::-1]
num2 = num2[::-1]
# to tackle uneven lengths you can pad with 0s
if len(num2)>len(num1):
padding = len(num2) - len(num1)
num1 = num1 + '0'*padding
else:
padding = len(num2) - len(num1)
num1 = num1 + '0'*padding
currentresult = ''
nextdigit = 0
# iterate over two numbers
for i, j in zip(num1,num2): # if you are not allowed to use zip, you can use two nested loops one for num1 and one for num2, and add an if condition to do the operations only when i == j
i = int(i) + nextdigit
if int(i) + int(j) == 3:
# case where current bits are 1 and 1, and carry from the last addition is 1
carry = 1
digit = 1
elif int(i)+int(j) == 2:
carry = 1
digit = 0
elif int(i)+int(j) == 1:
carry = 0
digit = 1
else:
carry = 0
digit = 0
currentresult += str(digit)
nextdigit = carry
# add next digit (if in case the carry from the last bits are 1)
if nextdigit == 1:
currentresult += str(nextdigit)
# reverse the strings as we got the result in reverse
finalresult = currentresult[::-1]
print(finalresult)

Related

Reading in a positive int and transform every digit of that number in an even-odd way

So what I need to do is read in a number and transform every digit.
add 2 to an odd digit
subtract 3 from an even digit (watch out for negative numbers!)
zero stays 0
input
14502
wanted output
31701
Current output
14504
Below is what I have for now, I can read every digit in a for loop but I don't know how to transorm them one by one.
num = int(input("Enter a number:"))
for digit in str(num):
print(digit)
if (num % 2)==0:
print(num + 2)
else:
print(num - 3)
ALSO NO IMPORTS
num = input("Enter a number:")
new_num = []
single_number = ''
for digit in num:
digit = int(digit)
if digit == 0:
new_num.append(digit)
elif (digit % 2)!=0:
digit = digit+2
new_num.append(digit)
elif (digit % 2)==0:
digit = digit-3
if digit>=0:
new_num.append(digit)
else:
digit = digit*(-1)
new_num.append(digit)
print(new_num)
# for single int instead of array
for digit in new_num:
digit = str(digit)
single_number = single_number+digit
print(single_number)
new_number is array of digits single_number is the final number you want.
is your code missing the indent after the for loop? I know that may not solve the question but is that another issue with your code or just a formatting issue here on stack?
num = int(input("Enter a number:"))
for digit in str(num):
print(digit)
if (num % 2)==0:
print(num + 2)
else:
print(num - 3)
num = int(input("Enter a number:"))
print(len(str(num)))
finaloutput = []
for i in range(len(str(num))):
digit = num%10
if digit%2==0:
if digit - 3 < 0:
digit = 0
else:
digit = digit - 3
else:
digit = digit + 2
finaloutput.append(digit)
num = num //10
print(finaloutput)
string=""
for i in range(len(finaloutput)):
string = string + str(finaloutput[i])
print(string[::-1])
Might be a big scuffed but gets the job done. Substract 3 from even, add 2 to odds, and watch for zeros.
output:
Enter a number:14502
5
[0, 0, 7, 1, 3]
31700
I put it so if an even number sub 3 is less than zero it jus stays zero, bc thats how I understood it. You can easily modify the code to suit your need and in accordance with your task or whatever
Try:
num = 9876543210
l = [int(c) for c in str(s)]
l = [min(c, 7) + 2 if c % 2 else max(c, 4) - 3 if c != 0 else c for c in l]
out = int(''.join(str(c) for c in l))
Output:
>>> out
9593715130
Details:
9 -> 9 (else 12)
8 -> 5 (-3)
7 -> 9 (else 10)
6 -> 3 (-3)
5 -> 7 (+2)
4 -> 1 (-3)
3 -> 5 (+2)
2 -> 1 (else -1)
1 -> 3 (+2)
0 -> 0 (do nothing)
A simple implementation based on your solution. It can only handle integers though. And there is one case which you have not specified which is
what to do when the digit is 9? As 9 + 2 = 11 and 11 is not a digit but could well be what you want in your algorithm?
In this implementation 9 is turned to 1.
def calc_on_digits(num: str):
result: str = ""
for digit in num:
digit = int(digit)
if digit == 0:
result += "0"
continue
if digit % 2 == 0:
# in case it get negative take the absolute value
digit = abs(digit - 3)
else:
digit += 2
# in case its 9 the result would be 11 -> make it one
digit = digit % 10
result += str(digit)
return result
# string in this implementation can only contain valid integer values
print(calc_on_digits("14502"))
You cannot calculate modulo from string. Also you have to perform the comparison per digit, not for the whole number.
num = input("Enter a number:") # no need to cast to int just to transform back to str below
new_number = ""
for digit in num:
digit = int(digit)
print(digit)
if (digit % 2) = 0:
tmp = digit + 2
if tmp >= 10:
tmp = 0
else:
tmp = digit - 3
if tmp < 0:
tmp = 0
new_number += str(tmp)

How to create list of 15-digit numbers with condition?

I want to create list of random 20 15-digit numbers and each of this 15-digit numbers must follow 1 rule.
The rule is that I want this 15-digit number to be made out of 5 3-digit numbers in which first digit + second digit = third digit or if sum of first two digits is greater than 10 then third digit must be, equal to second digit of sum of first two digits. for example if first digit is 5 and second is 8, third digit must be 3 since 5 + 8 = 13.
I've written code that fills list with 15-digit numbers with the same rule, but it only works for first three digits.
import random as rd
def numchoose(start, end):
arr=[]
num=0
while num<20:
a=(rd.randint(start, end))
if int(str(a)[0]) + int(str(a)[1]) == int(str(a)[2]):
arr.append(a)
num+=1
elif int(str(a)[0]) + int(str(a)[1]) > 10 and int(str(a)[2]) == int(str(int(str(a)[0]) +
int(str(a)[1]))[1]) :
arr.append(a)
num+=1
else: continue
print(numchoose(100000000000000, 999999999999999))
How do I write this code so that entire 15-digit number is made out of 3-digit numbers that follow the stated rule and first three digits are not the only ones that follow rule?
This seems to work, but i replaced the big number with how long you want the number to be.
import random as rd
def numchoose(len):
number = ""
for i in range(int(len/3)):
a = rd.randint(0, 9)
while i == 0 and a == 0:
a = rd.randint(0, 9)
b = rd.randint(0, 9)
c = a + b
if c >= 10:
c -= 10
number += str(a) + str(b) + str(c)
return int(number)
print(numchoose(15))
Bit more compact then #eav28 but credit goes to them for answering first:
import random
def NumberGen(Length):
Number = ""
for X in range(int(Length // 3)):
A = random.randint(0, 9)
## To drop leading zero's:
## if X == 0 and A == 0:
## A = random.randint(1, 9)
B = random.randint(0, 9)
C = A + B
if C > 9:
C -= 10
Number += str(A) + str(B) + str(C)
return Number
print(NumberGen(15))
I hope this answers your question

Appending to arrays in python

I am new to python and trying to append characters of a card number to two different arrays. 4003600000000014 every other digit, starting with the number’s second-to-last digit so the first digit is 1(that is left of the 4) and by jumping one number going all the way to the 0. After that, numbers that did NOT appended to the first array (mbt) should be appended to the 2nd array(normal).
mbt should be like = 4 0 6 0 0 0 0 1
normal should be like = 0 3 0 0 0 0 0 4
(two arrays combined will be again equal to 4003600000000014)
import math
def digitnumber(n):
if n > 0:
digits = int(math.log10(n)) + 1
return digits
def isvalid(n, mbt=[], normal=[]):
cardnumber = 4003600000000014
dnumber = digitnumber(4003600000000014)
n = dnumber - 1,
mbt = []
while 1 <= n < dnumber:
x = int(cardnumber / pow(10, n) % 10)
mbt.append(x)
n -= 2
n = dnumber - 2
normal = []
while 1 <= n < dnumber:
x = int(cardnumber / pow(10, n) % 10)
normal.append(x)
n -= 2
def main():
mbt = []
normal = []
isvalid(4003600000000014, mbt=[], normal=[])
print(len(mbt))
main()
From what I understand you are trying to slice number to get individual digits.
You can find more information on slicing in Python:
Understanding slice notation
Here's a solution using python slicing to the problem. The output arrays can be reversed as needed.
def isvalid(n):
string_num = str(n)
mbt = [int(x) for x in string_num[1::2]]
normal = [int(x) for x in string_num[0::2]]
return mbt, normal
def main():
mbt, normal = isvalid(378282246310005)
print(len(mbt))
main()
Assuming that your input is an integer and you expect 2 lists of integers as output:
x = 4003600000000014
x = list(str(x))
a = list(map(int, x[1::2]))
b = list(map(int, x[0::2]))
print(a)
print(b)
[0, 3, 0, 0, 0, 0, 0, 4]
[4, 0, 6, 0, 0, 0, 0, 1]
You can use this function:
def split(num):
num = [n for n in str(num)]
num1 = []
num2 = []
for n in range(len(num)//2): # Move all element from num to num1 and num2. Since we are moving elements from 1 list to 2 lists, divide by two to distribute evenly. If the number of elements in num is odd, the // will get get rid of the decimal part
num1.append(num.pop()) # Removes last element from num and adds it to num1
num2.append(num.pop()) # Removes last element from num and adds it to num2
if num: # If there is still an element left (as in, the number of elements in num was odd to begin with):
num1.append(num.pop()) # Move that element to num1
return ' '.join(reversed(num1)),' '.join(reversed(num2))
print(split(4003600000000014))
Output:
('0 3 0 0 0 0 0 4', '4 0 6 0 0 0 0 1')

While loop problem.The result isn't what I expected

I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and I'm not good at English. But I have a problem with this code.
n = int(input("Fibonacci sequence (2-10): "))
a = 0
b = 1
sum = 0
count = 1
f = True
print("Fibonacci sequence up to {}: ".format(n), end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
This is the result of the code
Fibonacci sequence (2-10): 2
Fibonacci sequence up to 2: 0 1
And this is the result that I expect.
Fibonacci sequence (2-10): 1
Invalid Number!
Fibonacci sequence (2-10): 15
Invalid Number!
Fibonacci sequence (2-10): 10
Fibonacci sequence up to 10: 0 1 1 2 3 5 8 13 21 34
Looks like you just need to add an additional validation step to make sure that the input is in the desired range. This should do it.
while True:
n = int(input("Fibonacci sequence (2-10): "))
if n<2 or n>10:
print("Invalid Number!")
else:
a = 0
b = 1
sum = 0
count = 1
f = True
print("Fibonacci sequence up to {}: ".format(n), end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
break
Edit: To #Barmar's point, a loop on the outside would help avoid rerunning the code in case the input isn't within the desired range.

How can I reverse index and -1 each loop

value = input("Enter the binary value to convert to a decimal number.")
prod = 0
power = 0
ans = 0
for i in range (int(value)):
prod = ((int(value[*right most digit here*])) * ((2**power)))
ans = prod + ans
prod = 0
power + 1
else:
print (ans)
I am trying to create a binary calculator.
I believe I have the power part of the equation working as it begins with 2 ^ 0, then 2 ^ 1 for the next digit and so on. But I am having trouble getting the first part of the equation, the right most digit of the value inputted.
So let's say, 0101 was inputted. I want 1 * ( 2 ^ 0 ) in the first loop, 0 * ( 2 ^ 1) in the second loop, and so on; right to left. So with how indexing works in Python, how can I reverse index it so [4] is in the first loop, then [3] in the second loop, and so on.
Thanks for help.
However there are better options available, i am assuming you are clearing your basics. Following can be the options:
Note : You should use len(value) instead of int(value) in the loop.
# 1. When starting the loop from 0 (i.e. i=0). you can use ( len(value) - i )th index.'
for i in range (len(value)):
prod = ((int(value[len(value) - i - 1])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 2. Python also supports negative indexing, So you may run a loop from -1 to -len(value).
for i in range (-1,-len(value) - 1,-1):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 3. You can reverse the whole string in your first step and then loop from 0 to len(value)-1.
value = reversed(value)
for i in range (len(value)):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
But there are some bugs in the code (or may be lack on information). This code works only for unsigned integers. If you want it to work on signed numbers as well, you have to take 2's complement into consideration.
Below is a very simple code that works with signed numbers too (in case needed):
#convert binary string into decimal value. Works on 2's complement.
def binToDecimal(s):
neg = False
if s[0] == '1':
s = twosComp(s)
neg = True
#compute the decimal value
val = reduce(lambda x,y : int(x)*2+1 if y=='1' else int(x)*2,'0'+s)
#negate the value if the first bit is 1
return -val if neg else val
#return the 2's complement string
def twosComp(s):
s = list(s[::-1])
#take 1's complement
s = ['1' if i=='0' else '0' for i in s]
#take 2's complement
for i in range(len(s)):
if s[i] == '0':
#no carry will be generated in this case, so we break it.
s[i] = '1'
break
else:
s[i]='0'
# return 2's complement string
return ''.join(map(str,s))[::-1]
value = input("Enter the binary value to convert to a decimal number.")
power = 0
ans = 0
for i in reversed(value):
prod = int(i) * (2**power)
ans = prod + ans
power += 1
else:
print(ans)
Improved your code while keeping it as close to your code as possible. Your for loop was creating a list of 1 to whatever the value we input, that's not what you should be doing. One way of doing is, treating your input as a string (which basically is a list that can be iterated through) reverse it so you go from right to left, then do your operation on it on each value. You were trying to get the index of the location of the value input right? Why? Python is beautiful where you most likely don't need to directly tell the index of something.
value = input("Enter the binary value to convert to a decimal number.")
prod = 0
power = 0
ans = 0
for i in range(int(len(value))-1):
prod = ((int(value[-1])) * ((2**power)))
ans = prod + ans
prod = 0
power + 1
else:
print (ans)
You were doing the range of the value and not the input len so we use len() to get the length of the string that was inputted. -1 is there because the length of a string can be 3 for input 001 but if indexing 3 would be out of bounds because indexing starts at 0 not 1
Note that in Python a negative index value is accepted. Negative index means starts from the end of the list and count backwards, so I think that was the answer you were looking for.
For example if we have the list my_list=['a','b','c'] and we call my_list[-2] it will return 'b'
You have some mistakes in your code, so replace it with this:
value = input("Enter the binary value to convert to a decimal number: ")
value = int(value) # conversion from string to number
power = 0
ans = 0
while(value > 0):
lastDigit = value % 10 # last digit
value = value // 10 # cutting off last digit (for next iteration)
prod = lastDigit * (2 ** power)
ans = prod + ans
power = power + 1
print (ans)
Last digit is calculated as the remainder after division by 10 (value % 10)
and is cutting of by integer division by 10 (value // 10) - as in first grades of basic school: 27 % 10 = 7 27 // 10 = 2
Simpler way to achieve this with be to mention base as 2 with int(). For example:
>>> num = '110'
>>> int(num, 2)
6
In case you are looking for custom solution, you may create a function as:
def binary_string_to_int(binary_string):
int_num = 0
for i in binary_string:
int_num += int(i)
int_num *= 2
return int_num / 2
Sample run:
>>> binary_string_to_int('111')
7
>>> binary_string_to_int('101')
5

Categories

Resources