Does Python syntax prevent me from creating this list comprehension? - python

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]

Related

Print a number not in a list python

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.

Unexpected output after merging two sorted arrays with Python

I found a partial solution to the problem; however, it seems that I'm getting extra numbers from my array than what it should be. This is the question I'm trying to find out:
Given two sorted integer arrays nums1 and nums2, merge nums2 into
nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n
respectively. You may assume that nums1 has enough space (size that is
greater or equal to m + n) to hold additional elements from nums2.
Example:
Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
I'm practicing some coding challenges to the hang of Python3 language and prepare myself for an interview. I have tried a few methods like using pop when the beginning of the array are 0s. But it seems that after new test case showed up, I should've expected more. I'm pretty new with the language.
def mergeArrays(nums1, m, nums2, n):
nums1[:] = sorted(nums1 + nums2)
i = 0
while (i < len(nums1[:-1])):
if nums1[i] is 0:
nums1.pop(i)
if i > len(nums1):
break
i += 1
print(nums1)
nums1 = [-49,-48,-48,-47,-45,-42,-39,-36,-33,-33,-28,-28,-23,-23,-7,-4,-3,0,0,4,6,21,29,29,31,34,36,38,40,43,45,46,47,0,0,0,0,0,0,0,0]
m = len(nums1)
nums2 = [-16,-5,-3,26,33,35,38,41]
n = len(nums2)
mergeArrays(nums1, m, nums2, n);
My expected output should be of both arrays sorted and go through. Results should be this: [-49,-48,-48,-47,-45,-42,-39,-36,-33,-33,-28,-28,-23,-23,-16,-7,-5,-4,-3,-3,0,0,4,6,21,26,29,29,31,33,34,35,36,38,38,40,41,43,45,46,47]
However, I'm getting a couple extra zeros, which should look like this:
[-49,-48,-48,-47,-45,-42,-39,-36,-33,-33,-28,-28,-23,-23,-16,-7,-5,-4,-3,-3,0,0,0,0,0,4,6,21,26,29,29,31,33,34,35,36,38,38,40,41,43,45,46,47]
EDIT: added more information to make the problem clear.
As per my understanding you want to sort the two sorted array without having any duplicate element. You can refer the below code:
first_list = [-49,-48,-48,-47,-45,-42,-39,-36,-33,-33,-28,-28,-23,-23,-7,-4,-3,0,0,4,6,21,29,29,31,34,36,38,40,43,45,46,47,0,0,0,0,0,0,0,0]
second_list = [-16,-5,-3,26,33,35,38,41]
merged_list = list(set(first_list+second_list))
merged_list.sort()
print(merged_list)
With one of the old methods that I used was a loop comprehension. Basically, what I did was array splice from beginning to end and do the sort inside of the loop:
def mergeArrays(nums1, m, nums2, n):
nums1[0: m + n] = [x for x in sorted(nums1[:m] + nums2[:n])]
If you have a different explanation than what I just did, please feel free :)
After much back-and-forth on the intent of your code and where your unwanted mystery zeros come from, seems you want to do the following: merge-sort your two arrays, preserving duplicates:
your input is arrays nums1, nums2 which are zero-padded, and can be longer than length m,n respectively
But to avoid picking up those padded zeros, you should only reference the entries 0..(m-1), i.e. nums1[:m], and likewise nums2[:n]
Your mistake was to reference all the way up to nums1[:-1]
Your solution is: sorted(nums1[:m] + nums2[:n]). It's a one-liner list comprehension and you don't need a function.
There is no reason whatsoever that zero entries need special treatment. There's no need for your while-loop.
Also btw even if you wanted to (say) exclude all zeros, you can still use a one-liner list-comprehension: x for x in sorted(nums1[:m] + nums2[:n]) if x != 0]
List comprehensions are a neat idiom and super-powerful! Please read more about them. Often you don't need while-loops in Python; list comprehensions, iterators or generators are typically cleaner, shorter code and more efficient.

How to add values into an empty list from a for loop in python?

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]

Reading input in two lists simultaneously in python

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]

Index error:list assignment index out of range

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)]

Categories