List of lists into table (Row, Column) - arrays

I have inspiration with loop pattern diamond. The pattern diamond is replaced with the list of the lists like this code. Actually, I already print the actual result is not looked to row and column. the expected result is looked similar to the actual result. Dummy Coords (dum_coords) is represented the data will put into a table (row, column).
How to rule to change value None or value inside the list the value less than 3. I can replace the value to a new list. Which one better-using value or index of the list.
Please I need advice and suggestions
python, pattern diamond, list of lists
l = 4
dum_coords = [None, [[1,2,3],6,7,8], [9,[1,2,3],11,12], [[1,2,3],14,15,16]]
for i in range(l):
print("row:{}, {}".format(i, dumy_coords[i]))
actual result:
row:0>> [None]
row:1>> [[1,2,3],6,7,8]
row:2>> [9,[1,2,3],11,12]
row:3>> [[1,2,3],14,15,16]
expected result:
row:0>> [[None],[None],[None],[None]]
row:1>> [[None],[1,2,3],6,7]
row:2>> [9,[1,2,3],11,[1,2,3]]
row:3>> [[1,2,3],14,15,0]
Updated Question:
#Shishir Naresha suggestion me his code. for the result is similar to the expected result. But, need more than it. I can replace the value None or not None.
this my code and added with #Shishir Naresha's code
dum_fish_space = [None]*5
dum_fish_pop = [None]*3
dum_fish_preying = [{"current":random.uniform(0,1)*2}]
dum_fish_following = [{"current":random.uniform(0,1)*1,"target":random.uniform(0,1)}]
dum_fish_swarming = [{"current":random.uniform(0,1)}]
dum_fish_randoming = [{"current":random.uniform(0,1)*3}]
dum_fish_battle = []
idxrange = []
new_idxrange = []
for i in range(len(dum_fish_pop)):
temp = random.randrange(len(dum_fish_space))
idxrange.append(random.randrange(len(dum_fish_space)))
if temp is not idxrange:
new_idxrange.append(temp)
l = 4
dumy_coords = [None, [[1, 2, 3], 6, 7], [9, [1, 2, 3], 11, 12], [[1, 2, 3], 14, 15, 16]]
for i in range(l):
if dumy_coords[i] is None:
print("row:{}, {}".format(i, [None] * l))
else:
if len(dumy_coords[i]) < l:
dif = l - len(dumy_coords[i])
print("row:{}, {}".format(i, [None] * dif + dumy_coords[i]))
else:
print("row:{}, {}".format(i, dumy_coords[i]))
I thought is a value inside the table will change based on the index of list of the lists, I expected the result will be alike
expected result before changing the value:
row:0>> [[None],[None],[None],[None]]
row:1>> [[None],[1,2,3],6,7]
row:2>> [9,[1,2,3],11,[1,2,3]]
row:3>> [[1,2,3],14,15,0]
expected result after change the value:
row:0>> [[1,2,3],[1,2,3],[None],[None]]
row:1>> [[None],[None],6,7]
row:2>> [9,[None],11,[1,2,3]]
row:3>> [[1,2,3],14,15,0]

Try the below code. I hope this will help.
l = 4
dumy_coords = [None, [[1,2,3],6,7], [9,[1,2,3],11,12], [[1,2,3],14,15,16]]
for i in range(l):
if dumy_coords[i] is None:
print("row:{}, {}".format(i, [None]*l))
else:
if len(dumy_coords[i]) < l:
dif = l-len(dumy_coords[i])
print("row:{}, {}".format(i, [None]*dif+dumy_coords[i]))
else:
print("row:{}, {}".format(i, dumy_coords[i]))
Output will be as shown below:
row:0, [None, None, None, None]
row:1, [None, [1, 2, 3], 6, 7]
row:2, [9, [1, 2, 3], 11, 12]
row:3, [[1, 2, 3], 14, 15, 16]

Related

Merge Two Sorted Arrays in Python

I have two sorted arrays
array1 = [0, 3, 4, 31]
array2 = [4, 6, 30]
I try to sort these arrays by using the code below:
def mergeSortedArray(array1, array2):
if not len(array1):
return array2
if not len(array2):
return array1
mergedArray = []
array1Item = array1[0]
array2Item = array2[0]
i = 0
j = 0
while (i < len(array1)) and (j < len(array2)):
if array1Item < array2Item:
mergedArray.append(array1Item)
array1Item = array1[i + 1]
i += 1
else:
mergedArray.append(array2Item)
print(j)
array2Item = array2[j + 1]
j += 1
return mergedArray
print(mergeSortedArray([0, 3, 4, 31], [4, 6, 30]))
But the terminal keep telling me that:
line 26, in mergeSortedArray
array2Item = array2[j + 1]
IndexError: list index out of range
I wonder which part I did wrong! Can someone explain to me? plz~
BTW, what is the syntactically cleanest way to accomplish this?
Make use of Python's features, such as merging two lists with the + operator. Then, simply sort the new list.
>>> array1 = [0, 3, 4, 31]
>>> array2 = [4, 6, 30]
>>> merged_array = array1 + array2
>>> merged_array.sort()
>>> merged_array
[0, 3, 4, 4, 6, 30, 31]

How to combine two array into a list which have a inner-list?

I had two list:
a=[0,0,0,1,1,1,1,2,2]
b=[2,5,12,2,3,8,9,4,6]
And I wanted to get:
c=[[0,2,5,12],[1,2,3,8,9],[2,4,6]]
A and b correlated to each other, a[i] related to b[i], when the value in a change like 0 to 1, 12 end in the first inner-list of c.
I tried it with if else statement but it failed
How to get c in python?
This code produces c in a good enough way (provided a and b are always adjusted in the same way as in the example):
a=[0,0,0,1,1,1,1,2,2]
b=[2,5,12,2,3,8,9,4,6]
c = []
i = 0
while i < len(a):
d = a.count(a[i])
c.append([a[i]] + b[i:i + d])
i += d
print(c) # ==> [[0, 2, 5, 12], [1, 2, 3, 8, 9], [2, 4, 6]]
We can zip the lists, group by first value from a, and make lists with the second:
from itertools import groupby
from operator import itemgetter
a=[0,0,0,1,1,1,1,2,2]
b=[2,5,12,2,3,8,9,4,6]
[list(map(itemgetter(1), group)) for _, group in groupby(zip(a, b), key=itemgetter(0))]
#[[2, 5, 12], [2, 3, 8, 9], [4, 6]]
Similar to #Thierry Lathuille's answer, but does actually prepend the keys to the sub lists as requested by OP:
import itertools as it
ib = iter(b)
[[k, *(next(ib) for _ in gr)] for k, gr in it.groupby(a)]
# [[0, 2, 5, 12], [1, 2, 3, 8, 9], [2, 4, 6]]
Here's my simple solution. Notice that you are splitting the list by by the counts of elemets in the list a. deque is used for popping elements in O(1) time from the left.
import itertools
from collections import Counter, deque
a = [0,0,0,1,1,1,1,2,2]
b = deque([2,5,12,2,3,8,9,4,6])
c = Counter(a)
new_list=[]
for x in c:
new_list.append([x]+[b.popleft() for i in range(a[x])])

Ruby save modified array in a variable without it changing the original array

I'd like to save in two variables the values of an array excluding the first and last elements.
For example:
prices = [9, 3, 5, 2, 1]
The elements I need are:
prices_excl_first = [3, 5, 2, 1]
prices_excl_last = [9, 3, 5, 2]
I figured out how to remove an element from an array a few ways, including slicing off the value by passing its index to the slice method like so:
first_price = prices.slice(0)
last_price = prices.slice(-1)
We could then save the modified arrays into variables:
array_except_first_price = prices.delete(first_price) #=> [3, 5, 2, 1]
array_except_last_index = prices.delete(last_price) #=> [3, 5, 2]
There are two problems with this:
array_except_last_index doesn't contain the first element now
I still need access to the full, original array prices later
So essentially, how can I just temporarily modify the elements in the array when necessary in the problem?
Slicing and dropping elements from array permanently affect the array.
Ruby has first and last to copy just the first and last elements.
Ask for the first and last prices.size-1 elements.
prices = [9, 3, 5, 2, 1]
except_first = prices.last(prices.size-1)
except_last = prices.first(prices.size-1)
#Schwern's answer is probably the best you can get. Here's the second best:
prices = [9, 3, 5, 2, 1]
prices[1..-1] # => [3, 5, 2, 1]
prices[0..-2] # => [9, 3, 5, 2]
Or drop/take (which more closely map to the wording of your question).
prices.drop(1) # => [3, 5, 2, 1]
prices.take(prices.size-1) # => [9, 3, 5, 2]
You could use each_cons:
a, b = prices.each_cons(prices.size - 1).to_a
a #=> [9, 3, 5, 2]
b #=> [3, 5, 2, 1]
Splat it.
*a, d = prices
c, *b = prices
a #=> [9, 3, 5, 2]
b #=> [3, 5, 2, 1]
You can use dup to duplicate the array before performing destructive operations.
prices = [9, 3, 5, 2, 1]
except_first = prices.dup
except_first.delete_at 0
except_last = prices.dup
except_last.delete_at -1
This does end up duplicating the array a couple of times. If you're dealing with large arrays, this may be a problem.

Divide array into subarray

I want to create two sub-arrays from this array:
a = [0, 1, 2, 3, 4, 5, 6]
This array will not always contain the same number of elements because it depends on the user input.
For example, in some occasions it'll be:
a = [0, 5]
or:
a = [5, 6, 4]
I want to divide the array into two subarrays. The first one will contain numbers from 1 to 4 (inclusive) and the second one will contain 0, 5 and 6.
In the first example, it will be:
a = [0, 1, 2, 3, 4, 5, 6]
sub_array1 = [1, 2, 3, 4]
sub_array2 = [0, 5, 6]
In the second:
a = [0, 5]
sub_array1 = []
sub_array2 = [5]
In the third:
a = [5, 6, 4]
sub_array1 = [4]
sub_array2 = [5, 6]
and so on, depending on the user input.
How can I do this?
First thing that comes to mind is Enumerable#partition.
sub_array1, sub_array2 = [0,1,2,3,4,5,6].partition {|x| (1..4).include? x }
=> [[1,2,3,4], [0,5,6]]
if you have two conditions (I mean if 0,5,6 are an actual condition and not the excluded set) I think that a double iteration wouldn't hurt
a = [0,1,2,3,4,5,6]
sub_array1 = a.select { |x| (1..4).include? x }
sub_array2 = a.select { |x| [0,5,6].include? x }
You can try something like this:
[0,1,2,3,4,5,6].group_by{|x| [0,5,6].include? x}
The result will be a hash:
{true=>[0, 5, 6], false=>[1, 2, 3, 4]}
In the second case:
[0,5].group_by{|x| [0,5,6].include? x}
The result will be:
{true=>[0, 5]}

How do I find the complement of an array?

If I have a sorted array of numerical values such as Double, Integer, and Time, what is the general logic to finding a complement?
Over my CS career in college, I've gotten better of understanding complements and edge cases for ranges. As I help students whose skill levels and understanding match mine when I wrote this, I need help finding a generalized way to convey this concept to them for singular elements and ranges.
Try something like this:
def complement(l, universe=None):
"""
Return the complement of a list of integers, as compared to
a given "universe" set. If no universe is specified,
consider the universe to be all integers between
the minimum and maximum values of the given list.
"""
if universe is not None:
universe = set(universe)
else:
universe = set(range(min(l), max(l)+1))
return sorted(universe - set(l))
then
l = [1,3,5,7,10]
complement(l)
yields:
[2, 4, 6, 8, 9]
Or you can specify your own universe:
complement(l, range(12))
yields:
[0, 2, 4, 6, 8, 9, 11]
To add another option - using a data type that is always useful to learn about, for these types of operations.
a = set([1, 3, 5, 7, 10])
b = set(range(1, 11))
c = sorted(list(b.symmetric_difference(a)))
print(c)
[2, 4, 6, 8, 9]
>>> nums = [1, 3, 5, 7, 10]
>>> [n + ((n&1)*2-1) for n in nums]
[2, 4, 6, 8, 9]
The easiest way is to iterate from the beginning of your list to the second to last element. Set j equal to the index + 1. While j is less than the next number in your list, append it to your list of complements and increment it.
# find the skipped numbers in a list sorted in ascending order
def getSkippedNumbers (arr):
complement = []
for i in xrange(0, len(arr) - 1):
j = arr[i] + 1
while j < arr[i + 1]:
complement.append(j)
j += 1
return complement
test = [1, 3, 5, 7, 10]
print getSkippedNumbers(test) # returns [2, 4, 6, 8, 9]
You can find the compliment of two lists using list comprehension. Here we are taking the complement of a set x with respect to a set y:
>>> x = [1, 3, 5, 7, 10]
>>> y = [1, 2, 3, 4, 8, 9, 20]
>>> z = [n for n in x if not n in y]
>>> z
[5, 7, 10]
>>>

Resources