Why is this code not working as intended? Python - python

import string
decimal1 = 55
binary1 = 0
def convert(decimal1, binary1):
binary1 = str(decimal1 % 2) + str(binary1)
decimal1 = decimal1//2
if decimal1 == 0:
binary1 = str(binary1)
return binary1
convert(decimal1, binary1)
x = convert(decimal1, binary1)
print(x[-1])
I wanted a code that converts decimal to binary but the function output is not being taken into x or the program is the returning none. I want to understand why it is happening??

I think if you want to reteurn the result, then you don't need to pass binary1 variable.
import string
decimal1 = 55
def convert(decimal1):
value = str(decimal1 % 2)
decimal1 = decimal1//2
if decimal1 == 0:
return value
else:
return convert(decimal1) + value
x = convert(decimal1)
print(x)

Your function only has one return statement, for the base case. You need a return for the recursive case, too.
When the recursion finishes, in your case the value is just thrown away because there's no return. Python isn't like other languages that return the value of the last expression. If there's no return statement, it returns None instead.

To debug recursion problems like this it can be helpful to visualize whats happening. If you post OPs code in this recursion visualizer here you can see the return value isnt bubbling up, as it does in the selected answer here.

Related

how to count consecutive number of ones given a decimal number?

def decToBin(n):
x=str(bin(n))
x=x[2:]
return x
def result(x):
print(len(max(x.split('0'))))
if __name__ == '__main__':
n = int(input().strip())
decToBin(n)
result(x)
I have tried this code but i am getting an error saying undefined "x"
I want to know what is wrong in this code.
There are several issues in your code.
You aren't returning anything from decToBin function, you should put this at the end of the function:
return x
You aren't storing the result of decToBin function anywhere, you can either store it in a variable or put decToBin directly in the result function like this:
result(decToBin(n))
Your code is not formatted according to PEP8 in some places, I highly recommend you to read it and use it as it should be always used when programming in Python
I'm also not sure if this is what you wanted to do according to your question title
Here is the final code:
def decToBin(n):
x = str(bin(n))
x = x[2:]
return x
def result(x):
print(len(max(x.split('0'))))
if __name__ == '__main__':
n = int(input().strip())
result(decToBin(n))
The problem is that the value x is defined in your method decToBin, but never returned. So it is only valid inside of that method.
def decToBin(n):
x=str(bin(n))
x=x[2:]
return x
def result(x):
print(len(max(x.split('0'))))
if __name__ == '__main__':
n = int(input().strip())
x = decToBin(n)
result(x)
EDIT:
But your code is not counting the ones in a decimal number, but in the binary representation of the number.

Python classes and definitions

Here is my python code:
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
s1.isPalindrome()
It checks to see if the input is a palindrome. I want to create a new object that has the x value 121 and when I execute the isPalindrom function, I want it to return either a true or false boolean answer.
Currently when I run this program, nothing gets outputted. I am a bit lost as to where to go from here, would appreciate help.
Just print out the return value of isPalindrome(), because if you have a line with only a return value (this case being a boolean), the compiler won't know what to do with it.
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
print(s1.isPalindrome())
You're not telling the program to print anything. Try using print to make it reveal the answer.
Along with printing results we can also make class more pythonic.
class Solution:
def __init__(self):
self.input = None
def is_palindrome(self):
if isinstance(self.input, str):
return self.input == self.input[::-1]
print("Error: Expects str input")
return False # or leave blank to return None
s1 = Solution()
print(s1.is_palindrome())
s1.input = "121"
print(s1.is_palindrome())
output
Error: Expects str input
False
True
The main idea here is divide number. let's take number 122. First of all you need store it in a variable, in this case r_num. While loop is used and the last digit of the number is obtained by using the modulus operator %. The last digit 2 is then stored at the one’s place, second last at the ten’s place and so on. The last digit is then removed by truly dividing the number with 10, here we use //. And lastly the reverse of the number is then compared with the integer value stored in the temporary variable tmp if both are equal, the number is a palindrome, otherwise it is not a palindrome.
def ispalindrom(x):
r_num = 0
tmp = x
while tmp > 0:
r_num = (r_num * 10) + tmp % 10
tmp = tmp // 10
if x == r_num:
return True
return False

Return and assignment in recursive function in python: None type given, expected an int value

I am fairly new to python but worked with recursion previously. I came across this problem while working with recursive functions.
archive = {1: 0}
def engine(base, chain=0):
if base in archive:
return archive[base]
else:
if base == 1:
return chain
elif base % 2 == 0:
get = engine(base/2)
meaning = 1 + get
archive[base] = meaning
else:
next = 3 * base + 1
get = engine(next)
meaning = 1 + get
archive[base] = meaning
print archive(13)
I worked with scheme recently. So, I expected it to work.
I want the code to evaluate till the case bool(base==1) becomes true and then work it's way up ward making a new entry to the dictionary on each level of recursion.
How can I achieve that? I am just counting the level of recursion until the fore-mentioned condition becomes True with the variable 'chain'.
[Solved]: I missed the return statement in two clauses of if-else statement. The scheme would pass the function itself and the last return statement would do the work but not with python. I understand it now.
Thanks everyone who responded. It was helpful.
Your last two elif and else clauses have no return statements and Python returns None by default.

Python recursion doesn't yield desired result

I am trying to find the length of the string with out using the inbuilt len() function. Here's my python code:
increment = -1
def lenRecur(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
global increment
if aStr == '':
return increment
else:
increment += 1
return lenRecur (aStr[increment:])
print lenRecur ("abcdefq")
The result I am expecting is 7 but what I got was 4.What I realized was when the increment became 2, the value pass to the lenRecur (aStr[increment:]) was "defq". Which means aStr[2:] is evaluated as "defq" instead of "cdefq".
Why this is happening?
Your function should not depend on external variables.
def lenRecur(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
if aStr == '':
return 0
else:
return 1 + lenRecur(aStr[1:])
print lenRecur("abcdefq")
A common idiom is to use a default argument:
>>> def l(s, c=0): return l(s[1:], c+1) if s else c
This kind of solution works with anything that can be sliced
>>> l('pip')
3
>>> l([1,2,3])
3
>>> l('')
0
>>> l([])
0
>>>
As an other option, you could write this:
def lenRecur(aStr):
return _lenRecur(aStr, 0)
def _lenRecur(aStr, acc):
if not aStr:
return acc
return _lenRecur(aStr[1:], acc+1)
A noticed by #gboffi in his answer, it is commonly accepted in Python to use a default argument instead of using of an helper function:
def lenRecur(aStr, acc = 0):
if not aStr:
return acc
return lenRecur(aStr[1:], acc+1)
The choice of one form or the other will depend how much you want/don't want to allow the called to set the initial accumulator value to something else than 0.
Anyway, the interesting point here is in using an accumulator as the second parameter. That way, you have proper tail recursion. Unfortunately, this is not properly optimized by Python. But this is a good habit as many other languages have such optimization. And this will be a required skill if you switch someday to functional programing language.

What causes my function to return None at the end? [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 7 months ago.
My very simple python function is returning None at the end of it and I'm not sure quite why. I've looked at some other posts and still can't figure it out.
Here is my code:
def printmult(n):
i = 1
while i <= 10:
print (n * i, end = ' ')
i += 1
print(printmult(30))
Because in Python, every function returns a value, and None is what is returned if you don't explicitly specify something else.
What exactly did you expect print(printmult(30)) to do? You've asked it to evaluate printmult(30), and then print whatever results from that. Something has to result from it, right? Or were you maybe expecting some kind of exception to be raised?
Please be sure you understand that printing and returning are not the same thing.
You are not returning anything in the function printmult, therefore when you print the result of printmult(30) it will be None (this is the default value returned when a function doesn't return anything explictly).
Since your method have a print statement inside and it's not supposed to return something (usually when a method names is something like printSomething(), it doesn't return anything), you should call it as:
printmult(30)
not
print(printmult(30))
The other answers have done a good job of pointing out where the error is, i.e. you need to understand that printing and returning are not the same. If you want your function to return a value that you can then print or store in a variable, you want something like this:
def returnmult(n):
i = 1
result_string = ''
while i <= 10:
result_string += str(n * i) + ' '
i += 1
return result_string
print(returnmult(30))
def printmult(n):
i = 1
while i <= 10:
print (n * i, end = ' ')
i += 1
printmult(30)
The issue was that you were printing the return value of a function that returns nothing, which would print None
I came from Ruby as well and it seems strange at first.
If you print something that has a print statement in it, the last thing it returns is None.
If you just returned the values and then invoked a print on the function it would not output None.
Hope this helps :)

Categories