Get element range in list and swap - python-3.x

I want to swap element list by range in python
my code is
List = [1,2,3,4,5,6]
def swap(list_, a, b):
list_[a], list_[b] = list_[b], list_[a]
swap(List, 0, 5,)
print(List)
and my output is
[6, 2, 3, 4, 5, 1]
but what i want is swapped by list index range
# my expected output
n = 2 (add var by input)
#and it swapped to this
[3, 4, 5, 6, 1, 2]

You can use something like this:
def swap(List, n):
return List[n:] + List[:n]
List = [1,2,3,4,5,6]
n = input()
print(swap(List, n))
Using slice (:) you can split your list in sublists by index. Then you can recombine them in the return statement

Related

How do you append a value to a list by a certain frequency?

I'm writing a program to analyse a frequency table with different functions (mean, median, mode, range, etc) and I have the user inputting their data in two lists and then converting those answers into lists of integers
values_input = input('First, enter or paste the VALUES, separated by spaces (not commas): ')
freq_input = input('Now enter the corresponding FREQUENCIES, separated by spaces: ')
values = values_input.split()
freq = freq_input.split()
data_list = []
For every value, I want the program to append it to data_input by the corresponding frequency.
For example (desired result):
If values was: 1 2 3 4
and frequency was: 2 5 7 1
I want data_list to be:
[1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4]
At the moment I have this:
for i in range(len(values)):
j = 3
while j != 0:
data_input.append(values[i])
j -= 1
But that only appends the values to data_input 3 times instead of the frequency
a = input("First, enter or paste the VALUES, separated by spaces (not commas): ").split()
b = input("Now enter the corresponding FREQUENCIES, separated by spaces: ").split()
a = [int(i) for i in a]
b = [int(i) for i in b]
x = []
y = 0
for elem in a:
temp = []
temp.append(elem)
x.append(temp * b[0+y])
y += 1
final = []
for lst in x:
for elem in lst:
final.append(elem)
print(final)
I am also a newbie. I know there are more efficient ways, but for now I have come up with this.
You can use list multiplication to create a list of each value with the appropriate frequency. zip the two lists together to get the matching values for each index:
values = [1,2,3,4]
freq = [2,5,7,1]
result = []
for v, f in zip(values, freq):
result += [v] * f
Output:
[1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4]

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

the terminal doesn't display when i compile the code

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

Finding overlap of given list

Find overlap which given list, a list of intervals like [2, 4], returns whether any two intervals overlap. Boundary overlaps don't count.
Example:
`>>> check_overlap(li=[[1,5], [8,9], [3,6]])
True
>>> check_overlap(li=[[1,5], [5,6]])
False`
data= [[1, 5], [8, 9], [3, 6]]
values = [[value for value in range(elem[0], elem[1])]for elem in data]
print(values)
[[1, 2, 3, 4], [8], [3, 4, 5]]
After that i want to know how to check with each element in a list whether any two intervals overlapping.
For checking the overlap, I would sort the bigger list with first element of the sublists, and check the 2nd element of a sublist is bigger than the 1st element of the next sublist.
def overlap(li):
li.sort(key=lambda x: x[0])
for i in range(len(li)-1):
if li[i][1] > li[i+1][0]:
return True
return False
print(overlap([[1,5], [8,9], [3,6]]))
print(overlap([[1,5], [5,6]]))
True
False
I would use the itertools.combinations function as such:
from itertools import combinations
def check_overlap(li):
lists = [list(range(a, b)) for a, b in li] # Shorter way of your values = ... line
for l1, l2 in combinations(lists, 2):
if any(l in l2 for l in l1):
return True
return False
The combinations(lists, 2) call gives you all possible unique combinations of different elements.
Next, the any() function takes any iterable and returns True if any of the elements in the iterable are True (or rather 'truthy'). In this case, the l in l2 for l in l1 is a generator expression, but would work the same with square brackets around it to explicitly make it into a list first.
You can create sets and check for intersection -
data= [[1, 5], [8, 9], [3, 6]]
sets_from_data = [set(range(*l)) for l in data]
intersection_exists = bool(max([len(a.intersection(b)) for a in sets_from_data for b in sets_from_data if a != b]) > 0)
intersection_exists
# True
If you only have integers you can indeed use range to do this test:
def check_overlap(li):
ranges = [range(r[0]+1, r[1]-1) for r in li]
return any(any(e-1 in r for r in ranges) for l in li for e in l)
On the other hand, if you have floating point values you'll have to tests both bounds of the interval individually (using < and >):
def is_in_range(value, boundaries):
m, M = boundaries
return value > m+1 and value < M-1
def check_overlap(li):
return any(any(is_in_range(e, r) for r in li) for l in li for e in l)

what is list concatenation and how to add element to array?

catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):')
name = input()
if name == '': break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
Can someone please explain this.
catNames = catNames + [name] # list concatenation
catNames is an empty list. By summing a list to another list ([name]) you get a combined list. such as:
ls1 = [1]
ls2 = [2]
ls3 = ls1 + ls2
print(ls3)
output:
[1, 2]
If my understanding is correct, you are asking for clarification regarding list concatenation vs. the append() function.
List concatenation is the process of combining two or more lists to form one larger list that a variable can be set equal to.
Append() simply adds an item to a list.
Here is an example of concatenation.
myList = [0, 2, 5]
myList2 = [1, 45, 78]
#list concatenation
myList3 = myList + myList2
#output if printed would be [0, 2, 5, 1, 45, 78]
VS. append which simply adds an item
lst = [0, 1, 2]
lst.append(3)
print(lst)
#outputs [0, 1, 2, 3]

Resources