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))
Related
I'm trying to complete "Two Sum", which goes as such:
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2).
Efficiency of my code aside, this is what I have so far:
def two_sum(numbers, target):
for i in numbers:
for t in numbers:
if i + t == target:
if numbers.index(i) != numbers.index(t):
return (numbers.index(i), numbers.index(t))
return False
It works for inputs such as:
>>> two_sum([1,2,3,4,5,6,7,8,9,10], 11)
(0, 9)
But when I try a list of numbers that have recurring numbers that add up to the target, the code doesn't work:
>>> two_sum([2, 2], 4)
False
The code, for some reason that I cannot figure out, does not reach index [1] of the list, and thus returns False.
Why is that?
The list method index() always returns the first occurence of an item in a list, so numbers.index(i) != numbers.index(t) evaluates to 1 != 1 which is False.
You should use the builtin enumerate() to store the indices while looping over the list.
def two_sum(numbers, target):
for i, number_a in enumerate(numbers):
for j, number_b in enumerate(numbers):
if number_a + number_b == target and i != j:
return (i, j)
return False
'''
return will break the loop and come out of function, so first you need to complete the cycle, store the result in list as you cant write to tuple,
once your loop gets completed convert list to tuple and return
'''
def two_sum(numbers, target):
result = []
for i in numbers:
for t in numbers:
if (i + t == target) and (numbers.index(i) != numbers.index(t)):
result.append(i)
result.append(t)
if (len(result)> 0):
return tuple(result)
else:
return False
Your code looks fine except this part:
if numbers.index(i) != numbers.index(t):
return (numbers.index(i), numbers.index(t))
return False
Because the index method returns only the first occurrence of a value, i and t are always the same. It will always return false. The index of the value 2 is always 0 in the list even though there is another 2 at index 1.
Source: https://www.w3schools.com/python/ref_list_index.asp
What you want to do is this:
def two_sum(numbers, target):
i_index = 0
t_index = 0
for i in numbers:
for t in numbers:
if i + t == target:
if i_index != t_index:
return (i_index, t_index)
t_index +=1
i_index +=1
return False
This way the index is not associated with the value
def pairs_sum_to_target(list1, list2, target):
'''
This function is about a game: it accepts a target integer named target and
two lists of integers (list1 and list2).
Then this function should return all pairs of indices in the form [i,j]
where list1[i] + list[j] == target.
To summarize, the function returns the pairs of indices where the sum of
their values equals to target.
Important: in this game list1 and list2 will always have the same number of
elements and returns the pairs in that order.
'''
pairs = [] #make a list, which is empty in the beginning. But store the sum pairs == target value.
#loop for all indices in list1 while looping all the same indices in list2 and comparing if the sum == target variable.
for i, value1 in enumerate (list1):
for j, value2 in enumerate(list2):
if value1 + value2 == target: ## if the value of element at indice i + value of element at indice j == target, then append the pairs to list pairs []- in order.
pairs.append(i,j)
return pairs
Simple Input #1
"""This is one example of input for list1, list2, and target. In order to properly test this function"""
list1 = [1,-2,4,5,9]
list2 = [4,2,-4,-4,0]
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.
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).
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)]
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