List combination challenge in Python 3 [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 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']

Related

Python Enumerate [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 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].

How can I generate all possible words with a specified set of characters? [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 play to HackNet game and i have to guess a word to bypass a firewall.
The key makes 6 characters long and contains the letters K,K,K,U,A,N.
What is the simplest way to generate all possible combinations either in bash or in python ? (bonus point for bash)
Here is a backtracking-based solution in Python:
db = {"K" : 3, "U" : 1, "A" : 1, "N" : 1}
N = 6
def possibilities(v):
l = []
for k in db.keys():
if v.count(k) < db[k]:
l.append(k)
return l
def generateImpl(a):
if len(a) < N:
lst = []
for c in possibilities(a):
lst += generateImpl(a+[c])
return lst
else:
return [''.join(a)]
def generate():
return generateImpl([])
Just run generate() to obtain a list of possible words.
You have 6 letters and need to find a combination of 6 letters. If you are not using the same character in ['K','K','K','U','A','N'] again and again, then there is only 1 permutation.
If you can use the same character again and again, you can use the following code to generate all possible combinations.
import itertools
y = itertools.combinations_with_replacement(['K','U','A','N'],6)
for i in list(y):
print(i)

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