(Beginner)Python functions Codeacademy - python

I'm just learning to program on Codeacademy. I have an assignment, but cant figure out what I'm doing wrong.
First I need to define a function that returns the cube of a value. Then I should define a second function that checks if a number is divisible by 3. If it is I need to return it, otherwise I need to return False.
heres the code:
def cube(c):
return c**3
def by_three(b):
if b % 3 == 0:
cube(b)
return b
else:
return False

You are not catching the return value of the function cube. Do b = cube(b). Or better yet, do return cube(b).
def cube(c):
return c**3
def by_three(b):
if b % 3 == 0:
b = cube(b)
return b # Or simply return cube(b) and remove `b = cube(b)`
else:
return False
When you call the cube function with the argument b, it returns the cube of the passed argument, you need to store it in a variable and return that to the user, in your current code, you are neglecting the returned value.

I think this answer might also work:
def cube(b,c):
b = c ** 3
if b % 3 == 0:
return b
else:
return False
return b
I know that might be a little redundant but I think that might be another way of doing what you're trying to do. What Sukrit did I think is simpler.

I have finished Codecdemy and this is my code.
def cube(n):
return n ** 3
def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False

Here's a lightweight solution I just developed, should work :)
def cube(number):
return number**3
def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False

def cube(num):
return n ** 3
def by_three(value):
if value % 3 == 0:
return cube(value)
else:
return False

try calling the same letter for each. Instead of using 'c' and 'b', just use 'c'
def cube(c):
return c**3
def by_three(c):
if c % 3 ==0:
return cube(c)
else:
return False

Related

Need an OOP method for share variable between function?

I have a class and some functions. In the 'check_reflexive()' function, there is a variable called reflexive_list. I want to use this variable also in the 'antisymmetric' function.
I checked some examples about class but didn't find a specific example to solve this problem.
I'll be waiting for your advice. Hope you have a nice day
class MyClass():
def __init__(self):
def checkif_pair(k):
for a in k:
if a%2 == 0:
None
else:
return False
return True
def check_reflexive(k):
j = 0
z = 0
reflexive_list = []
while j < len(k):
i = 0
while i < len(k):
if k[i] == k[j]:
tup = k[j],k[i]
reflexive_list.append(tup)
i += 1
else:
None
j = j + 1
else:
None
print(reflexive_list)
if len(reflexive_list) == len(self.list1):
return True
else:
return False
def antisymmetric(k):
antisymettric_list = []
for b in k:
swap1 = b[0]
swap2 = b[1]
newtuple = (swap2, swap1)
antisymettric_list.append(newtuple)
for ü in reflexive_list:
if ü in antisymettric_list:
antisymettric_list.remove(ü)
else:
None
print(antisymettric_list)
for q in antisymettric_list:
if q in k:
print("The system is not Anti-Symmetric.")
break
print("The system is Anti-Symmetric.")
def transitive(k):
result = {}
for first, second in k:
result.setdefault(first, []).append(second)
print(result)
for a, b in k:
for x in result[b]:
if x in result[a]:
None
else:
print("There is no {} in the {}".format(x, result[a]))
return False
return True
You can just use reflexive_list as an instance variable. Just add a constructor where the variable is defined:
class MyClass():
def __init__(self):
self.reflexive_list = []
And everytime you want to use it inside the function, you use self.reflexive_list

How to not return nonType in this definition?

How can I return the value of total_square only when quasi_gen==0? If I put another return statement to the case where quasi_gen>0, then it always returns zero.
def count_boxes(quasi_gen, initial_list):
total_square=0
new_list=[]
new_list=[box * 2 for box in initial_list]
concatenate_list=initial_list+new_list
if quasi_gen>0:
quasi_gen-=1
count_boxes(quasi_gen, concatenate_list)
elif quasi_gen==0:
total_square=(sum(elem for elem in concatenate_list))
return(total_square)
count_boxes(4, [2,2])
Not sure what you're trying to do but first of all you should safe guard against quasi_gen < 0
you also don't need to do all those useless resets, in short, try this:
def count_boxes(quasi_gen, initial_list):
concatenate_list=initial_list + [box * 2 for box in initial_list]
if quasi_gen < 0:
return 0 # ?
if quasi_gen > 0:
return count_boxes(quasi_gen - 1, concatenate_list)
return(sum(elem for elem in concatenate_list))
You have to call return on the first if/else branch:
if quasi_gen>0:
quasi_gen-=1
return count_boxes(quasi_gen, concatenate_list)
Like this you will be returning the result of the recursive call.

print a binary tree how to fix the build_balanced_bst function

def str_tree(atree,indent_char ='.',indent_delta=2):
def str_tree_1(indent,atree):
if atree == None:
return ''
else:
answer = ''
answer += str_tree_1(indent+indent_delta,atree.right)
answer += indent*indent_char+str(atree.value)+'\n'
answer += str_tree_1(indent+indent_delta,atree.left)
return answer
return str_tree_1(0,atree)
def build_balanced_bst(l):
if len(l) == 0:
return None
else:
mid = (len(l)-1)/2
if mid >= 1:
build_balanced_bst(l[:mid])
build_balanced_bst(l[mid:])
else:
return
I am working on the build_balanced_bst(l), the build_balanced_bst(l) takes a list of unique values that are sorted in increasing order. calling build_ballanced_bst( list(irange(1,10)) returns a binary search tree of height 3 that would print as:
......10
....9
..8
......7
....6
5
......4
....3
..2
....1
the str_tree function is used to print what the build_balanced_bst() function returns. my str_tree function is correct, I cannot change it. I can only change the build_balanced_bst() function.
I used the middle value in the list as the root’s value. when I try to call the build_balanced_bst(l) in the below, it does not print anything.
l = list(irange(1,10))
t = build_balanced_bst(l)
print('Tree is\n',str_tree(t),sep='')
can someone help me to fix my build_balanced_bst(l) function? many thanks.
str_tree() doesn't do anything: It just defines a nested function and implicitly returns None.
As a start, you can have str_tree do something:
def str_tree(atree, indent_char ='.', indent_delta=2):
def str_tree_1(indent, atree):
# Note that str_tree_1 doesn't use the indent argument
if atree == None:
return ''
return str_tree_1(indent_delta, atree)
But this is just a start.

Can I create a master function in Python to take a single line of other functions?

I have two functions that contain mostly the same code. One returns "True" if the array passed in contains all positive numbers while the other returns "True" if the array contains all numbers that are divisible by 10.
I want to combine these two functions into a function like this:
def master_function(array, function):
for i in array:
if function:
result = True
else:
result = False
break
print(result)
return result
The only part that would vary is the "function" in the If statement. When I write functions with the missing line they don't get called as the program executes.
def positive_integers(array):
i >= 0
def divisible_by_10(array):
i%10 == 0
The test code isn't executed either.
master_function([10,20,30,35],divisible_by_10)
Your functions aren't returning anything, and you need to give them access to i:
def positive_integers(i):
return i >= 0
def divisible_by_10(i):
return not i%10
def master_function(array, function):
for i in array:
if function(i):
result = True
else:
result = False
break
print(result)
return result
Your function don't return anything. Also, you need read about all and any:
def positive_integers(array):
return all(i >= 0 for i in array)
def divisible_by_10(array):
return all(i % 10 == 0 for i in array)
def master_function(array, function):
return function(array)
def master_function(array, function):
for i in array:
print str(i)
if function(i):
result = True
else:
result = False
print(result)
return result
def positive_integers(i):
if i >= 0:
return True
def divisible_by_10(i):
if i%10 == 0:
return True
master_function([10,20,30,35],divisible_by_10)

Python recursion, how come my function doesn't work?

I am trying to write a Python 3 recursive function which will tell me if an integer is in a nested list. I am not sure how I can make my code return True if it finds it in the list, and False if it doesn't find it in the list. When I print the result of my for loop, I get a bunch of
false
false
false
false
true
false
false
false
etc. But, it returns False because the last call was false, even though I want it to return true. How can I fix this?
Here is my code:
def nestedListContains(NL, target):
if( isinstance(NL, int) ):
return NL
for i in range(0, len(NL)):
return ( nestedListContains(NL[i], target) == target )
return False
And here is how I'm calling it
print(nestedListContains([[3], [4,5,7], [[[8]]]], 8))
EDIT: This seems to be working for me, but it seems rather ghetto:
def nestedListContains(NL, target):
if( isinstance(NL, int) ):
if( NL == target ):
return 1
return 0
x = 0
for n in NL:
x += nestedListContains(n, target) == 1
return x != 0
My attempt:
def contains(lst, target):
if isinstance(lst, int):
return lst == target
return any(contains(x, target) for x in lst)
You return the result regardless of whether it's True or not. You could do something like this:
def nestedListContains(NL, target):
if isinstance(NL, int):
return NL == target
for n in NL:
result = nestedListContains(n, target)
if result:
return result
return False
Using duck typing for #gatto's solution
def contains(lst, target):
try:
return any(contains(x, target) for x in lst)
except TypeError:
return lst == target

Categories

Resources