I have this task building a code using recursion. The task is taking a list who can have an infinite amount of lists inside it and making it one list.
This is so far what I have:
def flat_list(array):
new_array =[]
for i in range(0,len(array)):
if len(str(array[i])) > 1:
flat_list(array[i:i+1])
else:
new_array += array[i:len(str(array))-1]
return new_array
These are the tests it needs to pass:
assert flat_list([1, 2, 3]) == [1, 2, 3]
assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4]
assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7]
assert flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1]
Mine returns this:
flat_list([1, [2, 2, 2], 4])
my result: [1,[2,2,2],4]
right answer: [1,2,2,2,4]
I think my problem is with creating a new local variable of the new_array at each entry, How can I return one list with no other lists inside it?
This task is without using numpy, but if you can also show me how it can be done with numpy it will really educate me. :)
Thank you for answering
Try this:
def flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
return S[:1] + flatten(S[1:])
How it works:
1. The list is passed as an argument to a recursive function to flatten the list.
2. In the function, if the list is empty, the list is returned.
3. Otherwise the function is recursively called with the sublists as the parameters until the entire list is flattened.
I suggest you the following suggestion: it iterates over the list and if the encountered item is a list, then it recursively flattens it before appending it to the resulting flattened list:
def flat_list(aList):
result = []
for i in aList:
if isinstance(i, list):
result += flat_list(i)
else:
result.append(i)
return result
Related
I am trying to get 25 Numbers to put them in a 2D list/array but whenever i try to get the index of the item, I'm always facing a valueError.
What i tried.
I have tried using a for loop with the enumerate() function to get the specfic Item which is (1).
I have also tried using the .index() method but also with that I was faced with a ValueError: 1 is not in the list. Which made me confused as to why the code isn't working.
mylist = [list(map(int, input().split())),
list(map(int, input().split())),
list(map(int, input().split())),
list(map(int, input().split())),
list(map(int, input().split())),]
print(mylist)
print(mylist.index(1))
Here is one approach to consider:
myList = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [12, 3, 5, 6, 7], [2, 4, 5, 6, 7], [2, 4, 3, 6, 2]]
def index_2d(input_list, value):
for i, row in enumerate(input_list):
try:
return (i, row.index(value))
except ValueError:
continue
# You can also raise ValueError here instead of implicit return (un-comment the next line)
# raise ValueError(f'{value} is not in the list')
Output:
>>> print(myList)
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [12, 3, 5, 6, 7], [2, 4, 5, 6, 7], [2, 4, 3, 6, 2]]
>>> print(index_2d(myList, 12))
(2, 0)
>>> print(index_2d(myList, 11))
None
Explanation:
We accept the 2d-list and a value we are trying to check. Then use enumerate (to keep track of the index of the main array). We then use index() at each row (list in the main array) to check if the value belongs there, if not (ValueError exception got raised) we simply move to the next row and repeat. But if index() resolves, we return a tuple of the index of the list inside the main list (from the enumerate()) and the index inside the second list or row.
I want to make a function that takes a list of integers and replaces the elements in the list with their respective squares.
I tried reassigning every element by virtue of its position (index) in the list, but for some reason the second element in the list gets squared twice.
def square_list(list1):
for i in list1:
list1[list1.index(i)] = i**2
print(list1)
square_list([1, 2, 3, 4, 5])
I expect the printed list to be [1, 4, 9, 16, 25] since the list I'm testing the function with is [1, 2, 3, 4, 5].
If a function is required to square list elements in-place, use it:
def square_list(list_1):
for i in range(len(list_1)):
list_1[i] = list_1[i]**2
my_list = [1, 2, 3, 4, 5]
square_list(my_list)
print(my_list)
Since the function doesn't return anything, square_list([1, 2, 3, 4, 5]) is useless.
Python's map built-in function is good for this, so you don't really have to write your own function.
l = [1, 2, 3, 4, 5]
l = list(map(lambda x: x**2, l))
Let us say we have a list of integers:
list = [6, 4, 1, 4, 4, 4, 4, 4, 2, 1]
I now wrote a function which returns another list with all the integers from the list above without repeats.
def no_repeats(s):
new_list = []
for number in s:
if new_list.count(number) < 1:
new_list.append(number)
return(new_list)
The new_list returns [6, 4, 1, 2] which is good! My question is how I would now write two similar functions:
A function clean(s) which does not return a new list like the function above, but changes the original list by deleting all the numbers that repeat. Thus, the result has to be the same and the function must not include "return" or create a new list. It must only clean the original list.
A function double(s) which, again, changes the original list (does not return a new list!) but this time, by doubling every number in the original list. Thus, double(list) should change the original list above to:
[6, 6, 4, 4, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 1, 1]
Thank you for all the help!
Removing duplicates inplace without preserving the order:
def no_repeats(L):
L[:] = set(L)
There are several variations possible (preserve order, support non-hashable items, support item that do not define total ordering) e.g., to preserve order:
from collections import OrderedDict
def no_repeats(L):
L[:] = OrderedDict.fromkeys(L)
To double each element's value inplace:
def double(L):
for i in range(len(L)):
L[i] *= 2
To duplicate each element:
def duplicate_elements(L):
L[:] = [x for x in L for _ in range(2)]
>>> def clean(s):
... s[:] = [s[i] for i in range(len(s)) if s[i] not in s[:i]]
...
>>> st = [1, 2, 3, 2, 1]
>>> clean(st)
>>> st
[1, 2, 3]
>>> def double(s):
... s[:] = [s[i//3] for i in range(3*len(s)) if i % 3]
...
>>> st = [1, 2, 3, 2, 1]
>>> double(st)
>>> st
[1, 1, 2, 2, 3, 3, 2, 2, 1, 1]
neither is particularly efficient nor pythonic, yet do address the OP question
def double(s):
... s[:] = [s[i//2] for i in range(2*len(s))]
will also do the trick, with a little less obsfucation
Okay, so I have this function that I need to create and I think the code checker is somehow flawed and I tried manage it but my code still seems to fail
def reversecomp(L):
""" assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
if L == []:
return L
elif type(L) == int:
return L
else:
return reversecomp(L[1:]) + [reversecomp(L[0])]
def run_code(L):
return reversecomp(L)
print(L)
The question states that you need to mutate L. Your code must work when you do this:
L = [[0, 1, 2], [1, 2, 3], [3, 2, 1], [10, -10, 100]]
reversecomp(L)
print(L)
Test: run_code([[0, 1, 2], [1, 2, 3]])
Your output:
[[3, 2, 1], [2, 1, 0]]
Correct output:
[[3, 2, 1], [2, 1, 0]]
None
The spec says "It does not return anything"; your program does.
L is a list of lists of ints
Okay, so why are you checking type(L) == int when type(L) == list is always true, per the specification?
Mutates L
You're not mutating L at all; you're returning a new list. Mutating L means doing something like L[...] = xxx.
It does not return anything.
You shouldn't be using the return keyword at all in reversecomp.
I'm having an issue in groovy trying to figure out how to convert a single item to a list. I have an incoming variable params.contacts, which could be a single value (e.g. 14) or it could be an array of values (e.g. 14, 15). I want to always turn it into a list. Previously, I was simply saying params.contacts.toList(), but this code fails when it's a single item. It would take a value of 14 and divide it into a list of [1, 4].
Is there a simple, elegant way of handling this problem?
One easy way, put it in a list and flatten it:
def asList(orig) {
return [orig].flatten()
}
assert [1, 2, 3, 4] == asList([1, 2, 3, 4])
assert ["foo"] == asList("foo")
assert [1] == asList(1)
One problem with this is that it'll completely flatten things, so it's not a good approach as it'll flatten lists within your list:
assert [[1, 2], [3, 4]] == asList([[1, 2], [3, 4]]) // fails!
Another way would be to use the type system to your advantage:
def asList(Collection orig) {
return orig
}
def asList(orig) {
return [orig]
}
assert [1, 2, 3, 4] == asList([1, 2, 3, 4])
assert ["foo"] == asList("foo")
assert [1] == asList(1)
assert [[1, 2], [3, 4]] == asList([[1, 2], [3, 4]]) // works!
Here, we let the type system do all the heavy lifting for us. If we've already got a collection, just return it. Otherwise, turn it into a list. Tricks like this from Java are still available to us in groovy, and we shouldn't completely throw them out when they're the right thing for the problem.