generating a list but only the first index showed - python-3.x

i want to generate a list, in which only odd number get factorial application. However only the first number will be execute, can you help me? Thanks.
def factorial(x):
if x<=0:
return 1
else:
return x*factorial(x-1)
def odd(x):
if x%2 ==0:
return x
else:
return factorial(x)
def apply_if(factorial,odd,xs):
#xs is a list
i=0
mlst=[]
for x in xs:
if i<len(xs):
return odd(xs[i])
i+=1
mlst=mlst.append(odd(x))
return mlst

You should change apply_if function.
def apply_if(factorial,odd,xs):
mlst=[]
for x in xs:
mlst.append(odd(x))
return mlst
Because at first iteration of loop i will always be smaller than lenght of ws list (if it's not empty). Also append method doesn't return anything so you shouldn't use a = a.append() as it just appends element to given list.

Related

Returning multiple value in python return function

My function prints the the index of every element in list that is divided by 2 in a given list. I want to know if there is a way to return all the indexes rather than printing?
def printEvenIndex(referenceTuple):
for i in referenceTuple:
if i % 2 ==0:
indexOfEvenIntegers = referenceTuple.index(i)
print(indexOfEvenIntegers)
return indexOfEvenIntegers
referenceTuple = (6,5,3,4,1)
print(printEvenIndex(referenceTuple))
Right now print statement prints 0 ,3 which is valid.
But return function is returning 3 only. Is there a way to tell return function to return every element that is divisible by 2? I want to return all the index rather than print it.
Just create a list and append your indexes there:
def readEvenIndexes(referenceTuple):
""" Named it readEventIndexes, as we are not printing anymore """
indexes = []
for index, i in enumerate(referenceTuple):
if i % 2 ==0:
indexes.append(index)
return indexes
referenceTuple = (6,5,3,4,1)
print(readEvenIndexes(referenceTuple))

Incorporate a while loop in a function in Python

Very new to any kind of coding. I would like to write a function that will return the elements of a numeric list, up to the first even number. For example, if the list is [1,5,7,8,9] it will return [1,5,7]
I know the below is not correct, but I am having trouble passing the list into the while loop.
def iter_up_to_even(num_lst):
i=0
new_lst=[]
while i < len(num_lst):
if i%2!=0:
new_lst.append(num_lst)
i=i+1
if i %2==0:
break
return new_lst
Looks like you might have some indentation issues. Try this solution:
def iter_up_to_even(num_list):
to_return = []
current_index = 0 if len(num_list) > 0 else len(num_list)
while current_index < len(num_list):
if num_list[current_index] % 2 == 1:
to_return.append(num_list[current_index])
else:
break
current_index += 1
return to_return
Explanation
We start with an empty list to_return, which we will return at the end of our function. Next, we iterate through each item in the input list num_list. If the input list num_list is empty to begin with, we don't even enter the while loop (see Line 3). If the item is odd, we append it to our to_return list. If it's even, we break from our loop and return to_return.
In addition, you should compare values in the list (e.g. num_list[i]), rather than the current index in the list (e.g. i).

Need help writing a function which returns a dictionary with the keys as recursive digit sums

So I have written a function which calculates the sum of the digits when a number is input to the function. Now I am trying to write another function which would return a dictionary with the values from my digitsum function as the keys and the values would be how many times the count of that specific digitsum has occurred. Any ideas on how to go about writing the second function?
def digitsum(x):
if x < 10:
return x
else:
return (x%10) + digitsum(x//10)
def digitsumdictionary(lnum=0, hnum=100):
L =[digitsum(num) for num in range(100)]
counter = Counter(L).items()
return counter
Digitsum function is called depending on the length of the number.
You can simply find it by using len(list(str(num))). But if you want to count as the function calls itself, Then try this,
def digitsum(x, count=1):
if x < 10:
return { x : count }
else:
return {(x%10) + int(list(digitsum(x//10 , count+1).keys())[0]) : int(list(digitsum(x//10 , count+1).values())[0])}
Setting the count to 1 or 0 initially, includes or excludes the first call respectively.
The below code returns a list of dictionaries of the desired output.
[digitsum(i) for i in range(10)]

Python - Create a recursion function

my question is basically this: Create a recursion function that takes a nested list as a
parameter and returns the sub-list that has minimum difference between its maximum and minimum elements.
For example: Function should return [1,2] for input [[1,199,59],[1,2],[3,8]]
I searched Google and stackoverflow, but i could not find this specific example.
What i would like to get help is with iteration. I want to, using recursion, iterate over each sub-list(can be as many as possible). I have achieved this with a for loop, but i cannot grasp the idea of iteration by using recursion method.
So far, i have this:
def sublist(mylist):
if len(mylist) == 0:
return []
elif len(mylist) == 1:
return mylist
else:
a = (mylist[0][0]) - (mylist[0][-1])
if a < sublist(mylist[1:]):
return mylist[0]
sublist([[1,199,58],[1,2],[3,8]])
This part, ( sublist(mylist[1:]) ) i know is clearly wrong. I'm trying to compare the value a, with the values from the mylist[1:]. I would appreciate much advice here.
Updated:
def differences(mylist):
diff = max(mylist) - min(mylist)
return diff
def sublist(nestedlist):
if len(nestedlist) == 1:
return nestedlist[0]
else:
if differences(nestedlist[0]) < differences(sublist(nestedlist[1:])):
return nestedlist[0]
else:
return sublist(nestedlist[1:])
print(sublist([[1,199,59],[1,2],[3,8]]))
i am assuming that you want to use recursion for the first level of the list. So, without giving you the code 100%, you have to do something like that:
1) create a method e.g diferences(list) that calculates the differences of a list and returns a list with the parameter list and the min difference i.e differences([1,2]) should return [1, [1,2]]. call it once on the first sublist i.e min = differences(mylist[0])
2) create your sublist method like this:
def sublist(initial_list):
# 1) call differences() method for the first sublist of the 'initial_list'
# 2) update 'min' with differences(initial_list[0])if differences(inilitial_list[0])[0] < min[0];
# 3) call sublist() again now removing the sublist you checked before from the arguement
# 4) (the following should be at the start of your sublist() method)
if len(initial_list) = 1:
if differences(initial_list) < min:
return initial_list
else: return min[1]
Hope that helps

k way merge sort divide and conquer

from math import ceil
def merge(all_lst):
sorted_lst = []
while all_lst:
min_value,index = all_lst[0][0],0
for lst in all_lst:
if lst[0]<min_value:
min_value = lst[0]
index = all_lst.index(lst)
sorted_lst.append(min_value)
all_lst[index].pop(0)
if not all_lst[index]:
all_lst.remove(all_lst[index])
return sorted_lst
def merge_sort(lst, k):
def split(lst):
split_lst = []
j = ceil(len(lst)/k) if len(lst)>=k else 1
for i in range(0,len(lst),j):
split_lst.append(lst[i:i+j])
return split_lst
lst=split(lst)
if len(lst[0])==1:
return lst
else:
for i in range(len(lst)):
lst[i]=merge(merge_sort(lst[i],k))
return merge(lst)
Above is my code for k-way merge sort. Basically what it does is split the list into k smaller list by calling the split function until each sublist in the list is a single element. Then the list containing sublists will be merged into one single list.
My code works fine when splitting is done twice. (eg.[3,6,8,5,2,1,4,7] -> [3,6,8],[5,2,1],[4,7] -> [3],[6],[8],[5],[2],[1],[4],[7]). But when the splitting is done more than twice, (eg,[3,6,8,5,2,1,4,7] -> [3,6,8,5],[2,1,4,7] -> [3,6],[8,5],[2,1],[4,7] -> [3],[6],[8],[5],[2],[1],[4],[7]), the code will fail. Can anyone help find me find out what goes wrong in my code? Thanks in advance.
I believe the problem you're having is that merge_sort sometimes returns a flattened list and other times returns a list of lists. You should probably return a flat list in all cases. There's some other cruft: You don't need split to be its own function, since you only call it the one time.
Here's a greatly simplified version of your code:
def merge_sort(lst, k):
if len(lst) == 1: # simpler base case
return lst
j = ceil(len(lst)/k) # no need to check for k < len(lst) (ceil handles it)
#split and recursively sort in one step
lst = [merge_sort(lst[i:i+j], k) for i in range(0, len(lst), j)]
return merge(lst) # always return a merged list (never a list of lists)

Resources