I was solving a problem on hackerrank and encountered a problem reading inputs.
The input format is:
First line: A number n, which tells the no. of lines I have to read.
n lines: Two space separated values, e.g.:
1 5
10 3
3 4
I want to read the space separated values in two lists.
So list 'a' should be [1,10,3] and list 'b' should be [5,3,4].
Here is my code:
dist = []
ltr = []
n = input()
for i in range(n):
ltr[i], dist[i] = map(int, raw_input().split(' '))
It gives me following error:
ltr[i], dist[i] = map(int, raw_input().split(' '))
IndexError: list
assignment index out of range.
This is a common error with Python beginners.
You are trying to assign the inputted values to particular cells in lists dist and ltr but there are no cells available since they are empty lists. The index i is out of range because there is yet no range at all for the index.
So instead of assigning into the lists, append onto them, with something like
dist = []
ltr = []
n = input()
for i in range(n):
a, b = map(int, raw_input().split(' '))
ltr.append(a)
dist.append(b)
Note that I have also improved the formatting of your code by inserting spaces. It is good for you to follow good style at the beginning of your learning so you have less to overcome later.
This might help you in some way; here's a simpler way to approach this problem as you know "Simple is better than complex.":
dist=[]
ltr=[]
n=int(raw_input())
for i in range(n):
dist.append(int(raw_input()))
ltr.append(int(raw_input()))
print(dist)
print(ltr)
output:
[1, 10, 3]
[5, 3, 4]
Related
I'm having an issue with a simple task it seems, but cannot figure it out. I believe the solution is within the code:
n = input().split(',')
list1 = []
list2 = []
for x in n:
list1.append(int(x))
for y in range(1, len(list1 + 1)):
if y not in list1:
list2.append(y)
print(list2)
The task is:
Given an array of integers, some elements appear twice and others appear once.
Each integer is in the range of [1, N], where N is the number of elements in the array.
Find all the integers of [1, N] inclusive that do NOT appear in this array.
Constrain:
N will always be in the range of [5, 1000]
Input:
1,2,3,3,5
Output:
4
Input:
1,1,1,1,1,1,1,1
Output:
2,3,4,5,6,7,8
My idea is to have two empty arrays. The first one I will write all the numbers using a for loop. Once I have them all there I will use another loop where I can look and find the missing numbers. I guess it related to some formatting that is killing my logic.
Any help would be appreciated!
Thanks
You only have to change this line:
for y in range(1, len(list1 + 1)):
to this one:
for y in range(1, len(list1)+1):
The problem is that you added one to the list, but you want to add 1 to the length of the list.
I am trying to recreate a for loop (A) into a list comprehension. I think the problem here is that there are too many functions that need to be done to ni, namely squaring it and then making sure it is an integer before appending onto nn .
The list comprehension (B) is an attempt at getting the list comprehension to take a string (m) and square each individual number as an integer. The problem is that it needs to iterate over each number as a string THEN square itself as individual integers.
A
n = str(2002)
nn = []
for x in range(len(n)):
ni = n[x]
ns = int(ni)**2
nn.append(ns)
print(nn)
[4, 0, 0, 4]
B
m = str(9119)
mm = [(int(m[x]))**2 for x in m]
TypeError: string indices must be integers
This makes me feel like A cannot be done as a list comprehension? Love to see what your thoughts for alternatives and/or straight up solutions are.
You are passing a string as the index!
Additionally, you were trying to index the string m with the number at each index instead of its index (e.g, you tried to index m[0] with m[9] instead)
Try using the following instead:
m = str(9119)
mm = [int(x)**2 for x in m] #Thanks #Gelineau
Hope this helps!
x represents each digit in m. So you just have to square it
mm = [int(x)**2 for x in m]
The given python code is supposed to accept a number and make a list containing
all odd numbers between 0 and that number
n = int(input('Enter number : '))
i = 0
series = []
while (i <= n):
if (i % 2 != 0):
series += [i]
print('The list of odd numbers :\n')
for num in series:
print(num)
So, when dealing with lists or arrays, it's very important to understand the difference between referring to an element of the array and the array itself.
In your current code, series refers to the list. When you attempt to perform series + [i], you are trying to add [i] to the reference to the list. Now, the [] notation is used to access elements in a list, but not place them. Additionally, the notation would be series[i] to access the ith element, but this still wouldn't add your new element.
One of the most critical parts of learning to code is learning exactly what to google. In this case, the terminology you want is "append", which is actually a built in method for lists which can be used as follows:
series.append(i)
Good luck with your learning!
Do a list-comprehension taking values out of range based on condition:
n = int(input('Enter number : '))
print([x for x in range(n) if x % 2])
Sample run:
Enter number : 10
[1, 3, 5, 7, 9]
I need to create an algorithm which would read user input of lists A and B and determine whether elements from list B occur in list A (if they occur, program needs to print 'Yes', and 'No' otherwise').
I have come up with the following code which should can be a starting point:
n=int(input('Enter the length of list A '))
A=[]
for i in range (0,n):
InpEl=int(input('Enter the elements '))
A.append(InpEl)
print(A)
n=int(input('Enter the length of list B '))
B=[]
for i in range (0,n):
InpEl2=int(input('Enter the elements '))
B.append(InpEl2)
print(B)
checklist=B
for each in A:
if each in checklist:
print('YES')
else:
print('NO')
Although in any case, I get 'No'. What is the mistake here?
Also, later I may need to modify the list so the program could determine if elements of B occur in A in the order they appear in B, but not necessarily consecutively.
For example, let M be the length of B and N be the length of A.
Then the program should return yes if there are indices i0, i1...im+1 such that 0<= i0 < i1...< im-1 < N such that A[i0] = B[0];A[i1] = B[1]...A[im-1] =
B[m-1].
Is there a simpler way to build the loop which would satisfy this kind of request?
P.S.: is it possible to make user input read not only integers, but strings? I am not sure if raw_input would be useful in Python 3.5.
P.S.S:
sorry, I made a minor mistake inputting the code here, I fixed it now.
Another question: I get the output of multiple yes' and no's for each element:
Enter the length of list A 3
Enter the elements 1
Enter the elements 2
Enter the elements 3
[1, 2, 3]
Enter the length of list B 3
Enter the elements 5
Enter the elements 4
Enter the elements 3
[5, 4, 3]
NO
NO
YES
How can I modify the code so it would print only one yes and no only once in case of any occurencies happen?
Here's one solution. Keep in mind there are many that have asked this type of question before and that best practice is to search around before asking.
a = input('enter list A with comma between each element: ')
b = input('enter list B with comma between each element: ')
a = a.split(',')
b = b.split(',')
contained_in_b = [element in b for element in a]
for i, in_b in enumerate(contained_in_b):
print('element {} contained in list B: {}'.format(a[i], in_b))
Better to take the raw input all together and use Python to split it into lists. This way, no need for the user to give the length of the list beforehand. Also, no need to convert to int - string comparisons work fine.
contained_in_b uses a list comprehension - a handy feature of Python that applies the boolean element in b to each element in a. Now you have a list of True/False values that you can enumerate through to print out the desired output.
One weapon you get is the all operator, which just checks that all of the items in the iterable are True:
A = [1, 4, 6, 8, 13]
B = [4, 6, 13, 8]
C = [3, 8, 25]
master = [i for i in range(20)]
print all(i in master for i in A)
print all(i in master for i in B)
print all(i in master for i in C)
Output:
True
True
False
To get the order as well, you'll need to drop back to an iterative method, stepping through the first list with a loop, while you maintain an index to know where you are in the second. For each value in the first list, go through the rest of the second list, until you either find the item (temporary success) or hit the end (failure).
Reading in number names and converting them to integers is a separate problem, and longer code.
I want to:
Take two inputs as integers separated by a space (but in string form).
Club them using A + B.
Convert this A + B to integer using int().
Store this integer value in list C.
My code:
C = list()
for a in range(0, 4):
A, B = input().split()
C[a] = int(A + B)
but it shows:
IndexError: list assignment index out of range
I am unable understand this problem. How is a is going out of the range (it must be starting from 0 ending at 3)?
Why it is showing this error?
Why your error is occurring:
You can only reference an index of a list if it already exists. On the last line of every iteration you are referring to an index that is yet to be created, so for example on the first iteration you are trying to change the index 0, which does not exist as the list is empty at that time. The same occurs for every iteration.
The correct way to add an item to a list is this:
C.append(int(A + B))
Or you could solve a hella lot of lines with an ultra-pythonic list comprehension. This is built on the fact you added to the list in a loop, but this simplifies it as you do not need to assign things explicitly:
C = [sum(int(item) for item in input("Enter two space-separated numbers: ").split()) for i in range(4)]
The above would go in place of all of the code that you posted in your question.
The correct way would be to append the element to your list like this:
C.append(int(A+B))
And don't worry about the indices
Here's a far more pythonic way of writing your code:
c = []
for _ in range(4): # defaults to starting at 0
c.append(sum(int(i) for i in input("Enter two space-separated numbers").split()))
Or a nice little one-liner:
c = [sum(int(i) for i in input("Enter two space-separated numbers").split()) for _ in range(4)]