How do I check every element in an appended text in python - python

I am doing the Euler project questions and the question I am on right now is least common multiple. Now I can go the simple route and get the factors and then find the number that way, but I want to make my life hard.
This is the code I have so far in Python:
i = 0
j = 0
count = []
for i in range (1,10):
for j in range(1,11):
k = i%j
count.append(k)
print(count)
Now when I print this out I get an array and every time I goes through the loop, the previous information is appended on with it. How can I make it so that the previous information is not appended?
Second once I get that information how can I look at each value in the array and only print out those elements that are equal to 0? I feel like I have to use the all() function but for some reason I just dont get how to use it.
Any and all help is appreciated.

For your first question, you should know the scope of variable. Just define the variable count inside the outer loop and before the inner loop starts.
You can try this if you want nothing but zero elements.
print [element for element in count if element == 0]

If I understand your question right the answer for your question is like this.
i = 0
j = 0
for i in range (1,10):
# Resetting so that count will not have previous values
count = []
for j in range(1,11):
k = i%j
count.append(k)
# printing all the indexes where the value is '0'
print([index for index, item in enumerate(count) if item == 0])

You know your range of extern loop so you can just write your code in this way :
count = []
for i in range (1,10):
for j in range(1,11):
k = i%j
if(i == 9):
count.append(k)
print(count)
print("Without 0:")
print([x for x in count if x is not 0])

Related

Pattern printing with arrays/tuples

So I'm trying to do this
You will be given a positive integer n > 0 and you will construct a pattern that is made up of n rows:
• Row 0 contains 1 number—the number 1
• Each row is one longer than the one before and follows the pattern that ensues
So if variable n:int = 4, the output would be
[1]
[1,2]
[2,3,5]
[5,7,10,15]
The number in the current array is added to the number immediately above it in the previous array and appended at the end of the current array. Also when starting a new array the last element of the previous array is considered as the first element of the current array.
I apologize if my question is unclear, but I hope after the example and explanation I provided, the question is clearer now.
Here is my code:
def append(n: int):
for x in range(1,n+1):
return(x,x+1)
print(append(n))
When I put n = 4, it doesnt seem to work, what's the problem here?
This will do it:
def func(n):
mylist = []
for i in range(n):
if i == 0:
mylist.append([1])
else:
mylist.append(createnewlist(mylist[i-1]))
return mylist
def createnewlist(a):
newlist = []
for i in range(len(a)+1):
if i == 0:
newlist.append(a[len(a)-1])
else:
value = a[len(a)-1]
for m in range(i):
value += a[m]
newlist.append(value)
return newlist
print(func(6))
I don't think your code will return the pattern you want to show. Here's a little code I wrote to print that pattern but there are two loops running, if you could optimize that you could do it or else use the code just as it is.
n=4
arr=[1]
brr = [1]
print(brr)
for i in range(0,n-1):
brr = arr[i:]
for k in range(0,len(arr)):
brr.append(arr[k]+brr[k])
arr = brr
print(brr)

List index out of range, apparently nothing wrong

transposta = []
nova_linha = []
for i in range (len(matriz)):
for j in range(len(matriz[i])):
nova_linha.append(matriz[i][j])
i+=1
transposta.append(nova_linha)
j+=1
nova_linha = []
return transposta
I am getting the list index out of range error in line nova_linha.append(matriz[i][j])
why is this happening?
This would work fine:
for i in range (len(matriz)):
for j in range(len(matriz[i])):
nova_linha.append(matriz[i][j])
transposta.append(nova_linha)
nova_linha = []
However, you added in lines that do i += 1 and j += 1. A for loop over a range already takes care of that for you.
Normally, that would be as harmless as it is useless, because your change would just get thrown away the next time through the loop—but you also got them backward. So now, each time through the inner loop, you increment i, and pretty quickly you run off the bottom of the matrix.

Negative number finder in index and occuring

Write a func/on first_neg that takes a (possibly empty) list of
numbers as input parameter, finds the first occurrence of a
nega/ve number, and returns the index (i.e. the posi/on in the
list) of that number. If the list contains no nega/ve numbers or it
is empty, the program should return None. Use while loop (and
not for loop) and your while loop should stop looping once the
first nega/ve number is found.
This is the question my teacher asked me any ideas this what i did:
def first_neg(list):
count = 0
for number in list:
if number < 0:
count += 1
return count
Dosent seem to work properly i just joined 1st post hope can get some help
x = [1,2,3,-5]
def first_neg(list):
count = 0
for number in list:
count += 1 #moved it outside of the if
if number < 0:
return count
print(first_neg(x)) #prints 4
You want to increment count not when you've found the answer but everytime the forloops loops. Note that this method returns 4 which is the fourth item in the list, not the index, Index of the list starts from 0 so to access it would be 3. Take our list x = [1,2,3,-5], -5 is in the fourth slot of the list, but to access it we have to call x[3] since lists starts at 0 indexing.
If you want to return the index of the list where the first negative number is found try this:
x = [1,2,3,-5]
def first_neg(list):
for count, number in enumerate(list):
if number < 0:
return count
print(first_neg(x)) # prints 3
This is because enumerate creates a "pairing" of the item in the list and it's the current count. Enumerate just counts from 0 everytime it gets an item out of the list.
Also as a side note ( I didn't change it in my answer since I wanted you to understand what's going on ). Don't name your variables keywords like list, tuple, int, str... Just a bad idea and habit, it works as you can see but it can cause issues.
Return the index immediately once you encounter the negative element. Increment the index otherwise:
def first_neg(lst):
count = 0
while count < len(lst):
if lst[count] < 0:
return count
count = count + 1
return None
Note : Better if you use enumerate() rather than using extra count variable. The code you mentioned is not written in pythonic way.
You may try this as well:
def first_neg(lst):
res = [i for i,x in enumerate(lst) if x<0]
return None if res == [] else res[0]
The code above can be improved using generators as suggested by #Chris_Rands.

Python-Merge sort difficulties

I attempted to implement a merge sort, here is my code:
def mergeSort(array):
result=[]
n=len(array)
if n==1:
result=array
else:
a=round(n/2)
first=mergeSort(array[0:a])
second=mergeSort(array[a:n])
for i in range(len(first)):
for j in range(len(second)):
if first[i]<second[j]:
result.append(first[i])
i=i+1
else:
result.append(second[j])
j=j+1
return result
a=[5,4,1,8,7,6,2,3]
b=mergeSort(a)
print(b)
Unfortunately, the result turns out to be [1]. What is wrong with my function?
A number of things...
Firstly, this is a recursive function, meaning you cannot create a list within the function, as you did here:
result=[]
This will simply reset your list after every recursive call, skewing your results. The easiest thing to do is to alter the list that is passed as a parameter to merge sort.
Your next problem is that you have a for loop within a for loop. This will not work because while the first for loop iterates over first, the second for loop will iterate over second for every increment of i, which is not what you want. What you need is to compare both first and second and extract the minimum value, and then the next minimum value, and so on until you get a sorted list.
So your for loops need to be changed to the following:
while i < len(first) and j < len(second):
Which leads me to final problem in your code. The while loop will exit after one of the conditions are met, meaning either i or j (one or the other) will not have reached len(first) or len(second). In other words, there will be one value in either first or second that is unaccounted for. You need to add this unaccounted value to your sorted list, meaning you must implement this final excerpt at the end of your function:
remaining = first if i < j else second
r = i if remaining == first else j
while r < len(remaining):
array[k] = remaining[r]
r = r + 1
k = k + 1
Here r represents the index value where the previous while loop broke off. The while loop will then iterate through the rest of the remaining values; adding them to the end of your sorted list.
You merge sort should now look as follows:
def mergeSort(array):
if len(array)==1:
return array
else:
a=round(len(array)/2)
first=mergeSort(array[:a])
second=mergeSort(array[a:])
i = 0
j = 0
k = 0
while i < len(first) and j < len(second):
if first[i]<second[j]:
array[k] = first[i]
i=i+1
k=k+1
else:
array[k] = second[j]
j=j+1
k=k+1
remaining = first if i < j else second
r = i if remaining == first else j
while r < len(remaining):
array[k] = remaining[r]
r += 1; k += 1
return array
I tried to not alter your code as much as possible in order to make it easier for you to understand. However, if your difficulty in understanding what I did persists, try de-bugging your merge sort using multiple print statements so that you can follow the function's progress and see where it goes wrong.

List index out of range while counting Python

I have a little problem - I need to iterate through a list of lists (lines in a file) and count how many times the lines begin with six or seven. It was no problem, but I also need to remove the items which repeat themselves, e.g. if I have this: [6,6,7,7,6], I need to do this out of it: [6,7,6] - it is the number of switches that counts. But somehow the list index is always out of range. Why?
Thank you!
def number_of_switches(list):
counter = []
for element in li:
if int(element[0]) == 6 or int(element[0]) == 7: counter.append(element[0])
else: pass
i = 0
for i in (0, len(counter)):
if counter[i] == counter[i+1]: counter.remove(counter[i+1])
print 'number of switches is', len(counter)-1 #the first number doesn't count as switch, hence '-1'
for i in (0, len(counter)) only iterates over two elements: 0, and the length of counter. It does not count up from 0 to the length. For that you need range:
for i in range(len(counter))
However, you should not do that either. Think about what happens each time you remove an element: the list is now one shorter, but you are iterating until the end of the original list. So you will quickly get an IndexError. You need to append the non-matching elements to a new list, rather than removing from the current one.
When you write:
for i in (0, len(counter)):
That means for in those two values: 0 and len(counter) and, len(counter) is the index out of range.
I think you meant:
for i in range(0, len(counter)):
You should be doing for i in range(len(counter)): and also if counter[i] == counter[i+1]: will give an error in this range. You need to handle the end case.
This might be a better solution:
def number_of_switches(list):
counter = []
prev = li[0]
for element in range(1, len(li)):
if int(li[element][0]) != prev:
count.append(int(li[element][0]))
print 'number of switches is', len(counter)-1 #the first number doesn't count as switch, hence '-1'

Categories