python swap two elements [duplicate] - python

This question already has answers here:
Python multiple assignment issue (list) [duplicate]
(3 answers)
Tuple unpacking order changes values assigned
(4 answers)
Closed 5 years ago.
I have the following code for a small program:
def get_different_number(arr):
if len(arr) == 0 or arr is None:
return 0
n = len(arr)
for i in range(n):
print (str(i))
temp = arr[i]
while (temp < n and temp != arr[temp]):
temp, arr[temp] = arr[temp],temp
for i in range(n):
if arr[i] != i:
return i
return n
test = [0,1,2,4,5]
get_different_number(test)
however, when it executes, it tells me there is a problem in the line where I swap temp and arr[temp], it gives me a list index out of range error at i is 3 (temp is 4).
When I change that line to arr[temp], temp = arr[temp], temp (reversed assign order), it worked fine. Why is this happening? I thought the a,b = b,a assignment in python assign both elements at the same time?

Related

Python adding to a nested list [duplicate]

This question already has answers here:
Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?
(9 answers)
Closed 4 months ago.
n = int(len(network))
num=[]
for i in range(n):
for j in range(n):
num[i].append(int (between_lists(network[i],network[j])))
return num
this error message I get
num[i].append(int (between_lists(network[i],network[j])))
IndexError: list index out of range
Any of your three indexing operations could be the cause, but num is definitely an empty list, so you can't index it at all. Did you perhaps mean to append to num itself, not to a sublist within num (which has no inner lists at all)?
num.append(int (between_lists(network[i],network[j])))
# ^ removed [i]
Update: Based on your comments, you want a new sublist for each run of the outer loop, so what you really wanted is:
for i in range(n):
num.append([]) # Put in new sublist
for j in range(n):
num[i].append(int(between_lists(network[i],network[j])))
return num

Why does my insertion sort afect both of my arrays when only one is being used? [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 1 year ago.
nums = [100,20,30,90]
temp_arr = nums
answer = 0
print(nums, temp_arr)
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j] :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
insertionSort(temp_arr)
print(nums, temp_arr)
Idk why the array nums is getting sorted when im only trying to sort the temp_arr
nums and temp_arr are the same object in memory. When you write temp_arr = nums, you are introducing a new name (temp_arr) that references that same object as nums
Try:
nums is temp_arr
This should return the result True, since nums is the same object as temp_arr.
To make a new object, you can use:
temp_arr = nums.copy()
This will actually make a copy of the object and make temp_arr reference this new copy. Then try the same test using is, this should now return False
The reason for this is because your assignment
temp_arr = nums
is done by reference and not by value. So to say it simple any changes to "temp_arr" also affects "nums".
You may find a solution for this here: List changes unexpectedly after assignment. Why is this and how can I prevent it?

Looping over list of lists, but if statement does not seem to work correctly [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 2 years ago.
def drawme_five(n):
a = [['.']*n]*n
for i in range(len(a)):
for j in range(len(a[i])):
if i == 0 or i == len(a)-1 or i == int(len(a)/2):
a[i][j] = '*'
if i < int(len(a)/2):
a[i][0] = '*'
elif i > int(len(a)/2):
a[i][len(a)-1]='*'
return a
I expected this code to give an output of a list of lists, where it with '.' and '*' in the form of number 5, but it gives me an output of all asterics. I don't know why the if statements don't work. If it works correctly, and we print one list each line, the output would be in a form of 5, for example if n = 5
. . . .
. . . . *
If you create a 2D matrix in Python by initialising it as [['something']*n]*m, then all lists inside the main list will point to the same location. If edit even one sublist, all sublists will get edited.
Try initialising it as
lst = [['something' for i in range(m)] for j in range(n)]
to get a 2D Matrix of n x m

Is there an elegant way to increment the index of 'arr' without x? [duplicate]

This question already has answers here:
Accessing the index in 'for' loops
(26 answers)
Closed 2 years ago.
I want to improve my Python and I'm curious if there's an elegant way to increment the index of arr in the loop without using integer x in this code:
def predict_one_instance(xSeriesTestVector, xTrainInstances, yTrainCategories, distanceMetric, k):
distances = calc_distances(xSeriesTestVector, xTrainInstances,distanceMetric)
sorted_distances = np.sort(distances)
arr = np.zeros((k,), dtype=int)
x = 0
for el in sorted_distances[:k]:
arr[x] = yTrainCategories.iloc[np.where(distances == el)]
x+=1
return np.bincount(arr).argmax()
Maybe you want to use enumerate?
for item in iterable:
do_stuff(item)
can be turned to
for i, item in enumerate(iterable):
do_stuff(item, i)
where i contains the index of item in the iterable.
So, in your example:
for x, el in enumerate(sorted_distances[:k]):
arr[x] = yTrainCategories.iloc[np.where(distances == el)]
Although you might as well use the good old range if your iterable is a list:
for x in range(k):
arr[x] = yTrainCategories.iloc[np.where(distances == sorted_distances[x])]

Sort list a into ascending order by value using recursion instead of a loop in python [duplicate]

This question already has answers here:
A recursive function to sort a list of ints
(9 answers)
Closed 2 years ago.
How to sort a list into ascending order by value using recursion instead of a loop in python?
For example, to sort [2,0,1] to [0,1,2].
def sort(a):
pos = 0
if pos == 0 or a[pos] >= a[pos - 1]:
pos += 1
return sort(a)
else:
a[pos], a[pos-1] = a[pos-1], a[pos]
pos -= 1
return sort(a)
Here is what I wrote and I know it does not work because the pos is always equal to 0 at first.
How could I fix it?
I test the code below.
enter image description here
Based on this answer, Quick sort is an example of recursive sorting algorithm and can be implemented in Python like this:
def quick_sort(l):
if len(l) <= 1:
return l
else:
return quick_sort([e for e in l[1:] if e <= l[0]]) + [l[0]] +\
quick_sort([e for e in l[1:] if e > l[0]])

Categories