For loops python that have a range - python-3.x

So I'm writing a python code and I want to have a for loop that counts from the the 2nd item(at increment 1). The purpose of that is to compare if there are any elements in the list that match or are included in the first element.
Here's what I've got so far:
tempStr = list500[0]
for item in list500(1,len(list500)):
if(tempStr in item):
numWrong = numWrong - 1
amount540 = amount540 - 1
However the code doesn't work because the range option doesn't work for lists. Is there a way to use range for a list in a for loop?

You can get a subset of the list with the code below.
tempStr = list500[0]
for item in list500[1:]:
if(tempStr in item):
numWrong = numWrong - 1
amount540 = amount540 - 1
The [1:] tells Python to use all elements of the array except for the first element. This answer has more information on list slicing.

Use a function:
search_linear(mainValues, target)
This is the algorithm you are looking for: http://en.wikipedia.org/wiki/Linear_search
All you need to do is set the starting point equal to +1 in order to skip your first index, and than use array[0] to call your first index as the target value.
def search_linear(MainValues, Target):
result = []
for w in Target:
if (search_linear(MainValues, w) < 0):
result.append(w)
return result

Related

IndexError: list index out of range while using nested loops

A = [34,23,1,24,75,33,54,8]
K = 60
solution=[]
for i in range(len(A)):
for j in range(i+1,len(A)):
v=solution[(A[i]+A[j])]
print(v)
Hi, I am trying to get the list with result of individual sums like: 34+23 34+1 34+24 and so on then next 23+1,23+24 and so on.
Your code fails since it's trying to set v to the (A[i]+A[j])th element of solution, which is empty, so that value doesn't exist.
If I understand what you're trying to do, then this should give the desired result.
A = [34,23,1,24,75,33,54,8]
v = [[A[x] + A[i] for i in range(x + 1, len(A))] for x in range(len(A))]
As you can see here,
List index starts from 0 to the (n-1), where n is the len(list).
So A(len(A)) doesn't exist. Which results in the error.
So to fix this replace
len(A)
by
len(A) - 1
inside all instances of range function.

Selection Sort in Python not sorting

I wrote a program for selection sort by first creating a function that finds the minimum element in the array. Then I iterate through the array placing the smallest element in the correct place in the array while replacing the smallest element.
This is my code :
a=[int(input()) for _ in range(6)]
def smallest_element(arr,x):
smallest = arr[x]
d = x
for j in range(x+1,len(arr)):
if arr[j] < smallest:
smallest = arr[j]
d = j
return d
for i in range(0,len(a)):
c = a[i]
if(c > a[smallest_element(a,i)]):
a[i] = a[smallest_element(a,i)]
a[smallest_element(a,i)] = c
print(a)
But the problem is my array is not getting sorted.
Input - [5,2,4,6,1,3]
Output - [5,2,4,6,1,3]
The error seems to be in your loop.
You assign the smallest value found to the current index.
a[i] = a[smallest_element(a,i)]
You then assign the value that was originally stored to the index where the smallest element is located.
a[smallest_element(a,i)] = c
You do however re-calculate the index of the smallest element, which always is the current index - because you just copied the smallest value to the current index.
first approach
I know of two solutions to this problem. First you may only search the index of the smallest element once per loop round. That way you do not re-calculate the index and write to the correct position.
for i in range(0, len(a)):
c = a[i]
indexOfSmallestElement = smallest_element(a, i)
smallestElement = a[indexOfSmallestElement]
if c > smallestElement:
a[i] = smallestElement
a[indexOfSmallestElement] = c
second approach
Another solution is to search the element starting from the current index + 1 instead of the current index, and thus skipping the entry that you've already changed.
Exchange a[smallest_element(a, i)] = c with a[smallest_element(a, i + 1)] = c.
I do however recommend to use the first approach as it recudes the amount of times the array is iterated over.
First, in your code, you have called the smallest_element(arr,x) 3 times which will consume more time for larger arrays. Instead we can store that value to a variable rather calling 3 times.
Secondly you are swapping 2 times one in function body and in if block.
So in the function body , find the current smallest element. Then return that index to main.Then if it is smaller than the present element (in the main for loop), then swap it.
#Find the smallest element
def smallest_element(arr,x):
small = x
for j in range(x+1,len(arr)):
if arr[j] < arr[small]:
small=j
return small
#now compare it with the current element
for i in range(0,len(a)):
c = a[i]
curr=smallest_element(a,i)
if(c > a[curr] and curr!=i):
a[i] = a[curr]
a[curr] = c
print(a)

Can we change for loop result into list with index?

I am currently learning python, I just have one little question over here.
I used for loop and getting a result below.
Here is my code:
def psuedo_random(multiplier, modulus, X_0, x_try):
for i in range(x_try):
place_holder = []
count = []
next_x = multiplier * X_0 % modulus
place_holder.append(next_x)
X_0 = next_x
for j in place_holder:
j = j/modulus
count.append(j)
print(count)
Result:
[0.22021484375]
[0.75439453125]
[0.54443359375]
[0.47705078125]
Can we somehow change it into something like this?
[0.22021484375, 0.75439453125, 0.54443359375, 0.47705078125]
After you initialized a list, you can use append function in the loop.
initialize a list where you want to list these numbers
mylist = []
use this function in your for loop
for i in .....:
mylist.append(i)
It's simple. Do not initialize your list inside the loop. Just place it outside.

Python losing track of index location in for loop when my list has duplicate values

I'm trying to iterate over pairs of integers in a list. I'd like to return pairs where the sum equals some variable value.
This seems to be working just fine when the list of integers doesn't have repeat numbers. However, once I add repeat numbers to the list the loop seems to be getting confused about where it is. I'm guessing this based on my statements:
print(list.index(item))
print(list.index(item2))
Here is my code:
working_list = [1,2,3,4,5]
broken_list = [1,3,3,4,5]
def find_pairs(list, k):
pairs_list = []
for item in list:
for item2 in list:
print(list.index(item))
print(list.index(item2))
if list.index(item) < list.index(item2):
sum = item + item2;
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
### First parameter is the name is the list to check.
### Second parameter is the integer you're looking for each pair to sum to.
find_pairs(broken_list, 6)
working_list is fine. When I run broken_list looking for pairs which sum to 6, I'm getting back (1,5) but I should also get back (3,3) and I'm not.
You are trying to use list.index(item) < list.index(item2) to ensure that you do not double count the pairs. However, broken_list.index(3) returns 1 for both the first and second 3 in the list. I.e. the return value is not the actual index you want (unless the list only contains unique elements, like working_list). To get the actual index, use enumerate. The simplest implementation would be
def find_pairs(list, k):
pairs_list = []
for i, item in enumerate(list):
for j, item2 in enumerate(list):
if i < j:
sum = item + item2
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
For small lists this is fine, but we could be more efficient by only looping over the elements we want using slicing, hence eliminating the if statement:
def find_pairs(list, k):
pairs_list = []
for i, item in enumerate(list):
for item2 in list[i+1:]:
sum = item + item2
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
Note on variable names
Finally, I have to comment on your choice of variable names: list and sum are already defined by Python, and so it's bad style to use these as variable names. Furthermore, 'items' are commonly used to refer to a key-value pair of objects, and so I would refrain from using this name for a single value as well (I guess something like 'element' is more suitable).

python3 string to variable

I am currently trying to implement Conway's Game of Life in a Code, and therefore built a function which generates the coordinates depending of the size of the window.
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = []
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords.append ('x'+str(n)+'y'+str(i))
return coords
Yet, I would like to randomly assign values to the resulting strings, to mark them either as alive (1) or dead (0). However they only way to convert a string to a variable name known to me is via a dict and var(), but however, it is essential for the further code that the coordinates stay sorted, as I want to be able to iterate over the ordered items and put the cursor accordingly to the coordinates name. Something like:
print ('\033['+X_COORD+';'+Y_COORD+'f'+ x1y5)
if e.g. x1y5 is the corresponding value (0 or 1) of the variable
Is there a convenient method how to either do this via a dict or how to convert the name of the strings to variable names?
Or probably. If I keep one dict and one list and store the coordinate names in the list and the values in the dict?
Thank you in advance!
kyril
You use a dictionary:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = {}
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords['x'+str(n)+'y'+str(i)] = 0
return coords
You then access the value with
coords[x][y]
And change it like so:
coords[x][y] = 1
Now, of course this converting of coordinates to strings is completely pointless. Simply use a list of lists:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = [[0]*num_x for x in range(num_y)]
return coords
And I don't know why you add 1 to the coordinates either:
def coords_maker(num_x, num_y):
return [[0]*num_x for x in range(num_y)]

Resources