Do not understand how this recursion function works in Python - python

0 -> ‘Z’, 1->’X’, 2->’T’, 3->’J’, 4->’A’, 5->’W’, 6->’F’, 7->’S’, 8->’B’, 9->‘V’
To help your friend recover the integer, write a recursive function re_decry(x) in the answer box such that if x = re_encry(m), then re_decry(x) returns the integer m.
So basically, if x = "XTJA", the output should be 1234.
My code
def de_encry(x):
if len(x) == 1:
return mydict[x]
if len(x) > 1:
return de_encry(x[0:len(x)-1]) + mydict[x[len(x)-1]]
I wrote this, but the output is wrong. This outputs 10
The suggested answer is
def de_encry(x):
if len(x) == 1:
return mydict[x]
if len(x) > 1:
return de_encry(x[0:len(x)-1])*10 + mydict[x[len(x)-1]]
This outputs 1234
I don't get why the *10 makes or breaks the answer, why doesn't my code work?
This is not a homework question, I am just practicing

The number 1234 is not equal to 1+2+3+4; it is equal to (((1*10)+2)*10+3)*10)+4.

Write tests against smaller input. For example, if your input is WW, then your first solution would return 10, 5+5. You get the digits correct, but not the addition
If you multiply through each number by 10, then add the "ones position", you're effectively shifting the numbers left, so would return 55 (5*10+5 = 50+5), or logically, "5, shifted left, then appended with 5" for WW.
Expand that to three letters, you get ((x*10)+y)*10 + z = x*100 + y*10 + z, which is a three digit number for x, y, z < 10
Note: You should ask if a string of all Z's is a string 0000, or just int 0

Related

My Function To Count The Largest Binary Gap Doesn't Work But I Can't Figure Out Why

I'm working through the Codility problems and I have gotten the first one almost correct. The task is to write a function which returns the longest binary gap (a sequence of 0s in between 1s) in a binary number. I have gotten all of the test numbers correct apart from 9, which should be 2 (its binary representation is 1001) but which my function returns as 0. I can't seem to figure out why.
My function is as follows:
def Solution(N):
x = bin(N)[2:]
x_string = str(x)
y = (len(x_string))
count = 0
max = 0
for index, item in enumerate(x_string):
if item == "1":
count = 0
elif item == "0" and x_string[index + 1:y-1] != "0"*(y -1 - (index + 1)):
count = count + 1
if count > max:
max = count
print(max)
The complicated indexing and second condition in the elif statement is so that when a 0 is not contained between two 1s then it isn't recognised as the beginning of a binary gap e.g. when the for loop looks at the second character in bin(16) = 10000, it doesn't set count to 1 because all of the remaining characters in the string are also zero.
Simple solution
x_string[index + 1:y-1] != "0"
this bit wants to take a look at the whole string that's left, but the end argument isn't inclusive,it's exluded, so if string length = 4; string[0:4] is the whole string.
source: https://docs.python.org/3/tutorial/introduction.html
-Sam

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.

Layer Python Sum of Digits

this is my first question around here.
I've been working on an algorithm that adds the numbers entered until I get a single-digit number, but haven't been able to find a solution for about a week.
for example:
value = 1994
Step = 1+9+9+4 = 23
Step = 2+3 = 5
Try this:
def func(x):
while x >= 10:
x = sum([int(c) for c in str(x)])
return x
print(func(1994))
value = 1994
while len(str(value)) != 1:
value = sum([int(i) for i in str(value)])
print(value)
5
What's going on?
initiate value
loop if the length of the integer is not equal to one (meaning it's done)
get a sum of the list of all sub ints inside the int

Formatting unknown output in a table in Python

Help! I'm a Python beginner given the assignment of displaying the Collatz Sequence from a user-inputted integer, and displaying the contents in columns and rows. As you may know, the results could be 10 numbers, 30, or 100. I'm supposed to use '\t'. I've tried many variations, but at best, only get a single column. e.g.
def sequence(number):
if number % 2 == 0:
return number // 2
else:
result = number * 3 + 1
return result
n = int(input('Enter any positive integer to see Collatz Sequence:\n'))
while sequence != 1:
n = sequence(int(n))
print('%s\t' % n)
if n == 1:
print('\nThank you! The number 1 is the end of the Collatz Sequence')
break
Which yields a single vertical column, rather than the results being displayed horizontally. Ideally, I'd like to display 10 results left to right, and then go to another line. Thanks for any ideas!
Something like this maybe:
def get_collatz(n):
return [n // 2, n * 3 + 1][n % 2]
while True:
user_input = input("Enter a positive integer: ")
try:
n = int(user_input)
assert n > 1
except (ValueError, AssertionError):
continue
else:
break
sequence = [n]
while True:
last_item = sequence[-1]
if last_item == 1:
break
sequence.append(get_collatz(last_item))
print(*sequence, sep="\t")
Output:
Enter a positive integer: 12
12 6 3 10 5 16 8 4 2 1
>>>
EDIT Trying to keep it similar to your code:
I would change your sequence function to something like this:
def get_collatz(n):
if n % 2 == 0:
return n // 2
return n * 3 + 1
I called it get_collatz because I think that is more descriptive than sequence, it's still not a great name though - if you wanted to be super explicit maybe get_collatz_at_n or something.
Notice, I took the else branch out entirely, since it's not required. If n % 2 == 0, then we return from the function, so either you return in the body of the if or you return one line below - no else necessary.
For the rest, maybe:
last_number = int(input("Enter a positive integer: "))
while last_number != 1:
print(last_number, end="\t")
last_number = get_collatz(last_number)
In Python, print has an optional keyword parameter named end, which by default is \n. It signifies which character should be printed at the very end of a print-statement. By simply changing it to \t, you can print all elements of the sequence on one line, separated by tabs (since each number in the sequence invokes a separate print-statement).
With this approach, however, you'll have to make sure to print the trailing 1 after the while loop has ended, since the loop will terminate as soon as last_number becomes 1, which means the loop won't have a chance to print it.
Another way of printing the sequence (with separating tabs), would be to store the sequence in a list, and then use str.join to create a string out of the list, where each element is separated by some string or character. Of course this requires that all elements in the list are strings to begin with - in this case I'm using map to convert the integers to strings:
result = "\t".join(map(str, [12, 6, 3, 10, 5, 16, 8, 4, 2, 1]))
print(result)
Output:
12 6 3 10 5 16 8 4 2 1
>>>

Find the biggest number formed by digits of input numer

I am trying to write a function that return the biggest number formed by the digits from an input integer number.
So if the input = 123584
output should be = 854321
My code is -
def maxNumber(inputNumber):
x = len(str(inputNumber))
max_number = []
result= []
while(x>0):
max_number.append(inputNumber%10)
inputNumber = inputNumber/10
x -= 1
while(x<(len(str(max_number)))):
result.append(max(max_number))
x += 1
return result
print maxNumber(1238675)
and off-course the output is not as I want. Please help. I am eager to learn all possible way to do it.
def maxNumber(inputNumber):
return int(''.join(sorted(str(inputNumber), reverse=True)))
The biggest number is formed by sorting the digits in descending order. This can be achived using the rverse=True parameter to sorted():
def max_digit_permutation(n):
return int("".join(sorted(str(n), reverse=True)))
This is more reliable than most answers given so far ;-)
def max_number(n):
s = str(n)
digits = sorted(s, reverse=n>0)
return int(''.join(digits))
print max_number(231)
print max_number(-231)
print max_number(+231)
And good point - I missed the option of doing it with number alone - here it is for completeness. :)
from math import *
def max_number(n):
digit_count = int(log(abs(n+1),10)) + 1
digits = sorted([(n / 10 ** (x - 1) % 10) for x in range(digit_count,0,-1) ], reverse=True)
return reduce(lambda x, y:10*x + y, digits)
print max_number(1000)
print max_number(999)
print max_number(2345128)
print max_number(231)
sort the string of number, reverse it, join it and convert to int
>>> x=123584
>>> int(''.join(sorted(str(x))[::-1]))
854321
You could just treat the number as a list of single digits and then sort the list in decreasing order.
What about something like this:
num = str(123584)
int(''.join(sorted(num, reverse=True)))

Categories

Resources