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, 2019 in Python by Varsha

edited Jun 17, 2019 by Kalgi 379 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
    # 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):
            a[i]=(a[i-1]+1)% k
# 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, 2019 by Miya

Related Questions In Python

0 votes
2 answers

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

Delete the List and its element: We have ...READ MORE

answered Jun 7 in Python by sahil
• 540 points
0 votes
1 answer
0 votes
1 answer

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Hello @kartik, Since different users might have different ...READ MORE

answered Jun 15 in Python by Niroj
• 68,780 points
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,780 points
+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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,480 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,800 points
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, 2019 in Python by Mohammad
• 3,210 points
0 votes
2 answers

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

readline function help to  read line in ...READ MORE

answered Jun 21 in Python by sahil
• 540 points