the terminal doesn't display when i compile the code - python-3.x

I want to create a program, such that it returns the index of the element, if each element in list 1 matches the corresponding element in list 2
for example: [5, 1, -10, 3, 3], [5, 10, -10, 3, 5].
Here 5 in list 1 matches the first element 5 in list 2 hence it returns index 0. similarly -10 matches with -10. hence gives index 2.
required output
[0,2,3]
MY CODE:
def same_values(lst1,lst2):
n = 1
lst_of_index = []
while(n <= len(lst1)):
for i in lst1:
value_1 = i
for j in lst2:
value_2 = j
if (value_1 == value_2):
indexed_value = lst1.index(i)
lst_of_index.append(indexed_value)
n += 1
return lst_of_index
print(same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5]))
when i run the code, it doesn't display anything. Is something wrong with my code?

Combining the answers from #user12137152 and #diego-mourino with a list comprehension, you get a relatively simple one liner:
def same_values(lst1,lst2):
return [idx for idx, val in enumerate(zip(lst1, lst2)) if val[0] == val[1]]

Use a for loop and zip to iterate over both the lists at the same time. The benefit of the following program is that it doesn't crashes even if the lists are of different sizes.
def same_values(lst1, lst2):
lst_of_index = []
n = 0
for i, j in zip(lst1, lst2):
if i == j:
lst_of_index.append(n)
n += 1
return lst_of_index
print(same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5]))

The function you implementate has a major bug. The function doesn´t return anything because you are generating an infinite loop. That`s because you first iterate over all the values of the lists and, after that, you compare value_1 and value_2. In this example, the value_1 and value_2 will be 3 and 5 respectively (because you are comparing the last value of the lists because the if statement is after the two iterators over the lists at the same indentation level). And because of that, the while loop gets stuck.
I propose to you an alternative implementation, using enumerate() instead of a the while. When you use enumerate over a list, this iterator give you 2 elements: the position of a given element of the list (i) and the element of the list (in this case, value_1). This implementation is shown below:
def same_values(lst1,lst2):
lst_of_index = []
for i, value_1 in enumerate(lst1):
value_2 = lst2[i]
if (value_1 == value_2):
lst_of_index.append(i)
return lst_of_index

Related

Python} Reversing List Without Using String Method

How should I write the code with the following problem?
Implement the function reverse_print(lst) that prints out the contents of the given list ‘lst’
in reverse order. For example, given a list [3, 6, 2, 1], the output should be 1, 2, 6, 3 (vertical
printout allowed). For this code, you are only allowed to use a single for-loop. Without String Method
Also Not using Print[::-1]
Assuming you are not allowed to just call list.reverse() you can use range with a negative step to iterate the list in reverse order:
def reverse_print(lst):
out = []
for i in range(len(lst) - 1, -1, -1):
out.append(lst[i])
print(*out, sep=", ")
inp = [1, 2, 3, 4]
reverse_print(inp)
Output: 4, 3, 2, 1
You may try something like this
def reverse_print(lst):
rev = [lst[abs(i-l)-1] for i in range(l)]
return rev
lst = [3,6,2,1]
l = len(lst)
print(reverse_print(lst))

Beginner has trouble with comparing lists in python3

I'm new to stackoverflow and also new to programming.
I have to compare two lists in python3 and struggle to produce working code for half a day now.
a = [3,1,0,1,2,2]
b = [2,3,0,2,1,1]
The lists are always the same length and contain the same elements.
I have to order list b in accordance with list a (basically copy it), however I need to remember the swapping order.
For example as a first step I swap element 0 and 1 in list b to make it [3,2,0,2,1,1].
Seconde step: Swap element 1 and 4.
Third step: Swap elements 3 and 5.
So in the end list b is identical with list a and I have created a third list with the swapping tupels ((0,1),(1,4),(3,5)).
Thank you very much for helping me out.
My buggy code sample:
targetcounterlist: [3,1,0,1,2,2]
candidatecounterlist: [2,3,0,2,1,1]
for i in candidatecounterlist:
global uncommon_elements
uncommon_elements = [(e, v) for e, v in enumerate(targetcounterlist) if candidatecounterlist[e] != v]
print(candidatecounterlist)
swap_tupel = uncommon_elements[0]
swap_position = swap_tupel[0]
swap_value = swap_tupel[1]
if candidatecounterlist[i] == swap_value:
candidatecounterlist[i], candidatecounterlist[swap_position] = candidatecounterlist[
swap_position], \
candidatecounterlist[i]
uncommon_elements = uncommon_elements[1:]
else:
print("no match")
You can use list.index method (look at start parameter):
a = [3, 1, 0, 1, 2, 2]
b = [2, 3, 0, 2, 1, 1]
out, i = [], 0
while a != b:
if a[i] != b[i]:
idx = b.index(a[i], i)
b[i], b[idx] = b[idx], b[i]
out.append((i, idx))
i += 1
print(out)
Prints:
[(0, 1), (1, 4), (3, 5)]
I would suggest you to loop over the elements of list_a. Then check at what position it is in list_b, and if it is not in the correct position swap it. This should work assuming that a solution is possible.
However, you should be careful about repeated values, to avoid that fixing, for example, the 5th element doesn't break a previous element that has already been fixed).
For your example the algorithm should do something like that:
The 0th element of A is 3, but a 3 is in the first position in B, swap 0 and 1: [3, 2, 0, 2, 1, 1]
The 1st element of A is 1, but 1 is in the 4th position in B, swap 1 and 4: [3, 1, 0, 2, 2, 1]
The 2nd element of A is 0, which is also in the 2nd position in B, next.
The 3rd element of A is 1, but 1 is in the 5th position in B, swap 3 and 5: [3, 1, 0, 1, 2, 2]
etc...
Here, for example in step 4 is where you should be careful not to use the 1 in the 1st position since this would cause problems.
Now of course this isn't probably the most efficient algorithm, but it works. I let you try to write the actual code to implement it, or another one you came up with.

Why does my code for removing the even numbers from the beginning of a list not work?

def delete_starting_evens(lst):
for i in lst:
if i%2==0:
lst.remove(i)
else:
break
return lst
The given code produces unexpected results, but I'm not able to figure out from the output where the problem lies.
That's because you're suppressing items of a list your for-loop is iterating on. Hence it suppresses half of your items. For instance if you call your function on list [2, 2, 4, 6, 1] it will delete the first 2 of your list then move to lst[1] which is 4 (after deletion of the first 2), delete this one then move to lst[2] which is now 1 and terminates. The resulting list will be [2, 6, 1]
It is very bad practice to modify the structure you are iterating on. Here you should prefer a while loop:
def delete_starting_evens(lst):
while len(lst) > 0 and lst[0]%2==0:
lst.remove(lst[0])
return lst
l = [2, 2, 4, 6, 1]
delete_starting_evens(l)
print(l)

Can you use count() for an entire list instead of one variable?

Is there a way to use count() for an entire list rather than have to use it on each variable seperately? If this is possible it would save me alot of typing.
var1 = random.randint(u,v)
var2 = random.randint(w,x)
var3 = random.randint(y,z)
listName = [var1,var2,var3]
listName.count(x)
listName.count(y) #can you get the count for an entire list instead of having to do them
listName.count(z) #all seperately? It would be much more efficient.
Here's an example of creating a list with random contents and then showing the length and sum.
import random
my_list = [
random.randint(1, 10),
random.randint(1, 10),
random.randint(1, 10)
]
print("The value of my_list is {0}".format(my_list))
print("The length of my_list is {0}".format(len(my_list)))
print("The sum of my_list is {0}".format(sum(my_list)))
Sample Output:
The value of my_list is [4, 8, 4]
The length of my_list is 3
The sum of my_list is 16
Is this what you were looking for?
list.count(item) returns the number of times item appears in a list.
If you want to know how many times each item appears in the list, if it appears in the list, you can do this:
original_list = [1, 1, 2, 3, 4, 4, 4]
uniques = list(set(original_list))
counts = {}
for unique in uniques:
counts[unique] = original_list.count(unique)
print(counts)
which should print something like
{
1: 2,
2: 1,
3: 1,
4: 3
}
Here's more info on the set data type:
https://docs.python.org/3/tutorial/datastructures.html#sets
While we're at it, you can also use collections.Counter:
from collections import Counter
counts = Counter([1, 1, 2, 3, 4, 4, 4])
print(dict(counts))
and this should print the same dictionary as above.

Checking whether a list of numbers contains ANY five number sequence

I have a list that only includes positive integers:
my_list = [1, 2, 4, 7, 9, 10, 15, 16]
The list is sorted.
What would be the most "pythonic" way to check whether the list contains any sequence of x consequtive number? It shouldn't matter whether the sequence starts at the beginning of the list, or ends at the end of the list - as long as it's in the list, it should return true. For instance, if I wanted to check if the following list contains a 4-number sequence:
my_list = [1, 3, 4, 5, 6, 8, 10]
It should return true due to [3, 4, 5, 6]
I have seen multiple StackOverflow questions about "finding number sequences in lists", however none of them dealt with looking for a sequence in only a portion of the list. (What I found was useful only if the goal was to check whether the entire list is sequential.)
Here's a one liner:
def has_sequence(L, seq_len):
return any(list(L[i:i+seq_len]) == list(range(L[i],L[i]+seq_len))
for i in range(len(L)-seq_len+1))
def findRun(L, n):
runlen = 0
for i in range(1, len(L)):
if L[i] == L[i-1]+1:
runlen += 1
else:
runlen = 0
if runlen == n-1:
print("Found a run starting at", i-n+1)
Output:
In [451]: L = [1, 3, 4, 5, 6, 8, 10]
In [452]: findRun(L, 4)
Found a run starting at 1
You can try this:
after grouping them with the difference, you just check if any of the groups contains your preferred number of consecutive sequence(in this case 4).
from itertools import groupby
from operator import itemgetter
my_list = [1, 3, 4, 5, 6, 8, 10]
check = False
for key, group in groupby(enumerate(my_list), lambda (i, val): i - val):
g = map(itemgetter(1), group)
if len(g) == 4:
check = True
print(check)
True
I hope this is what you looking for.

Resources