Reconstruct an array by replacing every element with a[[i-1]%K] - Python

0 votes
I've recently started learning python and I've got an assignment to complete. One of the questions was to reconstruct an array by replacing every element with a[[i-1]%K]. Can somebody help me with this? Thanks you
Jun 14 in Python by Varsha

edited Jun 17 by Kalgi 29 views

1 answer to this question.

0 votes

Hey varsha, Have a look at this one:

def construct(s, k, a):
    index = 0
    # Finding the index which is not -1
    for i in range(s):
        if (a[i]!=-1):
            index = i
            break
    # Calculating the values of the indexes index-1 to 0
    for i in range(index-1, -1, -1):
        if (a[i]==-1):
            a[i]=(a[i + 1]-1 + k)% k
    # Calculating the values of the indexes index + 1 to n
    for i in range(index + 1, s):
        if(a[i]==-1):
            a[i]=(a[i-1]+1)% k
            print(a)
# Driver code
s, k = 6, 7
a =[1, 2, 3, 4, 5, 6]
construct(s, k, a)

It should give you the following output:

answered Jun 14 by Miya

Related Questions In Python

0 votes
1 answer

How do I remove an element from a list by index in Python?

You can use the pop() method to ...READ MORE

answered Jun 21 in Python by Nisa
• 1,090 points
38 views
0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
73 views
0 votes
1 answer

How can I define a multidimensional array in python using ctype?

Here's one quick-and-dirty method: >>> A = ((ctypes.c_float ...READ MORE

answered Oct 9, 2018 in Python by ariaholic
• 7,340 points
300 views
0 votes
1 answer

How do I generate some random numbers with a distribution using Python?

scipy.stats.rv_discrete is what you ned IMHO. You can supply ...READ MORE

answered Oct 31, 2018 in Python by Anirudh
• 2,070 points

edited Dec 14, 2018 by Anirudh 133 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 215 views
+4 votes
6 answers
0 votes
1 answer

how do I check the length of an array in a python program?

lets say we have a list mylist = ...READ MORE

answered Mar 12 in Python by Mohammad
• 3,060 points
38 views
0 votes
1 answer

In Python, how do I read a file line-by-line into a list?

with open(fname) as f:     content = f.readlines() # you ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 13,160 points
113 views