Add leading 0's to value until length is 8 characters long - python

For homework, we are asked to create a function that takes a binary input, increments the value by 1, and then displays the binary value of the new number. The output value must be an 8-bit string (8 characters long).
The following code returns the correct value, but I do not know how to add the leading zeros to the value.
def numToBinary(n):
if n == 0:
return ''
elif isOdd(n):
return numToBinary(n // 2) + '1'
else:
return numToBinary(n // 2) + '0'
def binaryToNum(s):
if s == '':
return 0
elif int(s[0]) == 0:
return 0 + binaryToNum(s[1:])
elif int(s[0]) == 1:
return 2**(len(s) - 1) + binaryToNum(s[1:])
def increment(s):
binToNum = binaryToNum(s) + 1
numToBin = numToBinary(binToNum)
return numToBin
A hint given to solve this problem was: "Consider how could you use the
function len() and string multiplication with * to make sure that the output has enough leading zeros?"
Could someone please point me in the right direction? Thank you!
Note: An example output should be:
>>> increment('00000001')
'00000010'

Calculate how many zeroes you will need. Then prepend them to value.
value = '01'
needed = 8 - len(value)
value = '0' * needed + value
You can also use zfill():
value = value.zfill(8)

Related

How to capture the first digit while converting a decimal number to binary digit using naive recursion?

I am trying to convert a decimal number to a binary digit in the below way using recursion.
def getbin(x: int, s: str):
if int(x/2) > 0:
y = int(x/2)
s += str(y % 2)
print(f'int(x/2): {int(x/2)}, y: {y}, st: {s}')
getbin(y, s)
elif int(x/2) == 1:
s += '11'
return s
if __name__ == '__main__':
print(getbin(28, ''))
But when I call this, I can see in the output that the first digit of the binary number is not getting captured.
I ran two test cases:
For the number 28, the expected output should be 00111 but the output is 0111:
For the number 5, the output should be 101 but the output is 01
Could anyone let me know what is the mistake I am making here and how can I correct it ?
Your problem is that you are testing against x/2 instead of testing against x. Thus you lose the most significant bit of the result. Try something like this:
def getbin(x: int, s: str):
s += str(x % 2)
y = x // 2
if y > 0:
return getbin(y, s)
return s
Note also that you need to reverse the result of getbin to get the correct binary string.

Python: How to find all ways to decode a string?

I'm trying to solve this problem but it fails with input "226".
Problem:
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
My Code:
class Solution:
def numDecodings(self, s: str) -> int:
decode =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
ways = []
for d in decode:
for i in s:
if str(d) == s or str(d) in s:
ways.append(d)
if int(i) in decode:
ways.append(str(i))
return len(ways)
My code returns 2. It only takes care of combinations (22,6) and (2,26).
It should be returning 3, so I'm not sure how to take care of the (2,2,6) combination.
Looks like this problem can be broken down into many subproblems thus can be solved recursively
Subproblem 1 = when the last digit of the string is valid ( i.e. non zero number ) for that you can just recur for (n-1) digits left
if s[n-1] > "0":
count = number_of_decodings(s,n-1)
Subproblem 2 = when last 2 digits form a valid number ( less then 27 ) for that you can just recur for remaining (n-2) digits
if (s[n - 2] == '1' or (s[n - 2] == '2' and s[n - 1] < '7') ) :
count += number_of_decodings(s, n - 2)
Base Case = length of the string is 0 or 1
if n == 0 or n == 1 :
return 1
EDIT: A quick searching on internet , I found another ( more interesting ) method to solve this particular problem which uses dynamic programming to solve this problem
# A Dynamic Programming based function
# to count decodings
def countDecodingDP(digits, n):
count = [0] * (n + 1); # A table to store
# results of subproblems
count[0] = 1;
count[1] = 1;
for i in range(2, n + 1):
count[i] = 0;
# If the last digit is not 0, then last
# digit must add to the number of words
if (digits[i - 1] > '0'):
count[i] = count[i - 1];
# If second last digit is smaller than 2
# and last digit is smaller than 7, then
# last two digits form a valid character
if (digits[i - 2] == '1' or
(digits[i - 2] == '2' and
digits[i - 1] < '7') ):
count[i] += count[i - 2];
return count[n];
the above solution solves the problem in complexity of O(n) and uses the similar method as that of fibonacci number problem
source: https://www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/
This seemed like a natural for recursion. Since I was bored, and the first answer didn't use recursion and didn't return the actual decodings, I thought there was room for improvement. For what it's worth...
def encodings(str, prefix = ''):
encs = []
if len(str) > 0:
es = encodings(str[1:], (prefix + ',' if prefix else '') + str[0])
encs.extend(es)
if len(str) > 1 and int(str[0:2]) <= 26:
es = encodings(str[2:], (prefix + ',' if prefix else '') + str[0:2])
encs.extend(es)
return encs if len(str) else [prefix]
This returns a list of the possible decodings. To get the count, you just take the length of the list. Here a sample run:
encs = encodings("123")
print("{} {}".format(len(encs), encs))
with result:
3 ['1,2,3', '1,23', '12,3']
Another sample run:
encs = encodings("123123")
print("{} {}".format(len(encs), encs))
with result:
9 ['1,2,3,1,2,3', '1,2,3,1,23', '1,2,3,12,3', '1,23,1,2,3', '1,23,1,23', '1,23,12,3', '12,3,1,2,3', '12,3,1,23', '12,3,12,3']

How do I return the middle of a python array?

Here is the prompt:
On the first line display the first, last and middle element of the list separated by the , character.
I have been trying to get this figured out for a few hours now, but do not know the correct process to return the middle of the array. Here is my code so far:
primary = []
length = 0
i = ("MORE")
while i != "NOMORE":
i = str(input("?"))
print(i)
if i == "NOMORE":
break
primary.append(i)
length = length + 1
mid = (length/2)
print(primary[0]," , ", primary[-1]," , ",primary.pop([mid]))
The code works to get the correct inputs from the program, but as the lists will be variable lengths I assume some form of a loop will be used. The primary.pop([mid]) was my poor attempt at getting the median printed. I know that the mid will not be printed as it is the wrong variable type, but how would I replace this?
Any help is appreciated.
You're unnecessarily calling the pop() method on primary with [mid] when you should simply be indexing primary with mid. You should also use the // operator instead of / to obtain an integer value for the index. Since the index is 0-based, the mid point should be (length - 1) // 2 instead:
primary = []
length = 0
i = ("MORE")
while i != "NOMORE":
i = str(input("?"))
print(i)
if i == "NOMORE":
break
primary.append(i)
length = length + 1
mid = (length - 1) // 2
print(primary[0]," , ", primary[-1]," , ",primary[mid])

Returning a string for the number with prefix 0s

I don't understand this question and confused. can anyone show me? It's an exercise in a python book. Only can use loop and function. And based on the question, have to ask the user to enter the number and width.
def format(number, width):
The function returns a string for the number with prefix 0s. The size
of the string is the width. For example, format(34, 4) returns "0034"
and format(34, 5) returns "00034". If the number is longer than the
width, the function returns the string representation for the number.
For example, format(34, 1) returns "34".
I don't quite understand what you mean by "Only can use loop and function". Since your can use function, you can use almost anything in Python.
The simplest solution:
def format(n,w):
s = str(n)
return ('0' * w + s)[-max(w,len(s)):]
>>> format(34,4)
'0034'
Or you can use a loop:
def format(n,w):
s = str(n)
result = ''
for i in range(w - len(s)):
result += '0'
return result + s
>>> format(34,1)
'34'
>>> format(34,4)
'0034'
Try:
def format(number, width):
numstr = str(number)
result = ''
numstrlen = len(numstr)
for i in range(width - numstrlen):
result += '0'
result += numstr
return result
I would have simply done subtraction, but you said it needed to be a loop.
If you can't use len:
def format(number, width):
numstr = str(number)
result = ''
numstrlen = 0
for c in numstr:
numstrlen += 1
for i in range(width - numstrlen):
result += '0'
result += numstr
return result

A python code to convert a number from any base to the base of 10 giving errors . What is wrong with this code?

import math
def baseencode(number, base):
##Converting a number of any base to base10
if number == 0:
return '0'
for i in range(0,len(number)):
if number[i]!= [A-Z]:
num = num + number[i]*pow(i,base)
else :
num = num + (9 + ord(number[i])) *pow(i,base)
return num
a = baseencode('20',5)
print a
Errors I get are
Traceback (most recent call last):
File "doubtrob.py", line 19, in <module>
a = baseencode('20',5)
File "doubtrob.py", line 13, in baseencode
if number[i]!= [A-Z]:
NameError: global name 'A' is not defined
Isn't int(x, base) what you need?
int('20',5) # returns the integer 10
You're confusing Python with... Perl or something...
if not ('A' <= number[i] <= 'Z'):
A more comprehensive solution to this problem may look like this:
import string
# Possible digits from the lowest to the highest
DIGITS = '%s%s' % (string.digits, string.lowercase)
def baseencode(num, base):
result = 0
positive = True
# If a number is negative let's remove the minus sign
if num[0] == '-':
positive = False
num = num[1:]
for i, n in enumerate(num[::-1]):
# Since 0xff == 0xFF
n = n.lower()
result += DIGITS.index(n) * base ** i
if not positive:
result = -1 * result
return result
Basically whilst converting a number to base 10 it's easiest to start from the last digit, multiply it by the base raised to the current position (DIGITS.index(n) * base ** i).
BTW, in my understanding it's a Python exercise, but if it's not there's a builtin function for that - int:
int(x[, base]) -> integer
Other bugs in the code:
1. You didn't initialize variable num that you used to store results.
2. you need to convert number[i] from char to int before you can apply multiplication/addition.
num = num + int(number[i]) * pow(i,base)
There are many errors in your code. To begin with,
number[i] != [A-Z]
is not Python syntax at all. What you probably want is
number[i].isdigit()
Furthermore, the
if number == 0:
return '0'
part should probably be
if number == '0':
return 0
but actually, there is no need to special-case this at all. Another problem is that you interpreting the first character as "ones", i.e. lowest significant. There are a few more problems, but maybe this will get you going...
That said, you could simply use
int('20',5)
import math
def base_encode(number, base):
"""Convert number in given base to equivalent in base10
#param number: string, value to convert (case-insensitive)
#param base: integer, numeric base of strNumber
#retval: integer, x base(10) == number base(base)
"""
# sanitize inputs
number = str(number).lower()
base = int(base)
# legal characters
known_digits = '0123456789abcdefghijklmnopqrstuvwxyz'
value = { ch:val for val,ch in enumerate(known_digits) if val<base }
# handle negative values
if number[0]=='-':
sign = -1
number = number[1:]
else:
sign = 1
# do conversion
total = 0
for d in number:
try:
total = total*base + value[d]
except KeyError:
if d in known_digits:
raise ValueError("invalid digit '{0}' in base {1}".format(d, base))
else:
raise ValueError("value of digit {0} is unknown".format(d))
return sign*total
base_encode('20', 5) -> 10
base_encode('-zzz', 36) -> -46655
You probably want
if number[i] not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
or
import string
# ...
if number[i] not in string.ascii_uppercase:

Categories

Resources