I'm a super n00b in python.
I have been struggling with finding proper solution.
Here is the list, L = [0, 0, 0, 3, 4, 5, 6, 0, 0, 0, 0, 11, 12, 13, 14, 0, 0, 0, 18, 19, 20], and each of the items refers to location in the list.
I wanted to make list from the upper list, showing smaller lists inside the list, and each of the elements represents starting location of the series, end of the series and number of elements. This should be [[3, 6, 4], [11, 14, 4], [18, 20, 3]]. How could I write code for this? Following is what I have done so far.
target = []
target.append([])
target.append([])
target.append([])
L = [0,0,0,0,4,5,6,7,8,9,0,0,0,13,14,15,0,0,0,19,20,21]
for i in L :
if i == 0 :
L.remove(i)
continue
elif i != 0 :
startpoint = i
i = i * i
while i != 0 :
i += 1
continue
else :
j = i
endpoint = i - 1
break
target[0].append(startpoint)
target[1].append(endpoint)
target[2].append(j)
About your code one mistake is that in following while :
while i != 0 :
i += 1
You must not increase i you need to increase the index of elements not itself!then continue to appending when you find a none zero element!
But as a more pythonic way You can use itertools.groupby with a list comprehension :
>>> from itertools import groupby
>>> [[i[0],i[-1],len(i)] for i in [list(g) for _,g in groupby(L,key=lambda x:x!=0)]if i[0]!=0]
[[3, 6, 4], [11, 14, 4], [18, 20, 3]]
Note that groupby returns the grouped elements as a generator (g) and when you want to loop over it you dont need to convert it to list but in this case as we need the length we must convert to list till we can use len function.
Here's a version based on your attempt:
L=[0,0,0,3,4,5,6,0,0,0,0,11,12,13,14,0,0,0,18,19,20]
target = []
i = 0
while i < len(L):
if L[i] == 0 :
i += 1
continue
start = i
while i < len(L) and L[i] != 0:
i += 1
target.append((L[start],L[i-1],i-start))
Related
Given a set of integers numbers = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9] containing at least two zeros. Print the sum of numbers from the given set located between the last two zeros (if the last zeros are in a row, then print 0).
My attempt:
numbers = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
index_of_first_zero = 0
i = 0
while i < len(numbers):
if numbers[i] == 0:
index_first_zero = 1
break
i += 1
index_of_last_zero = len(numbers) - 1
i = len(numbers) - 1
while i >= 0:
if numbers[i] == 0:
index_of_last_zero = i
break
i -= 1
summa = 0
while i in range(index_of_first_zero+1, index_of_last_zero):
summa += numbers[i]
print("Summa =", summa)
But unput is Summa = 0
Can you help me please?
It's much easier to reverse the list and look for the first two zeros.
>>> numbers = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
>>> numbers_rev = reversed(numbers)
>>> sum_ = 0
>>>
>>> for x in numbers_rev:
... if x == 0:
... break
>>>
>>> for x in numbers_rev:
... if x == 0:
... break
... sum_ += x
>>>
>>> sum_
2
Alternative:
numbers = [10, 0, 11, 5, 3, 0, 6, 0, 2, 5, 6, 0, 6, 9]
numbers_rev = numbers[::-1]
sum_ = 0
for x in numbers_rev[numbers_rev.index(0)+1:]:
if x == 0:
break
sum_ += x
This should do the trick...
a = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
i1 = a[::-1].index(0)
i2 = a[::-1].index(0,i1+1)
print("Summa =",sum(a[len(a)-i2:len(a)-i1]))
I hope this makes it clear :)
#take your original list
numbers = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
#reverse the list
numbes = numbers.reverse()
#make clear that the first zero has not been encountered
encountered_zero = False
#set the temporary sum to 0
cur_sum = 0
#for every number in your list
for number in numbers:
#if it's a zero, and you haven't passed any yet
if number == 0 and not encountered_zero:
#mark it
encountered_zero = True
#skip the rest of the iteration
continue
#if you have already encountered a zero
if encountered_zero == True:
#add every number to the sum
cur_sum += number
#if you encounter another zero
if encountered_zero == True and number == 0:
#break out of the loop, you're done
break
#here you have your answer
summa = cur_sum
print("Summa =", summa)
There are a few mistakes in your program...
One mistake in your program is that in the final part you're telling the script: "While the variable i is in the iterator range do [...]"
However, you should put a for loop there, not a while, changing it to:
summa = 0
for i in range(index_of_first_zero+1, index_of_last_zero):
summa += numbers[i]
print("Summa = ", summa)
Now that part of the program should work properly, because i in the for loop will be replaced with the values in the range iterator.
Instead, with the while, i takes index_of_last_zero as value, so it will never be in the range iterator.
However, the second error is a logical one: you have to sum the numbers between the last two zeros, not between the first and the last one, so the best thing to do is to reverse the list as other users already answered, so the entire program has to change:
original_list = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
reversed_list = reversed(original_list)
my_sum = 0
for num in reversed_list:
if num == 0:
# it breaks here because it found the first zero,
# and then it will continue the cycle from the next element
break
# Now it won't loop again from the beginning, but from where it broke before.
for num in reversed_list:
if num == 0:
break
my_sum += num
print(my_sum) # -> 2
This program will work, thanks to #timgeb, and works with reversed() which is a built-in function that returns an Iterator object.
Here will be clarified to you what is an Iterator and how to work with it.
Anyway, I'll put here another solution that won't use that function.
original_list = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
reversed_list = [] # we'll create it manually
my_sum = 0
# let's create here the reversed_list
for i in range(len(original_list) - 1, 0, -1):
reversed_list.append(original_list[i])
while i < len(reversed_list):
if reversed_list[i] == 0:
# it breaks here because it found the first zero,
# and we store the index of the first zero.
index_first_zero = i
break
i += 1
# Now it won't loop again from the beginning, but from where it broke before.
for i in range(index_first_zero, len(reversed_list)):
if reversed_list[i] == 0:
break
my_sum += reversed_list[i]
print(my_sum) # -> 2
AN implementation of Crohn(Крона) algorithm used in Scheduling theory, is it possible to change the data of the current index in a for loop in python?
I have a code like so;
link to the full code
#list1 is a 2d array
list1 = [[12, 3, 17], [14], [10, 12, 15]]
cond = 1
while cond:
d = delta(sum_calc(list1))
#delta() finds the difference between the list with the highest sum
#and the list with the minimum sum, then returns the
#difference(d[0]), index_of_list_with_max_sum(d[1]), #index_of_list_with_min_sum(d[2])
#d = [23, 2, 1]
if cond == 0:
break
else:
for i in list1[d[1]]:
if d[0] > i:
move(list1[d[1]], list1[d[2]])
#move() moves the min element from list1, to list2
else:
cond = 0
what I am trying to do is, given an index, loop through the elements of that list, then check if num is greater than i (element), after that we do some operations, like moving the smallest element from the current list we are looping from, to another list. then we have some operations, after that I want to change the value of i, to something like
#the index might change
i = l[index]
the problem I am facing is that when I do that, it continues looping from the first index.
Is there a way I can reset it, so that it starts looping from other elements?
I HAVE USED A WHILE LOOP, because I want the procedure to repeat itself and until d[0] !> i:
#since the list with the highest sum is list1[2], we got 2 from d,
#next step is to loop through the elements in that list and check if
#there's an element which is less than d[0](the difference between max and min sum)
#expected results
#after first iteration
list1 = [[12, 3, 17], [14, 10], [12, 15]]
d = [8, 0, 1]
#after second iteration
list1 = [[12, 17], [14, 10, 3], [12, 15]]
d = [2, 0, 1]
#the problem is it stops here, I want it to calculate delta again then #repeat the process, but after debugging, i found that in the second #iteration i = 15, which the second element of the list, but it should #be like that.
Try to combine while loop with index ?
example:
lst = [1,2,3]
idx = 0
while idx < len(lst):
print(lst[idx])
idx += 1
if idx == len(lst):
# Reset index
idx = 0
EDIT
After debugging I found your errors - You havent been assigning the new delta result to d where you have been referencing from your code thus you never got the new indexes
cond = True
idx = 0
while cond and idx < len(l[d[1]]):
if d[0] > l[d[1]][idx]:
move(l[d[1]], l[d[2]])
s = sum_calc(l)
d = delta(s)
print("l =", l)
print("s =", s)
print("d =", d)
print("")
idx = 0
else:
cond = False
idx += 1
Output:
l = [[12, 3, 17], [14, 10], [12, 15]]
s = [32, 24, 27]
d = [8, 0, 1]
l = [[12, 17], [14, 10, 3], [12, 15]]
s = [29, 27, 27]
d = [2, 0, 1]
Write a program with the definition of a function named Array_Swap() that will accept an integer list & its size as arguments and the function will swap elements in such a way that the first element is swapped with the last element, the second element is swapped with the second last element and so on, only if anyone or both the elements are odd and display the result.
If initially, a list of seven elements is: [5, 16, 4, 7, 19, 8, 2], the contents of the list after the execution should be:
[2, 16, 19, 7, 4, 8, 5].
def Array_Swap(List,Size):
for i in range (Size//2):
List[i]=List[Size//2-i]
print(List)
L=[]
n=int(input("Enter number of elements"))
for i in range(n):
x=int(input("Enter element"))
L.append(x)
Array_Swap(L,len(L))
The size/length of the list is not relevant because it can be obtained by len(list). And even then it's not required to conditionally swap items in the list. I suggest that the Size parameter be removed, but considering it's an assignment, it can be given a default of None so that it can be ignored by the caller if desired.
The following algorithm zips the input list with its reverse to form pairs relative to their index from the front and end of the list respectively, i.e. the first and last items are paired, the second and second last are paired, etc. Once the items are paired it is simply a matter of iterating over the list and emitting the second number of the pair if either number is odd, or the first number if neither is odd - effectively swapping the pairs as required.
This is done in-place (that's what the List[:] does) with a list comprehension.
def ArraySwap(List, Size=None):
List[:] = [b if (a % 2 or b % 2) else a
for a, b in zip(List, reversed(List))]
print(List)
>>> l = [5, 16, 4, 7, 19, 8, 2]
>>> ArraySwap(l)
[2, 16, 19, 7, 4, 8, 5]
>>> l
[2, 16, 19, 7, 4, 8, 5]
>>> l = list(range(1,30))
>>> ArraySwap(l)
[29, 2, 27, 4, 25, 6, 23, 8, 21, 10, 19, 12, 17, 14, 15, 16, 13, 18, 11, 20, 9, 22, 7, 24, 5, 26, 3, 28, 1]
>>> ArraySwap([1])
[1]
>>> ArraySwap([])
[]
To swap two elements in the list, use the pattern a, b = b, a.
If i is the index of a list item, it's opposite/mirror element is -(i+1), or - i - 1.
so for the 0th element (first one), the mirror is -(0+1), = -1
using that as the indexer for the element, swap the two list elements IF
check that at least one of them is odd before swapping:
def Array_Swap(List,Size):
for i in range (Size // 2):
if List[i] % 2 == 1 or List[-(i+1)] % 2 == 1:
List[i], List[-(i+1)] = List[-(i+1)], List[i]
print(List)
L = [5, 16, 4, 7, 19, 8, 2] # use your input blocks as before, this is an example
Array_Swap(L,len(L))
Output: [2, 16, 19, 7, 4, 8, 5]
(And if L = [5, 16, 4, 7, 19, 8, 1, 2], output is [2, 1, 4, 19, 7, 8, 16, 5].)
Btw, you don't need to pass in the size of the list as a parameter.
You could do just: for i in range(len(List) // 2)
Another solution:
def Array_Swap(List, Size=None):
if Size is None:
Size = len(List)
for (i, j) in zip(range(Size // 2), range(Size - 1, Size // 2, -1)):
if List[i] % 2 or List[j] % 2:
List[i], List[j] = List[j], List[i]
print(List)
Alternatively:
Size parameter is redundant since python's list instance knows its own size
Use bitwise operatos & | >>... possibly cheaper than modulus % and divide / operations.
def Array_Swap(List):
for i in range(len(List) >> 1):
if (List[i] | List[-i-1]) & 1:
List[i], List[-i-1] = List[-i-1], List[i]
print(List)
The standard way to swap two variables in Python is:
a, b = b, a
In this case, you would do:
lst[i], lst[size - i - 1] = lst[size - i - 1], lst[i]
which swaps the ith element with the element that is at index size - i - 1 (i.e. the ith index from the end).
The other issue with your code is that it doesn't check whether either of the elements being swapped are odd, which you can resolve by adding the condition:
if lst[i] % 2 or lst[size - i - 1] % 2:
before doing the swap. This uses the modulo operator (%) to check the parity of the elements. Taking a number modulo 2 will return 1 if the number is odd. If either are odd (1 has a truth value of True), the condition would succeed and the swap will be performed.
Finally, your function was printing the list, rather than returning it. Its usually best to return a result and print the returned result.
The full working version, with the above three changes is as follows:
def list_swap(lst, size):
for i in range(size // 2):
if lst[i] % 2 or lst[size - i - 1] % 2:
lst[i], lst[size - i - 1] = lst[size - i - 1], lst[i]
return lst
l = []
n = int(input("Enter number of elements: "))
for _ in range(n):
x = int(input("Enter element: "))
l.append(x)
result = list_swap(l, len(l))
print(result)
Also note, I've changed all the variables to be lowercase, which is standard in Python.
With your shown example:
Enter number of elements: 7
Enter element: 5
Enter element: 16
Enter element: 4
Enter element: 7
Enter element: 19
Enter element: 8
Enter element: 2
[2, 16, 19, 7, 4, 8, 5]
If I have two numpy arrays of the same size.
ArrayOne = np.array([ 2, 5, 5, 6, 7, 10, 13])
ArrayTwo = np.array([ 8, 10, 12, 14, 16, 18, 24])
How can I count how many elements there are until the beginning of the array. Unless the condition ArrayOne >= ArrayTwo is satisfied. In which case how many elements until that condition. Then make an array out of the result.
So as an example for element [0] there are 0 elements in front. For element [1] there is 1 element in front, and ArrayOne >= ArrayTwo wasn't satisfied. At element [5] in ArrayOne is bigger than element[0] in ArrayTwo so there are four elements until element [1] in ArrayTwo Etc.
Giving the result
result = np.array([ 0, 1, 2, 3, 4, 4, 3])
Thanks in advance.
Basically, at index i you have the value
value = i -count(how often element i in array one was bigger than array two until index i)
Because I'm on mobile with damn autocorrect, I rename the two arrays to a and b.
def get_value(a, b, i):
max_value = a[i]
nb_smaller_elements = sum(1 for el in range(i) if b[el] < max_value)
return i - nb_smaller_elements
I think I got it. Using #Paul Panzer 's answer, I made a for loop that goes through the list.
def toggle(ArrayOne,ArrayTwo):
a = 0
sum = -1
linels = []
for i in range(len(ArrayOne)):
sum += 1
a = sum - np.searchsorted(ArrayTwo, ArrayOne[i])
linels.append(a)
return np.array(linels)
I get the result
linels = np.array([ 0, 1, 2, 3, 4, 4, 3])
I hope anyone can help me with the following. I have a list called: 'List'. And I have a list called X.
Now I would like to check whether the value in the third column of each row in List is smaller than (<) X or equal/bigger than X. If the value is smaller I would like to add a 0 to the 6th column and a 1 if it is equal/bigger. And for each X I would like the answers to be added to the upfollowing columns to List. So in this case there are 4 X values. So as a result 4 columns should be added to List. My code below probably shows I'm quite an amature and I hope you can help me out. Thank you in advance.
List = [(3,5,6,7,6),(3,5,3,2,6),(3,6,1,0,5)]
X= [1,4,5,6]
for item in X:
for number in row[3] for row in List:
count = 0
if number < item:
List[5+count].append(0)
count += 1
return List
else:
List[5+count].append(1)
count += 1
return List
return List
First, you should know that tuples (parenthesis enclosed lists) are immutable, so you can not change anything about them once they're defined. It's better to use a list in your case (enclosed by []).
List = [[3,5,6,7,6],[3,5,3,2,6],[3,6,1,0,5]]
X= [1,4,5,6]
for item in X: # loop on elements of X
for subList in List: # loop on 'rows' in List
if subList[2] < item: # test if 3rd element is smaller than item in X
subList.append(0); # push 0 to the end of the row
else:
subList.append(1); # push 1 to the end of the row
List = [(3,5,6,7,6),(3,5,3,2,6),(3,6,1,0,5)]
X= [1,4,5,6]
scores = []
for item in List:
scores.append(tuple(map(lambda x: 0 if item[2] < x else 1, X)))
result = []
for item, score in zip(List, scores):
result.append(item + score)
print(result)
# [(3, 5, 6, 7, 6, 1, 1, 1, 1), (3, 5, 3, 2, 6, 1, 0, 0, 0), (3, 6, 1, 0, 5, 1, 0, 0, 0)]
Your indentation is off (you should unindent everything starting with your for statement.
You can't append to tuples (your rows inside the List variable are actually tuples).
Since you are not in a function, return does not do anything.
Since indices start with 0, you should use row[2] for 3rd row.
There are more elements in your X than the number of rows in List.
That being said, you can also use list comprehensions to implement this. Here is a one-liner that does the same thing:
>>> List = [(3,5,6,7,6),(3,5,3,2,6),(3,6,1,0,5)]
>>> X = [1,4,5,6]
>>> print [tuple(list(t[0])+[0]) if t[0][2] < t[1] else tuple(list(t[0]) + [1]) for t in zip(List, X)]
will print
[(3, 5, 6, 7, 6, 1), (3, 5, 3, 2, 6, 0), (3, 6, 1, 0, 5, 0)]
List = [[3,5,6,7,6],[3,5,3,2,6],[3,6,1,0,5]]
X= [1,4,5,6]
elems = [row[3] for row in List]
for i in range(len(elems)):
for x in X:
if elems[i] < x:
List[i].append(0)
else:
List[i].append(1)
print List
And you cannot use return if you are not using functions.
return needs to be called from inside a function. It exits the function and the value specified by return is given back to the function.
So you can't use it in your program.
In the list, each row is actually known as a tuple. Tuples don't have the append function so you can't use that to add to the end of a row.
Also, you can't have two for loops in a single line. (Which is not a problem since we only need one to achieve your output)
I've modified your code so that it looks similar so it's easier for you to understand.
List = [(3,5,6,7,6),(3,5,3,2,6),(3,6,1,0,5)]
X= [1,4,5,6]
for item in X:
n = 0
for row in list:
if row[3] < item:
list[n] = list[n] + (0,)
else:
list[n] = list[n] + (1,)
n = n+1
print List
You need to add with (0,) or (1,) to show that it's a tuple addition. (Or else python will think that you're adding a tuple with an integer)
agree with Selcuk
[edited #1: Thanks #Rawing, I mistyped > as <]
Here is AlmostGr's version simplified:-
List = [[3, 5, 6, 7, 6], [3, 5, 3, 2, 6], [3, 6, 1, 0, 5]]
X = [1, 4, 5, 6]
for num in X:
for item in List:
if num > item[2]:
item.append(0)
else:
item.append(1)
it runs for all elements in X and produces the output:
[[3, 5, 6, 7, 6, 1, 1, 1, 1], [3, 5, 3, 2, 6, 1, 0, 0, 0], [3, 6, 1, 0, 5, 1, 0, 0, 0]]