Loop. Why it can see only 10 from whole list? - python

def new_list(lst):
for i in lst:
if i%10 == 0:
return i
else:
return False
print(new_list([10, 20.0, 25, 30, 40, 98]))
i want to see all numbers from the list that can be divided into 10

Calling return in a function ends execution of the function. So either way, the your function will stop running after the first iteration in your for loop. I don't know what you are expecting for output, but in your function you can instead append the items to a list and return the list at the end:
def new_list(lst):
result_list = []
for i in lst:
if i%10 == 0:
result_list.append(i)
return result_list

This can also be done with a list comprehension:
def new_list(lst):
return [x for x in lst if x % 10 == 0]

Related

Summation of values in nested lists

I have encountered a problem where a return gives None back, though the variable had a value just a single line of code before.
mylist = [[7]]
def sumcalc(the_list,n):
s = n
for x,y in enumerate(the_list):
if type(y) == list:
sumcalc(y,s)
elif type(y) == int:
s += y
if x < len(the_list)-1:
sumcalc(the_list[x+1], s)
else:
print (s)
return s
print(sumcalc(mylist,0))
The print command in the second to last line gives me 7, as expected. But the return is None. Any help on this would be appreciated :)
If you are writing a recursive function. You must put return key word before recursive call.
mylist = [[7]]
def sumcalc(the_list,n):
s = n
for x,y in enumerate(the_list):
if type(y) == list:
return sumcalc(y,s)
elif type(y) == int:
s += y
if x < len(the_list)-1:
sumcalc(the_list[x+1], s)
else:
print (s)
return s
print(sumcalc(mylist,0))
sumcalc() doesn't do anything on its own; you need to use the return value. Beyond this, the index checking is unecessary, as the return could simply be placed after the loop. Here is a simpler way of writing the nested sum code.
def nested_sum(x):
if type(x)==int:
return x
if type(x)==list:
return sum(
nested_sum(item)
for item in x
)

remove negative element from nested list and square the list without using loop

Input: testlist = [[1,2,3,-1],2,3,[3,-4,1,3],-1,-3]
Requirement:
remove elements less than zero
then square the elements without using any loop
output :
[[1,4,9],4,9,[9,1,9]]
def testlist(f, l):
def listelement(inside):
return testlist(f, inside) if type(inside) is list else f(inside)
return list(map(listelement, l))
def square(x):
return x * x
def square_list(l):
return testlist(square, l)
You could think about the problem recursively:
If the list is empty, return an empty ist
If it isn't, for the first item of the list:
If it's a negative number, omit it
If it's a non-negative number, square it
If it's a list, apply the function on it.
Return a list that's a concatenation of the element from #1 and the function applied to the rest of the list.
Or, in python:
def func(l):
if len(l) == 0:
return []
item = l[0]
if isinstance(item, list):
result = [func(item)]
elif item >= 0:
result = [item**2]
else:
result = []
return result + func(l[1:])
Instead of having two separate functions, you can do the squaring and the checking for positive in the same function.
To handle not looping we can use recursion. Since we are already using recursion, we can handle lists with the same recursive function.
test_list = [[1,2,3,-1],2,3,[3,-4,1,3],-1,-3]
def positive_square_list(lst, index):
if index < len(lst):
if type(lst[index]) == list:
positive_square_list(lst[index], 0)
index += 1
if lst[index] < 0:
lst.pop(index)
index -= 1
if index == len(lst):
return lst
else:
return positive_square_list(lst, index+1)
lst[index] = lst[index] ** 2
return positive_square_list(lst, index+1)
return lst
output = positive_square_list(test_list, 0)
The variable output will have the values: [[1,4,9],4,9,[9,1,9]]

How to create a new list from a previous list where elements are added to their position if the position is even?

Define a function named addPosToElem(...) which receives a list with integer numbers and returns a new list containing the elements form the original list in even positions where the position is added to the element. The list can possibly be empty
As an example, the following code fragment:
lst = [0,10,20,30,40,50]
print(addPosToElem(lst))
gives the output:
[0, 22, 44]
My code:
def addPosToElem(lst):
for i in range(lst[0], len(lst)):
if (lst[i] % 2) == 1:
element_odd = int(lst[i])
elif (lst[i] % 2) == 0:
element_even = int(lst[i]) + lst.index(i)
new_lst = element_odd + element_even
return new_lst
I keep getting 1 is not in list, how to fix my code?
The most pythonic way to do this is with list comprehension:
[num + place for place, num in enumerate(lst) if place % 2 == 0]
# [0, 22, 44]
Or with regular loop:
new_lst = []
for place in range(len(lst)):
if place % 2 == 0:
new_lst.append(lst[place] + place)
new_lst # [0, 22, 44]
This will do what you want. It isn't as 'good' as list comprehension but may be slightly more readable for a beginner.
def addPosToElem(lst):
new_lst = []
for i in range(len(lst)):
if (i % 2) == 0:
new_lst.append(lst[i] + i)
return new_lst
There are a few error with this approach:
As mentioned in the comment, you are checking lst[i]%2, you should check i%2 to get the indices.
You are checking lst.index(i) which fails in the 2nd iteration, because i is 1 and 1 is not in list.
You are not using the element_odd and element_odd as lists, so even if somehow your algorithm worked you would get two values as output.
Instead try this:
def addPosToElem(lst):
return [index+value for index, value in enumerate(lst) if index%2 == 0]
Your fixed code will be:
def addPosToElem(lst):
new_lst = []
for i in range(lst[0], len(lst)):
if (i % 2) == 0:
element_even = int(lst[i]) + i
new_lst.append(element_even)
return new_lst

How to add a counter to a recursive function? [Python]

The program has to replace two numbers within the list with a number that is also given in the parameters. I can't change the parameters, but I can create other functions also. In addition I must use recursion. So far I figured out how to do the replacement with recursion, but I'm confused about the count. Every time I try I cant seem to only replace the first two occurrences of 'x' with 'y', instead I always get to replace every 'x' with 'y'.
EDIT: And I can't use global variables.
def replaceFirstTwo(x,y,lst):
if lst == []:
return []
else:
if lst[0] == x:
return [y] + replaceFirstTwo(x,y,lst[1:])
else:
return [lst[0]]+ replaceFirstTwo(x,y,lst[1:])
A correct outcome should look like this :
replaceFirstTwo(1,2,[5,1,2,3,1,1])
[5, 2, 2, 3, 2, 1]
If x is only ever going to be positive then you can use, the negative version to signify that it is the second time that you are running the function. Before changing x to something to signify do nothing.
I have modified your function so it does this, however it will not work with negative values of x as the abs(x) will make it positive.
def replaceFirstTwo(x,y,lst):
if lst == []:
return []
else:
if x is not None:
if lst[0] == abs(x):
if x > -1:
x = -x
else:
x = None
return [y] + replaceFirstTwo(x,y,lst[1:])
else:
return [lst[0]]+ replaceFirstTwo(x,y,lst[1:])
else:
return [lst[0]]+ replaceFirstTwo(x,y,lst[1:])
Here's an alternative using an inner function, which has no restrictions such as the accepted solution:
def replaceFirstTwo(x, y, lst):
def sub(lst, res, count):
if lst:
e = lst[0]
if e == x and count < 2:
return sub(lst[1:], res+[y], count + 1)
else:
return sub(lst[1:], res+[e], count)
else:
return res
return sub(lst, [], 0)

How can I use recursion to find increments of a number in python?

I have the following code, but it just doesn't work when I run it. I would like it to return something like: [5,10,15,20] if the inputed value for n is 4. Any advice is very appreciated.
def MultipleRecursive(n):
multiples=[]
if n==0:
multiples.append(n)
else:
Total=5*MultipleRecursive(n-1)
multiples.append(Total)
return multiples
A trivial version is:
def mr(n):
if n == 0:
return []
return mr(n-1) + [5*n]
You can try this:
def rek(n):
list = []
if n == 0:
return list
else:
list = rek(n-1)
list.append(5*n)
return list
print rek(4)
>>> [5, 10, 15, 20]

Categories

Resources