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.
Related
x = [1,2,3,4,50,6,3,2,3,8]
for i in x:
if i > x[x.index(i)+1:10]:
print(i)
TypeError: '>' not supported between instances of 'int' and 'list'
I want to determine which number is larger than all the numbers afterward, in this circumstance, 50.
However, came out this error.
Does anyone have any idea to solve this problem?
This should work:
for i in range(len(x)):
if all(x[i] > x[j] for j in range(i + 1, len(x))):
print(i)
Please try these simple solutions and see which one fits best for your need. I have left comments briefly explaining what each case does. Keep coding in Python, it is a great computer language, pal!
numbers_lst = [1, 2, 3, 4, 50, 6, 3, 2, 3, 8]
# 1- Fast approach using built in max function
print("Using Max Built-in function: ", max(numbers_lst))
# 2- Manual Approach iterating all the elements of the list
max_num = numbers_lst[0]
for n in numbers_lst:
max_num = n if n >= max_num else max_num
print("Manual Iteration: ", max_num)
# 3- Using comprehensions, in this case for the list
max_num = numbers_lst[0]
[max_num:=n for n in numbers_lst if n >= max_num]
print("List Comprehension: ", max_num)
# 4- Sort the list in ascending order and print the last element in the list.
numbers_lst.sort()
# printing the last element, which is in this case the largest one
print("Using the sort list method:", numbers_lst[-1])
# 5 - Using the built in sorted function and getting the last list element afterwards
sorted_lst = sorted(numbers_lst, reverse=True)
max_num = sorted_lst[0]
print("Sorted List: ", max_num)
Although answer given by #Green Cloak Guy is a perfectly valid answer, it is inefficient as it is O(n^2) solution. I present below an O(n) solution by storing the greatest elements from the right.
x = [1,2,3,4,50,6,10,2,3,1]
largest = [0 for i in range (len(x))] # temporary array to store, for every index i, the largest number from the right to index i
largest[-1] = x[-1]
ans = [] # list to store numbers satisfying condition
for i in range (len(x) - 2, -1, -1):
if (x[i] > largest[i+1]):
ans.append(x[i])
largest[i] = max (x[i], largest[i+1])
for i in range (len(ans)-1,-1,-1): # print elements in the same order as given list
print (ans[i])
You could also make use of python's built in sorted method.
x = [1,2,3,4,50,6,3,2,3,8]
y = sorted(x, reverse=True)
print(y[0])
The issue is that you are comparing an individual value against a whole list of values. You will either have to make another loop or use the max() function on that sublist to get the highest value it contains.
A more efficient strategy is to process the list backwards while keeping track of the maximum number encountered.
By accumulating the maximum value backwards in the list and comparing it to the previous number, you can find all the numbers that are greater than all their successor. This produces results in reverse but the accumulate() function from the itertools module can be used to get these reversed maximum and the zip() function will allow you to combine them with the numbers in the original list for comparison/selection purposes.
x = [1,2,3,4,50,6,3,2,3,8]
from itertools import accumulate
r = [n for n,m in zip(x[-2::-1],accumulate(x[::-1],max)) if n>m]
print(r)
[50]
This returns a list because, depending on the data, there could be multiple numbers satisfying the condition:
x = [1,2,3,4,50,6,3,2,3,1]
r = [n for n,m in zip(x[-2::-1],accumulate(x[::-1],max)) if n>m][::-1]
print(r)
[50, 6, 3]
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 question is to take 4 integers as input entered in separate lines.
ex:=
1
1
1
2
The below code does the required thing. I am trying to understand its working part.
x,y,z,n=[int(input()) for _ in range(4)]
welcome!
This code is the equivalent of
x = int(input())
y = int(input())
z = int(input())
n = int(input())
The input() function reads an input from the user and the int tries to transform it to an integer, which is assigned to each variable (x,y, z and n).
The code can be also written as:
numbers = []
for i in range(4): # Loop 4 times
numbers[i] = int(input())
x = numbers[0]
y = numbers[1]
z = numbers[2]
n = numbers[3]
Which is more similar to the form you provided. But the author uses two python features that makes the code smaller (and more expressive). I'll explain both:
List Comprehensions
Lot of times during programming, you will be whiling to execute a command several times and get the results into an list, or for example, map values from one list to other. In this case, you would have something like this:
numbers_til_5 = [0,1,2,3,4,5]
squares_til_5 = []
for n in numbers_til_5:
squares_til_5.append(n*n)
With the List Comprehension syntaxe, we could do:
sqaures_til_5 = [ n*n for n in numbers_til_5]
The other feature is:
Destructuring
This is a feature that allows you to get elements of a list in one single statement.
In the example we have this:
x = numbers[0]
y = numbers[1]
z = numbers[2]
n = numbers[3]
Which could be replaced by x,y,z,n = numbers.
Another form interesting, is when you care only for the first arguments, for example:
first = numbers[0]
rest = numbers[1:] # This get all elements starting from the first
could be written as first, *rest = numbers.
I hope I was able to make it clear.
for _ in range(4) repeats int(input()) 4 times, so the brackets contain now the first four inputs [1, 1, 1, 2].
In Python you can assign multiple variables at one time, so x,y,z and n will be assigned to the corresponding values of the bracket.
For better understanding, you could extract the individial parts like this:
x = int(input())
y = int(input())
z = int(input())
n = int(input())
It is running a loop to input values as integers and feeding those values to the variable x,y,z,n in that sequence. range(n) runs the loop for a range 0-n (in this case, 4 times). _ is used to denote "anything" while running the loop.
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 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]