Python Enumerate [closed] - python

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 2 years ago.
Improve this question
I have a code listed below that accepts a list and then returns a new list with every second value removed.
Can someone explain to me how this code works? I understand that the enumerate function will put the list into a list of tuples. Example: [1,2,3,4,5] will go to (0,1) (1,2) (2,3) (3,4) (4,5)
Question 1: In the code why is "val" listed before the for loop in the return statement and then listed a second time after the for?
Question 2: After the word "for" is i for index 0 of the resulting tuple from the enumerate?
Question 3: After the word "for" is val for index 1 of the resulting tuple from the enumerate?
CODE:
def remove_every_other(lst):
return [val for i,val in enumerate(lst) if i % 2 == 0]
print(remove_every_other([1,2,3,4,5])) # [1,3,5]

Regarding Q1, this is just a list comprehension syntax.
In your function it creates a list and returns it.
It could be rewritten as a regular for loop, e.g.
def remove_every_other(lst):
result = []
for i, val in enumerate(lst):
if i % 2 == 0:
result.append(val)
return result
In Python list comprehension is a more natural way to do this same thing.
Answers to Q2 & Q3 are yes and yes.
I think the function would be easier to understand if it looked something like this
def remove_every_other(lst):
return [i for i in lst if i % 2 != 0]
print(remove_every_other([1,2,3,4,5])) # [1,3,5]

This is not a "for" loop, this is a list comprehension syntax. [val for i,val in enumerate(lst)] would go over what enumerate(lst) yields, tuple by tuple, and put just the val-s into a new list. All of them. Hence, this would simply recreate the same list. Adding the condition [val for i,val in enumerate(lst) if i % 2 == 0] will make it take just the values the condition is true for, so only the ones where index is dividable by 2. As others have already mentioned, reading about list comprehension would be very helpful.
This said, you can do the same thing in a much simpler form. Specifically, just lst[::2].

Related

Cant find what's wrong in the code... Repeat and missing Number [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 months ago.
Improve this question
Question
You are given a read only array of n integers from 1 to n.
Each integer appears exactly once except A which appears twice and B which is missing.
Return A and B.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Note that in your output A should precede B.
Example:
Input:[3 1 2 5 3]
Output:[3, 4]
A = 3, B = 4
My code:
class Solution:
def repeatedNumber(self, A):
n=len(A)
asum=0
rsum = (n*(n+1))//2
x=0
dict={}
for i in A:
asum+=A[i]
if A[i] in dict:
x=A[i]
else:
dict[i]=1
diff=rsum-asum
return x,x+diff
Your error is simple, you're using for i in A: but you refer to i within the for loop as if you did for i in range(len(A)):. To fix this all you need to do is replace all instances of A[i] in your code with i. It should look something like this:
class Solution:
def repeatedNumber(self, A):
n=len(A)
asum=0
rsum = (n*(n+1))//2
x=0
distinct={}
for i in A:
asum+=i
if i in distinct:
x=i
else:
distinct[i]=1
diff=rsum-asum
return x,x+diff
Note: It doesn't have any functional relevance in this case, but it is generally go practice to name your variables something other than the object name. In this case I just renamed the dict variable to distinct, as it also gives readers a better understanding of what the dictionary is actually used for.
This could be a solution. It runs in O(2n)
my_list = [3, 1, 2, 5, 3]
new_list = []
length = len(my_list)
for x in range(1,length+1):
new_list.append(x)
for x in range(1,length+1):
try:
my_list.remove(x)
except:
missing_number = x
double_number = my_list[0]
print(missing_number)
print(double_number)
Basically, according to your input, you can use the fact that the max value inside the list is the max length. So you create a new list with all the possible values, scan your first list and removing the values from the second list. If you try to remove a value that doesn't exist in the list you got error (that's why the try, except) and at the end you get, in the original list, only the double value (as it has been removed just one time)
EDIT: actually, if you consider the execution time of .remove() function, the overall running time of the function is O(n+n^2)

List combination challenge in Python 3 [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 2 years ago.
Improve this question
I am just facing one tricky challenge to make a list combination in python 3.
I have one list that needs to used for combination. (given list)
['01101001', '01110110', '01100101', '01101011']
I want to get the list combined with each value like below. (result list)
['00001111', '11110100', '10010110', '01011011']
The first item in the result list is made by the combination of the first 4 strings and the second 4 strings of each item in turn in the given list.
So 0000 are the first 4 strings of each item and 1111 are the second 4 strings of each item in the given list.
Thus the first item of the result list is 00001111.
What is the optimized code written by Python 3?
Thank you in advance!
Idiomatic Python code makes heavy use of iterators. What you are trying to do is a form of parallel iteration over your strings, which is what zip can do.
If strings = ['01101001', '01110110', '01100101', '01101011']
Then [''.join(chars) for chars in zip(*strings)] evaluates to
['0000', '1111', '1111', '0100', '1001', '0110', '0101', '1011']
That is almost what you want. It would be nice if you could iterate over the list by pairs. You can do so in several ways, including by using this nice solution due to #mic_e:
#the following pairwise iterator is due to mic_e
#from https://stackoverflow.com/a/30426000/4996248
def pairwise(it):
it = iter(it)
while True:
try:
yield next(it), next(it)
except StopIteration:
# no more elements in the iterator
return
Then simply:
new_strings = [a+b for a,b in pairwise(''.join(chars) for chars in zip(*strings))]
which is ['00001111', '11110100', '10010110', '01011011'].
Here is the solution.
givenList = ['01101001', '01110110', '01100101', '01101011']
unitList = list()
result = list()
for i in range(8):
for j in givenList:
unitList.append(j[i])
if i % 2 == 1:
result.append(''.join(unitList))
unitList = []
print(result)
This would be working for only the given list contains static 8 digits.
You can update the 8 with len(givenList[0]).
Simple Solution
lt = ['01101001', '01110110', '01100101', '01101011']
def list_combination(lt,new=[],num=""):
for i in range(len(lt[0])):
if len(num)==8:
num = ""
for j in lt:
num += j[i]
if len(num)==len(lt[0]):
new.append(num)
return new
print(list_combination(lt))
#['00001111', '11110100', '10010110', '01011011']

Given a list of numbers how to insert items into another list with the list of numbers as the index? [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 5 years ago.
Improve this question
I have a list of numbers:
numbers=[1,3]
and I have two list of lists:
a=[[1,2,3],[4,5,6]] and b=[[1,2],[2,4]]
I want to insert the items from list a into list b according to index in the numbers list. So [1,2,3] will be inserted into list b at index 1 and [4,5,6] into list b at index 3. How do I do that?
EDIT:I tried using a for loop but it said list index out of range?
EDIT:The loop is correct.Errors were from other parts of my code.
for itemOne in numbers:
for item in a:
verticeToAppend= item
b.insert(itemOne,verticeToAppend)
Output:
[[1,2],[1,2,3],[2,4],[4,5,6]]
The error I got was from errors in other parts of my code.This for loop is correct.
for itemOne in numbers:
for item in a:
verticeToAppend= item
b.insert(itemOne,verticeToAppend)
[b.insert(numbers[elem],a[elem]) for elem in range(len(numbers))]
You could use a list comprehension
Insert values into a result list according to the indices list (see code).
result = []
originals = [...]
values = [...]
while len(indices) > 0:
if len(result) == indices[0]:
result.append(values[indices[0]])
indices = indices[1:]
elif len(originals) == 0:
result.append("placeholder") # e. g. None
else:
result.append(originals[0])
originals = originals[1:]

How do i print every 3rd number in a list in python WITHOUT USING slice notation (square brackets)? [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 6 years ago.
Improve this question
def every_third(lst):
'''
every_third that takes a list as a parameter and returns
a new list that contains every third element of the original
list, starting at index 0.
>>> every_third([1,2,3,4,5,6,7,8,9,10])
[1,4,7,10]
How would I do this? I know that we can use a for loop, but i just dont know how to begin.
If range is allowed with all of start, stop, step (which is not exactly slice notation), just do:
def every_third(lst):
return [lst[i] for i in range(0, len(lst), 3)]
If not, use a conditional comprehension with a condition based on modulo:
def every_third(lst):
return [lst[i] for i in range(len(lst)) if i%3 == 0]
Another trick using enumerate:
seq = [1,2,3,4,5,6,7,8,9,10]
every_three = [value for idx, value in enumerate(seq) if idx % 3 == 0]
But my first comment if code review of lines above would be: Use slice syntax, there's no need to use an enumerate here.
If the problem is just the slice notation, as in [::3] I think it should be somethink like this, I figure You are doing exercises right?
list=[1,2,3,4,5,6,7,8,9,10]
def third(list):
res=[]
count=3
res.append(list[0])
while len(list)>0:
if count>0:
list.pop(0)
else:
res.append(list[0])
list.pop(0)
count=3
count -= 1
return res
print(third(list))

Difference between for items in list and for i in range (0, len(x)) 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 6 years ago.
Improve this question
I'm getting to grips with lists in python but I'm stumped when it comes to the difference in using these two functions.
def print_list(x):
for j in range (0, len(x)):
print x[j]
and
def print_list(x):
for item in list:
j = 0
print x[j]
j++
Can anyone explain to a beginner? Thanks!
I assume
def print_list(x):
for j in range (0, len(x)):
print x[j]
is how loops run in C++. So you understand that intuitively. Here, range generates (look up generators) the values 0 through len(x) and the for statement iterates through them.
Your 2nd syntax, as pointed out in the comments, is wrong. I assume you meant
def print_list(x):
for item in x:
print(item)
The for statement iterates through every item in the list x.
So if your list is [1,3,5,7,9], in the 1st loop, item will have value 1. In the 2nd loop, item will have the value 3. In the 3rd loop, item will have the value 5. And so on.
When all the values have been iterated through, the for loop ends.
The first example is correct and it should be pythonic enough. The second one is incorrect.
def print_list(x):
for item in list: #where is the iterable oject called list? This shuold be x
j = 0 # if you use a counter like j you shuold be defining before the loop otherwise you keep resetting it to 0.
print x[j]
j++
A more pythonic and better way if you want to print all the elemets in a list interating over them.
def print_list(list_item):
for element in list_item:
print(element)
You don't need to use the range and len like in the first example, list are iterable object so you can just do like the above example without recuring to range().

Categories