Out of bounds error due to list assignment? [closed] - python-3.x

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
array1 = []
array2 = []
size = int(input("Enter the size of the array: "))
print("Enter the elements in the array: ")
for item in range(size):
element = int(input())
array1.append(element)
array2[0] = -1
for item in range(1, 8):
x = item-1
if array1[item] < array1[x]:
array2.append(-1)
elif array1[item] > array1[x]:
array2.append(array1[x])
elif array1[item] == array1[x]:
array2.append(array2[x])
print(array2)
Expected output: a proper execution of the code
Received output:
Traceback (most recent call last)
array2[0] = -1
IndexError: list assignment index out of range

First of all, note that your problem is in array2, so most of the code is superfluous to this issue. The minimal, complete example to reproduce your error is:
array2 = []
array2[0] = -1
When looking at this example, it's easier to see the problem - array2 is initialized with size 0, so its 0-th index is already out of bound.
Going back to your code, you can just initialize it as array2 = [-1] instead of how it's written - after all, array2[0] = -1 is the first time that array2 is accessed. Or you can change the array2[0]=-1 to an .append.

u set array2 as [],so when u define array2[0] = -1 the index is out of range

Related

Python: Separate things of string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have the following string in my database: items = '1;2 | 3;4'
And I have to get information, like quantity and product, separating the information, I have to get the following, for example:
1;2 = Product 1, quantity 2
3;4 = Product 3, quantity 4
I tried anyway with split, partition with join, but it doesn't work.
I can get the first one with [0], but if there are others in the string I can't do the transformation.
x = "1;2 | 3;4" # string
data = x.split("|") # data = ["1;2", "3;4"]
data = [i.split(";") for i in data] # data = [["1","2"], ["3","4"]]
data = [[int(i) for i in j] for j in data] # converts strings to ints
Now, data[0][0] gives the number of the first product and data[0][1] gives the quantity of the first product. Similarly for data[1][0] and data[1][1]
Edit
To clarify Andre's comment:
x = '1;2 | 2;4 | 3;8 | 45;1'
data = x.split("|")
data = [i.split(";") for i in data]
data = [[int(i) for i in j] for j in data]
for i in data:
print("Product number: " + str(i[0]))
print("Quantity: " + str(i[1]))
txt = '1;2 | 3;4'
x = txt.split('|')
for i in x:
print(i.split(';'))

How to index identical item in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
lst = [1,0,0,0,1,0,1,1]
x = lst[4]
print(lst.index(x))
The last line prints 0.
What if I wanted to return the item at the original index of four. Is there a way to the original, rather than an equavalent element in the list?
Edit: To be clear, I want the last line to print 4.
If the format of the list doesn't matter, you could try using the enumerate class (a generator object):
lst = [x for x in enumerate((1,0,0,0,1,0,1,1))]
x = lst[4]
lst.index(x) # This should return 4 rather than 0.
EDIT: Instead of doing lst.index(x) to get the index, you could do x[0] which will also return 4.
The only problem is that you're going to have to write some changes to your code. If you tried to print x, the result would be [4, 1]. If you wanted to simply gather the value, you would have to print x[1]. The enumerate class is a generator object, that when iterated over yields a list in the form of [index, value]. If you have any other questions, please comment and I'll do my best to answer them.
index(obj) return only the index of the first item equal to obj, if you want to search from a certain position you can use index(obj, start), example:
>>> l = [0, 1, 1, 10, 0, 0, 10, 1]
>>> l.index(1, 5)
>>> 7
if you want to jump a certain number of item equals to your obj you can use a loop:
def my_index(l, obj, after=0):
for i, item in enumerate(l):
if item == obj:
if after == 0:
return i
after -= 1
raise ValueError(str(obj) + ' is not in list') # nothing was found
Once you've resolved lst[4] to 1, that value is just an integer value with no information about where it came from. If you need to be able to go back from the value to the index in the original list, you'll have to either make the entry unique or keep the indexes you are interested in stored somewhere else.
To make the entries unique, you could store the index along with each value in the list, like this:
lst = [[(0,1),(1,0),(2,0),(3,0),(4,1),(5,0),(6,1),(7,1)]]
To fetch a value:
x_entry = lst[4]
x_val = x_entry[1]
To find it's original position in the list:
index = x_entry[0]
If you want to generate that data structure automatically, you can loop through the list with enumerate() to get the index of each entry:
lst = [1,0,0,0,1,0,1,1]
annotated_lst = []
for i, val in enumerate(lst):
annotated_lst.append((i, val))

Finding maximum value in a dictionary Python [duplicate]

This question already has answers here:
Getting the Max Value from a Dictionary [duplicate]
(3 answers)
Closed 3 years ago.
the input I have given is
BatmanA,14
BatmanB,199
BatmanC,74
BatmanD,15
BatmanE,9
and the output i expect is the highest value and i get something else this is my code below i have tried other methods too pls help thanks.
N = int(input("Enter the number of batsman : "))
d = {}
for i in range(0,N):
batsman = input("enter the batsman values " ).split(',')
d[batsman[0]] = batsman[1]
v = list(d.values())
k = list(d.keys())
print(k[v.index(max(v))])
d[max(d, key=d.get)]
See Getting key with maximum value in dictionary? for more discussion.

From a given list, remove all even numbers(including 0) and print out the resulting list [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 3 years ago.
input_list = [22,456,3465,456,6543,546,345]
for num in input_list:
if num==0 or num%2==0:
input_list.remove(num)
Could you please tell me what is the problem in this code?
It is not removing second 456 from the list.
The problem with your code is that you are removing an item while iterating over the list.
So when the num become 22 then 22 will be removed and 456 become index 0 in your list, in the next iteration the for loop looks for index 1 which is 3465.
Try this:
input_list = [i for i in input_list if i%2 == 1]

Split a number per unit of token python function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to create a function that receive as argument a number and return an array of 3 numbers max.
I have 3 tokens. 1 unit, 5 unit and 25 unit.
calculateUnit(4) should = [4,0,0]
calculateUnit(7) should = [2,1,0] (because 2 unit of 1 and 1 unit of 5 = 7)
calculateUnit(36) should = [1,2,1] (because 1 unit of 1, 2 unit of 5 and 1 unit of 25 = 36)
I have a basic code and I think I need to use modulo division, I already tried to search here and every other resources I have but I may not use the correct terms.
You can reduce your solution to:
def convertInToken(am):
return [am//25, (am%25)//5, am%5]
This leverages integer-division (3.x upwards, also named floor division) and modulo division.
Floor division returns the full integer that woud have been returned if you did a normal division and floored it.
Modulu division returns the "remainder" of a division.
I managed to do that, but thanks anyway :)
# your code goes here
import math
def convertInToken(am):
result = [];
#need to use 25
if am >= 25:
amount25 = math.floor((am/25))
amount5 = math.floor((am-(amount25*25))/5)
amount1 = math.floor(((am-(amount25*25)-(amount5*5))/1))
result = result+[amount1]
result = result+[amount5]
result = result+[amount25]
#need to use 5
elif am >= 5:
amount5 = math.floor((am/5))
amount1 = math.floor(((am-(amount5*5))/1))
result = result+[amount1]
result = result+[amount5]
result = result+[0]
#need to use 1
elif am < 5:
result = result+[am]
result = result+[0]
result = result+[0]
return result
print(convertInToken(4))
print(convertInToken(7))
print(convertInToken(12))
print(convertInToken(37))

Resources