How to fix the recursive function? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
It's a simple question of recursive function, which extracting every digits from a positive number. As the comment mentioned, I have known the mistake is because of global variable, but I still have no idea to fix it to get expected result. Thanks.
def getdigits(n):
if n == 0:
return list_1[::-1]
list_1.append(n % 10)
return getdigits(int(n / 10))
list_1 = []
print(getdigits(120)) # output = [1,2,0]
print(getdigits(5)) # output = [5,1,2,0]
But the expected output should be
print(getdigits(120)) # expected output = [1,2,0]
print(getdigits(5)) # expected output = [5]

You are using the existing LIST that already have values from the previous function call.
First clear the list and then try to call for another value.\
Try it
def getdigits(n):
if n == 0:
return list_1[::-1]
list_1.append(n % 10)
return getdigits(int(n / 10))
list_1 = []
print(getdigits(120))
list_1.clear() #clear list values
print(getdigits(5))

def getdigits(n):
global list_1
if n == 0:
listTemp = list_1
list_1 = []
return listTemp
list_1.append(n % 10)
return getdigits(int(n / 10))
list_1 = []
print(getdigits(120)) # output = [1,2,0]
print(getdigits(5)) # output = [5]
you need to declare list 1 as a global varible inside your function so you can clear list one within th function
i have tested it and got that output

Related

How to nest python lists recursively? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
list0 = [[]]
list0[0].append([])
list0[0][0].append([])
list0[0][0][0].append(["I'm in deep!"])
print(list0)
How do I achieve the nested effect above in a loop? Like how I can append lists to a list in a loop.
def list_deepener(layers):
list1 = [[]]
count = 0
while count != layers:
count += 1
y = "list1" + ("[0]" * count)
y.append([])
print(x)
list_deepener(5)
I tried this but I couldn't think of any way to convert the string into code which would allow me to alter list1.
You could pass a range and initial string to functools.reduce for a simple one-liner:
from functools import reduce
layers = 4
reduce(lambda a, _: [a], range(layers), "I'm in deep!")
# [[[["I'm in deep!"]]]]
Suppose that we have mylist = [] to begin with, and we want to add lists to a certain depth. The trick is to use a separate variable to keep track of where we are in the nesting process, and update that variable as we add each layer. Thus:
>>> mylist = []
>>> current = mylist
>>> for i in range(5):
... to_add = []
... current.append(to_add)
... current = to_add
...
>>> mylist # 6 pairs of brackets: the initial list, plus 5 added nested lists
[[[[[[]]]]]]
There's many ways to solve this issue, but when you find yourself constructing code in strings and looking for ways to execute that, you're on the wrong path.
A recursive solution:
def nest(x, levels):
assert levels >= 0
if levels == 0:
return [x]
else:
return [nest(x, levels-1)]
print(nest("I'm in deep", 5))
An iterative solution:
def nest(x, levels):
assert levels >= 0
result = [x]
for _ in range(levels):
result = [result]
return result
print(nest("I'm in deep", 5))
Another way to think about this is recursively. Consider what you want in the deepest part of your list (your 'base' case') and then layer on top for each iteration.
def deepen(layers: int) -> list:
if layers <= 1: # Base case, i.e. 'what happens at the bottom'
return ["Deeper than deep"]
else: # Iterative case, i.e. 'what happens at each layer'
return [deepen(layers - 1)]
This gives you the correct result:
>>> def deepen(layers: int) -> list:
... if layers <= 1:
... return ["Deeper than deep"]
... else:
... return [deepen(layers - 1)]
...
>>> deepen(5)
[[[[['Deeper than deep']]]]]

Return just the item of a list if len(list) == 1 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I have a list with possibly several items (tuples) that I need to return. But what about, in the case that I only get one item in my list, I would like to return the item itself and not a list with only one item. How could this be done?
This is my code:
def strength(self):
values = []
max_v = 0
my_list = []
for i in inspect.getmembers(self):
if not i[0].startswith('_'):
if not inspect.ismethod(i[1]):
if "name" in i:
continue
values.append(i[1])
my_list.append(i)
max_v = max(values)
result = [tup_item for tup_item in my_list if tup_item[1] == max_v]
result.sort(reverse=True)
if len(result) > 1:
return tuple(result)
else: # in case len(result) == 1
return result # this is where i get a list with only one item but
# i would like to get just the tuple itself
If your list only has one item, it's usually at the 0th index. Just return result[0]. I would not recommend it though, since you will have to differentiate between lists and tuples from wherever you're calling that function.

Compare empty array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm writing a program that takes a list of floating point numbers representing distance in inches and converts them to shoe sizes to the nearest 0.5.
I'm trying to compare an empty list and expect the output to be The list is empty. Instead I don't return any value. Not sure where I'm going wrong?
foot_length = []
for length in foot_length:
if length == 0:
print('The list is empty.')
else:
convert_to_shoe_size = length * 3 - 23
round_shoe_size = round(convert_to_shoe_size * 2, 2) / 2
print(round_shoe_size)
I've tried a number of different approaches none of which get the output I want/expect.
if not length:
print('The list is empty.')
if len(length) == 0:
print('The list is empty.')
Try to change your code to
foot_length = []
if len(foot_length) == 0:
print('The list is empty.')
else:
for length in foot_length:
convert_to_shoe_size = length * 3 - 23
round_shoe_size = round(convert_to_shoe_size * 2, 2) / 2
print(round_shoe_size)

How to code this condition in Python? I am new to python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am new to python. so any help will be appreciated.
I have two arrays A = [1,2,4,2,3,5,3] and B = [0,4,4,4,1,1,1]
for the function if I give A, B as input then I should get output as = [1,(2+4+2),(3+5+3)] = [1,8,11](if numbers are repeating in B then corresponding values in A should be added together).
This should do the trick:
def bla(list1:list, list2:list):
prev = list2[0] - 1
final_list = []
for ele, pos in zip(list1, list2):
if prev != pos:
final_list.append(ele)
else:
final_list[-1] += ele
prev = pos
return final_list

variance of list values [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I want to calculate the variance of values in list x1. Could anyone fix the error in this code?!
def my_mean(L):
s = 0
for i in range(0, len(L)):
s = s + L[i]
return s / len(L)
def my_var(L):
t = 0
for i in range(0, len(L)):
t = t + L[i] - def my_mean(L)
return t*t / len (L)
x1 = [1, 3, 4, -3, 8]
v1 = my_var(x1)
print(v1)
You need to use the def keyword only when you define the function.
When you call to the function you don't need to use def again.
Fix this row:
t = t + L[i] - def my_mean(L)
To:
t = t + L[i] - my_mean(L)

Categories