how will I create this getnext function from this my suedocode - python-3.x

help me how will I create the getnext function
def getnext(atable, currind):
"""
Given a list of lists, 'atable', and a list of indices one for each row in atable, 'currind',
getnext changes currind in place to make it point to the "next" element in atable.
It returns True if the change was successful, otherwise False.
It also returns False if at least one index points outside atable,
but the last element in currind, that is allowed to be -1 to make it possible
to return pointers to the first element in atable.
Example: atable = [['a', 'b', 'c'], ['d'], ['e', 'f', 'g', 'h'], ['i', 'j']]
currind = [2, 0, 1, 0], points to ['c', 'd', 'f', 'i'].
getnext(atable, currind) returns True and currind becomes:
currind == [2, 0, 1, 1] pointing to ['c', 'd', 'f', 'j'].
If you call again getnext(atable, currind) it returns True and currind becomes:
currind == [2, 0, 2, 0] pointing to ['c', 'd', 'g', 'i'].
If currind were [2, 0, 3, 2], getnext(atable, currind) would return False.
To print the whole atable in order:
currind = [0 for _ in atable]
currind[-1] = -1
while getnext(atable, currind):
print([atable[r][c] for r, c in enumerate(currind)])
"""

Related

How can I separate list of items into numbers, upper & lower case lists and then make a dictionary off these three lists?

for ex.
lst = [2,'j','K','o',6,'x',5,'A',3.2]
I want 3 lists in the form
numbers = [2, 3.2, 5, 6],
uppercase = ['A', 'K'],
lowercase = ['j', 'o', 'x']
I wish to change them into a dictionary of the form
{'numbers': [2, 3.2, 5, 6],
'uppercase': ['A', 'K'],
'lowercase': ['j', 'o', 'x']
how can I achieve this? any help will be appreciated
This is a solution to the problem:
lst = [2,'j','K','o',6,'x',5,'A',3.2]
# get the numbers
numbers = [x for x in lst if type(x)==int or type(x)==float ]
# get the strings
strings = [x for x in lst if type(x)==str]
# get the uppers
upper = [x for x in strings if x.isupper()==True]
# get the lowers
lower = [x for x in strings if x.islower()==True]
# now put into a dict
d = {
'numbers':numbers,
'upper':upper,
'lower':lower
}
# this is the answer as a dict
print(d)
# here there are deperately
print(numbers)
print(upper)
print(lower)
result:
{'numbers': [2, 6, 5, 3.2], 'upper': ['K', 'A'], 'lower': ['j', 'o', 'x']}
And the lists:
[2, 6, 5, 3.2]
['K', 'A']
['j', 'o', 'x']

How do I get FOR to work on a list but leaping through it according to another list and how to get it back to the start to keep counting like a loop?

So this is the chromatic_scale = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
I want to form major, minor and other scales based on this.
To form a major scale, for example, I need to leap through the chromatic scale like this: major = [2, 2, 1, 2, 2, 2, 1] (in music, we say "tone, tone, semitone, tone, tone, tone, semitone" where tone means leaping 2 list items and semitone means leaping 1, thus the list)
A practical example: Starting from 'C', I should get ['C', 'D', 'E', 'F', 'G', 'A', 'B', 'C'] (yes, it should loop back to 'C' at the end).
1 - I thought of doing it with FOR but how do I get FOR to work on a list (chromatic) but leaping through it according to another list (major)?
2 - And if I start from 'A', for instance, how to get it back to the beginning to keep counting?
At the end, I managed to do it but I used WHILE instead of FOR.
chromatic = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B',
'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
def major(tom):
major_scale = [2, 2, 1, 2, 2, 2, 1]
step = 0
t = chromatic.index(tom)
m = []
while len(m) < 8:
m.append(chromatic[t])
if len(m) == 8:
break
t += major_scale[step]
step += 1
return m
x = major('D')
print(x)
Thank you everyone!

Python Object Referencing Workaround

Consider the code below:
outer_list = ['a', 'b', 0]
inner_list = [1, 2, 3]
final = []
for item in inner_list:
outer_list[-1] = item
final.append(outer_list)
print(final)
with output : [['a', 'b', 3], ['a', 'b', 3], ['a', 'b', 3]]
My intended output is: [['a', 'b', 1], ['a', 'b', 2], ['a', 'b', 3]]
I understand this has to do with the fact that Python uses object referencing but i cant seem to find a way around this.
Anyone with a solution or alternative i'd appreciate
Yes you're right. Your assignment at line 6 modifies list outer_list and your append call add references to that list in final. You can work on a copy of outer_list to get your result :
outer_list = ['a', 'b', 0]
inner_list = [1, 2, 3]
final = []
for item in inner_list:
l = outer_list.copy()
l[-1] = item
final.append(l)
print(final)
List concatenation returns a new list object.
outer_list = ['a', 'b']
inner_list = [1, 2, 3]
print([outer_list + [item] for item in inner_list])
You could also achieve using map
print(list(map(lambda item: outer_list + [item], inner_list )))

How do I order double list of elements of this type: [[1,2,3], [a,b,c]]?

I have a double list of this type: dl = [[13, 22, 41], ['c', 'b', 'a']], in which, each element dl[0][i] belongs a value in dl[1][i] (with the same index). How can I sort my list using dl[0] values as my order criteria, maintainning linked both sublists? Sublist are kind of 'linked data', so the previous dl[0][i] and dl[1][i] values must match their index after sorting the parent entire list, using as sorting criteria, the first sublist values
I expect something like:
input: dl = [ [14,22,7,17], ['K', 'M', 'F','A'] ]
output: dl = [ [7, 14, 17, 22], ['F', 'K', 'A', 'M'] ]
This was way too much fun to write. I don't doubt that this function can be greatly improved, but this is what I've gotten in a very short amount of time and should get you started.
I've included some tests just so you can verify that this does indeed do what you want.
from unittest import TestCase, main
def sort_by_first(data):
sorted_data = []
for seq in data:
zipped_to_first = zip(data[0], seq)
sorted_by_first = sorted(zipped_to_first)
unzipped_data = zip(*sorted_by_first)
sorted_data.append(list(tuple(unzipped_data)[1]))
return sorted_data
class SortByFirstTestCase(TestCase):
def test_sort(self):
output_1 = sort_by_first([[1, 3, 5, 2, 4], ['a', 'b', 'c', 'd', 'e']])
self.assertEqual(output_1, [[1, 2, 3, 4, 5], ['a', 'd', 'b', 'e', 'c']])
output_2 = sort_by_first([[9, 1, 5], [21, 22, 23], ['spam', 'foo', 'bar']])
self.assertEqual(output_2, [[1, 5, 9], [22, 23, 21], ['foo', 'bar', 'spam']])
if __name__ == '__main__':
main()
Updated for what you're looking for, selection sort but added another line to switch for the second list to match the first.
for i in range(len(dl[0])):
min_idx = i
for j in range(i+1, len(dl[0])):
if dl[0][min_idx] > dl[0][j]:
min_idx = j
dl[0][i], dl[0][min_idx] = dl[0][min_idx], dl[0][i]
dl[1][i], dl[1][min_idx] = dl[1][min_idx], dl[1][i]
You can try solving this with a for loop also:
dl = [ [3,2,1], ['c', 'b', 'a'] ]
for i in range(0,len(dl)):
dl[i].sort()
print(dl)

How to filter similar edges in a list?

I have a list which contains all the edges of an undirected weighted graph.I further sorted it in increasing order of their edge weights.
The list is as follows
lis = [['B', 'C', 1], ['C', 'B', 1], ['B', 'A', 2], ['C', 'A', 2], ['A', 'C', 2], ['A', 'B', 2], ['D', 'C', 3], ['C', 'D', 3], ['B', 'D', 5], ['D', 'B', 5]]
Now in the list, ['B', 'C', 1], ['C', 'B', 1] means the same thing.That is an edge BC has a weight of 1 and edge CB has a weight of 1.Similarly we have edges AB, BA and so on in the list.
How do I keep only one of the two edges and not both since they both mean the same thing.So for ['B', 'C', 1], ['C', 'B', 1], I only want to keep say ['B', 'C', 1].How do I do that?
I found a similar question but I am not really sure how to implement it in my case.
Removing duplicate edges from graph in Python list
I tried to implement the solution posted in the link for my situtation but doesn't work
def normalize(t):
[n1, n2, dist] = t
if n1 < n2:
return t
else:
return [n2, n1, dist]
unique_edges = set(map(normalize, lis))
Simply sort each item and remove duplicates:
>>> lis = sorted([sorted(item) for item in lis])
>>> [lis[i][::-1] for i in range(len(lis)) if i == 0 or lis[i] != lis[i-1]]
[['C', 'B', 1], ['B', 'A', 2], ['C', 'A', 2], ['D', 'C', 3], ['D', 'B', 5]]

Resources