Binary to Decimal Number Converter - python

Today my professor asked us to do a binary converter using python, and I did it quickly with my friend assigning a variable to the length and decreasing it by 1 in the for loop. And then we decided to do it the opposite way.
We tried to do it converting the number into a list, reversing the list, using the index position to match the required exponent number. But we found 2 main problems with that code:
1.The exponent will never be able to be bigger than 1, because it's not in the list.
2.The number 1 and 0 are going to repeat a lot of times in the list, so there's gonna be a problem when we try to access the index value.
Is there any way to fix it or we should just stick to the other method? Here's the code so you can take a look:
num = input ('Insert the binary number: ')
res = [int(x) for x in num]
res.reverse()
length = len(res) + 1
counter = 0
for x in range (0, length):
if res[x] == 1:
counter += res[x]**res.index(x)
elif res[x] == 0:
pass
else:
print ('The number is not binary')
break
print (f'Your number in decimal is : {counter}')

Your method is fine. Two errors in your code:
Do not add 1 to the length as it is already the correct value. If you have a, say, 8 digit binary number the range should be from 0 to 7.
You should simply add 2**x to the counter when the digit is 1. I don't know why you tried to use the .index()
Here is a working version:
num = input ('Insert the binary number: ')
res = [int(x) for x in num]
res.reverse()
length = len(res)
counter = 0
for x in range(length):
if res[x] == 1:
counter += 2 ** x
elif res[x] == 0:
pass
else:
print ('The number is not binary')
break
print (f'Your number in binary is : {counter}')
...or a one-liner just for some Python fun:
print(sum(int(x) * 2**i for i, x in enumerate(reversed(num))))

For determining the correct value of the exponent you can use enumerated. Also, there is no point in converting the each digit to an integer, you can just compare the string.
num = input('Insert the binary number: ')
result = 0
for i, digit in enumerate(reversed(num)):
if digit == "1":
result += 2 ** i
elif digit != "0":
print('The number is not binary')
break
else:
print(f'Your number in decimal is : {result}')

Just a little fix and your program will work. Modified length = len(res), added enumerate to find index, and changed the counter formula.
num = input ('Insert the binary number: ')
res = [int(x) for x in num]
res.reverse()
length = len(res)
counter = 0
for index,x in enumerate(range(length)):
if res[x] == 1:
counter += res[x]* 2**index
elif res[x] == 0:
pass
else:
print ('The number is not binary')
break
print (f'Your number in decimal is : {counter}')

Related

Printing largest number from a given input

I created a code to print the largest number from a given input(string) but it is only valid for inputs containing distinct digits and gives an error 'string index out of range' when the input consists of repetitive digits. Why so?
Note: "The concept of list cannot be used"
My code is as follows:
def largest_num(num):
nums = ""
length = len(num)
while length:
max_num = num[0]
for i in num:
if i > max_num:
max_num = i
num = num.replace(max_num,"")
nums = nums + max_num
length-=1
return nums
x = input("Entered number: ")
a = largest_num(x)
print(a)
Output:
Output of above code
#Husnian Mehdi - the original code has error in the line - "num.replace(max_num, ""). You could put print statement after that to see what's happening when you input a number with duplicated digits: such as '454'. I also change some variable names to make it more descriptive. [Hint: that num.replace() statement has removed both duplicated digits....!]
def largest_num(num):
ans = ""
size = len(num)
while size:
max_digit = num[0]
for n in num[1:]:
if n > max_digit:
max_digit = n
ans = ans + max_digit
num = num.replace(max_digit, "")
print(f' num is: {num} now ...')
size -=1
print(f' len: {size}')
return ans
x = input("Entered number: ")
It's more straightforward to take the advantage of the fact that the input is a string, and string can be sorted easily. Please try the code next:
from functools import cmp_to_key
def largestNum(num):
num = [str(n) for n in num]
num.sort(key=cmp_to_key(lambda b, a: ((a+b)>(b+a))-((a+b)<(b+a)) ))
return ''.join(num).lstrip('0') or '0'
x = input("Entered number: ")
#a = largest_num(x)
print(largestNum(x))
Demo:
>>>Entered number: 321895
985321
>>>Entered number: 10957
97510
>>>Entered number: 4576889
9887654
>>>
Or simply do the sorting directly (you can convert this to function):
1. num = list(num). # num is string input of number
2. num = num.sort(reverse=True)
3. largest = int(‘’.join(num)) # answer

Counting divisors to detect prime number in python 3.7.4

I tried to write a code to detect prime numbers myself and accidentally, I found this which is working just fine:
def prime_number_check(inp):
setp = [ ]
res = [ ]
count = 0
for x in range(1, inp):
setp.append(x)
print(setp) #just to control the set
for y in setp: #set of dividers
if inp % setp[y-1] == 0:
res.append(setp[y-1])
else:
continue
print(res) #just to control the set
for z in res:
count += 1
if count > 1:
print(inp, "is not a prime number!")
else:
print(inp, "is a prime number!")
I tried to divide the input number, which will be checked whether it is prime or not, to the numbers smaller than itself and wanted to detect the result set whether it has float results or int results, then remove float results with res.remove(), then if there is int result other than 1, print not a prime, otherwise print prime, but I failed; instead found this code which counts divisors.
Could you help me to find out how can I make float/int check in a list and return a result? I tried bool(), and isinstance() but always got an error about iterability.
def prime(*arg):
if num<2:
return 0
else:
t=0
for x in range(2,num+1):
k=0
for y in range(1,x+1):
if x%y == 0:
k += 1
if k == 2:
t += 1
return t
Here I actually not considered 0 and 1 as prime . I hope you got my simple code in python.

Factors of a number using Python recursive function

I've got an assignment which requires me to use a Python recursive function to output the factors of a user inputted number in the form of below:
Enter an integer: 6 <-- user input
The factors of 6 are:
1
2
3
6
I feel like a bit lost now and have tried doing everything myself for the past 2 hours but simply cannot get there. I'd rather be pushed in the right direction if possible than shown where my code needs to be changed as I'd like to learn
Below is my code:
def NumFactors(x):
for i in range(1, x + 1):
if x == 1:
return 1
if x % i == 0:
return i
return NumFactors(x-1)
x = int(input('Enter an integer: '))
print('The factors of', x, 'are: ', NumFactors(x))
In your code the problem is the for loop inside the method. The loop starts from one and goes to the first if condition and everything terminates there. That is why it only prints 1 as the output this is a slightly modified version of your own code. This should help. If you have any queries feel free to ask.
def factors(x):
if x == 1:
print(1 ,end =" ")
elif num % x == 0:
factors(x-1)
print(x, end =" ")
else:
factors(x-1)
x = num = int(input('Enter an integer: '))
print('The factors of', x, 'are: ',end =" ")
factors(x)
Since this question is almost 3 years old, I'll just give the answer rather than the requested push in the right direction:
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)
Your recursion is passing down x-1 which will not give you the right value. For example: the number of factors in 6 cannot be obtained from the number of factors in 5.
I'm assuming that you are not looking for the number of prime factors but only the factors that correspond to the multiplication of two numbers.
This would not normally require recursion so you can decide on any F(n) = F(n-1) pattern. For example, you could use the current factor as a starting point for finding the next one:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if F == N : return count
return count + NumFactors(N,F+1)
You could also optimize this to count two factors at a time up to the square root of N and greatly reduce the number of recursions:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if N != F : count = count * 2
if F*F >= N : return count
return count + NumFactors(N,F+1)

finding emrips with python, what am i doing wrong?

An Emirp is a prime number whose reversal is also a prime. For
example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps.
Write a program that prints out the first N emirps, five on each line.
Calculate the first N emirp (prime, spelled backwards) numbers, where
N is a positive number that the user provides as input.
Implementation Details
You are required to make use of 2 functions (which you must write).
isPrime(value) # Returns true if value is a prime number. reverse
(value) # Returns the reverse of the value (i.e. if value is 35,
returns 53). You should use these functions in conjunction with logic
in your main part of the program, to perform the computation of N
emirps and print them out according to the screenshot below.
The general outline for your program would be as follows:
Step 1: Ask user for positive number (input validation) Step 2:
Initialize a variable Test to 2 Step 3: While # emirps found is less
than the input:
Call isPrime with Test, and call it again with reverse(Test).
If both are prime, print and increment number of emirps found. Test++ Hint - to reverse the number, turn it into a string and then
reverse the string. Then turn it back into an int!
MY CODE:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
count = 0
while(test < value):
if( value % test == 0):
count+=count
test+=test
if(count == 0):
return 1
else:
return 0
def reverse(value):
reverse = 0
while(value > 0):
reverse = reverse * 10 + (value % 10)
value = value / 10
return reverse
n = float(input("Please enter a positive number: "))
while(count < n):
i+=i;
if(isPrime(i)):
if(isPrime(reverse(i))):
print("i" + "\n")
count+=count
if((count % (5)) == 0 ):
print("\n")
where are the mistakes?
UPDATED CODE BUT STILL NOT RUNNING:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
def reverse(value):
return int(str(value)[::-1])
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
There are a lot of issues with your code. I altered the function isPrime. There is among other no need for count here and if you want to increment test by 1 every loop use test +=1:
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
return 1
There is an easy way to reverse digits by making value a string in reversed order and to convert this into an integer:
def reverse(value):
return int(str(value)[::-1])
You among other have to assign the input to i. n in your code is a constant 5. You have to increment i by one in any condition and increment the count by one if i is an emirp only:
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
def emrip_no(num):
i=0
j=0
for i in range(1,num+1):
a=0
for j in range(1,i+1):
if(i%j==0):
a+=1
if(a==2):
print("Number is a prime number")
k=0
l=0
rv=0
while(num!=0):
r=num%10
rv=(rv*10)+r
num=num//10
print("It's reverse is: ",rv)
for k in range(1,rv+1):
b=0
for l in range(1,k+1):
if(k%l==0):
b+=1
if(b==2):
print("It's reverse is also a prime number")
else:
print("It's reverse is not a prime number")
n=int(input("Enter a number: "))
emrip_no(n)

Python3.4 - math with index numbers

My objective was to use the index of a list to do addition/subtraction with. Where by I turned the even index positive, and the odd index negative.
EX1: 1234508 Should be answered by a 0: 1-2+3-4+5-0+8 = 11, then the while loops it again and I get 1-2+1 = 0
Ex2: 12345 Should be answered by a 3: 1-2+3-5 = 3, so it shouldn't go through the loop again.
Ex3: 121 Should be answered by a 0: 1-2+1 = 0, so it shouldn't go throught he loop again.
def main():
print()
print("Program to determine if a number is evenly\ndivisible by 11")
print()
indexed = input("Enter a number: ",)
total = 0
num = 0
while num >= 10:
for item in indexed:
if num %2 == 0:
total = total + int(item)
else:
total = total - int(item)
num = num + 1
print(total)
main()
Note that this print statement above is a place holder for a if statement which is inactive on my code, but was printing as large bold print here.
Let's say you have a string st whose characters are all digits, and that you want to have the sum of these digits. You then define the following function
def sd(st):
return sum(int(d) for d in st)
that we can test in the interpreter
In [30]: sd('10101010101010101010')
Out[30]: 10
In [31]: sd('101010101010101010101')
Out[31]: 11
What you really want is to sum the odd digits and subtract the even ones, but this is equivalent to sum the odds, sum separately the evens and then take the difference, isn't it? so what you want is
step_1 = sd(odds(st)) - sd(evens(st))
How can you separate the odd digits from the even ones? Ah! no need for a function, we can use slices
step_2 = sd(st[::2]) - sd(st[1::2])
Now we want to test the slices in the interpreter
In [32]: '101010101010101010101'[::2]
Out[32]: '11111111111'
In [33]: '101010101010101010101'[1::2]
Out[33]: '0000000000'
But step_2 could be a negative number, that I don't want to manage... I'd rather use the abs builtin
step_3 = abs(sd(st[::2]) - sd(st[1::2]))
and this is exactly what you were looking for.
Eventually we can put all the above together, but we may need to iterate until the difference is less than 11 --- we'll use an infinite loop and a break statement to exit the loop when we'll have found the answer
def sd(st):
return sum(int(d) for d in st)
number = input('Give me a number: ')
trial = number
while True:
n = abs(sd(trial[::2]) - sd(trial[1::2]))
if n < 11: break
trial = str(n)
if n > 0:
...
else:
...
what exactly do you want to do with this?
evenindex = evenindex int(item)
"list" is a type, means the list type in python, so it cannot be the name of a variable. Furthermore, you have not defined this variable in your code.
I have figured out the answer to the question I asked above. As such, my answer here is in the event anyone stumbles upon my above question.
def main():
indexed = input("Enter a number: ",)
total = 0
num = 0
while num <= 10:
for item in indexed:
if num %2 == 0:
total = abs(total + int(item))
else:
total = abs(total - int(item))
num = num + 1
if total == 0:
print(indexed, "is evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
else:
print(indexed, "is not evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
input()
main()

Categories

Resources