number = [1,2,3,4,63,2]
max = number[0]
for large in number:
if large > max:
max = large
print(max)
This Python code prints the largest number in a list and it works, but I am not sure how it works. On the 5th line when max = large I am not quite sure that this if statement is true in the first place because the first item in the list is not bigger than max but it is equal to it.
number = [1,2,3,4,63,2]
max = number[0]
for large in number:
if large > max:
max = large
print(max)
Explanation:
First iteration: max=1 and large=1 so if 1>1 then max=large else the max will the previous number as we assigned 1 initially.
2nd iteration: max will have 2.
.
.
.
4nd iteration: max will have 4.
5nd iteration: max will have 63.
6th iteration: max will have still 63 since 2 is not > 63.
I think I understood your confusion. The statement for large in number: assigns each element of number to large successively no matter what happens in the loop. Python for loops do not have a condition, unlike C-like for loops.
The statement if large > max: is not the condition for the loop to continue. It is totally independent of the loop statement. As you observed correctly, it is False for the first iteration, but that has no effect on what the for loop is doing. Only the value of max is not updated.
It's conventional not to use names like max that shadow built-in names. Something like max_ or max_value is better.
I am not quite sure that this if statement is true in the first place because the first item in the list is not bigger than max but it is equal to it.
Your current loop works perfectly fine and in fact omits useless reassignment of the max variable.
number = [1,2,3,4,63,2]
max = number[0]
for large in number: # For every item in the list of numbers
if large > max: # if a currently selected item is larger than the current maximum
max = large # assign that value of that item to be the new maximum
print(max)
For the first iteration you will get a False. For the given list all other iterations will yield a True. However if you add items that are equal like
[ 1, 1, 2, 3, 4, 4, 4, 4, 5 ]
you will soon discover that the current check you have is quite efficient. Why? Because if you add equality to the check (in which case your IF condition will return more times True including the first iteration)
if large >= max:
max = large
you will end up with pointless reassignment of max every time you get to a value that is equal to the current maximum. So for the list I've given above as an example you will go through 4 reassignments that are completely useless - one for the second 1 and three for the three 4 after the first 4 (marked with * below):
[ 1, 1, 2, 3, 4, 4, 4, 4, 5 ]
| | | |
* * * *
There is one thing I would add to solution and that is omitting the first item:
for large in number[1:]:
...
For your comparison of numbers you will not see much of a difference but if you compare larger objects it will.
Related
With reference to Kelly's Short O(n) solution at
Python sum of number in array, ignoring sections of specific numbers
Can someone explain to me why the numbers between 6 and 9 are not included in the sum? I have tried deriving the answer myself using:
def summer_70(lst):
it = iter(lst)
return sum(x for x in it
if x != 4 not in it)
print(summer_70([4, 5, 6, 7, 8, 9])) #Output 5 not 35 ??
But I still do not understand how the code executes.
Thanks in advance :D
I'll take the code from Kelly's answer as your's lacks the or operator.
Generate iterator from the given list
it = iter(lst)
For each entity in the given iterator, start summing it.
return sum(x for x in it
if x != 6 or 9 not in it)
If the current value we are iterating not equals 6, the or condition already return True and it adds it to the sum.
Once we find x == 6, we go into the other condition
9 not in it
Currently, the iterator contains only the remaining values we didn't sum.
This condition will iterate the rest of the values until it finds a 9.
If it didn't found a 9, then we summed only the values until the first 6.
If it finds a 9, the iterator will point on the next value after the 9 (this way we skipped the values between 6 to 9), and we'll do the same if condition again (sum if it's not 6, or check again until we find a 9)
Given
lst = [1,2,6,7,8,9,10]
When we reach the 6, we already summed 1, 2.
Then, the or condition will search for 9 in the remaining list:
[7,8,9,10]
Found 9, and the remaining list:
[10]
Sum 10 and we'll get
1+2+10 = 13
Link to the accepted answer - https://stackoverflow.com/a/68975493/3125312
The code in question
def summer_69(lst):
it = iter(lst)
return sum(x for x in it
if x != 6 or 9 not in it)
Lets work through this with an example.
Say we have a list of numbers
[1,2,6,7,9,5]
and we need calculate the sum skipping any region starting with a 6 and ending with a 9. The sum would be 8.
We can start by trying to solve it using a simpler but longer code
set a counter total to 0 - this will be the default sum
set a flag should_skip to let us know if we need to skip a number or not
iterate through the list and add all numbers but only if should_skip is False
Now the most important question arises - how do we know if we should skip a number? Checking whether a number is a 6 or 9 is not enough as we need a skip a whole section which may include other numbers as well. This is where we make use of the should_skip flag. And we need to check only 2 conditions.
If we hit a 6 in our iteration we know this is the start of the section to skip. so we set should_skip to True
If we hit a 9 in out iteration then this is the end of the section to skip. we can set should_skip to False.
We can add to the total if should_skip is False
Converting this into code looks like
input = [1, 2, 6, 7, 9, 5]
total = 0 # The default sum
should_skip = False
for number in input:
if number == 6:
# start of the section to skip, keep skipping till we reach a 9
should_skip = True
if not should_skip:
# add it to the total!
total += number
if number == 9:
# End of section to skip, we can start adding numbers to the total
should_skip = False
print(total) # 8
If you can understand the above logic then it will be extremely easy to understand the shorter implementation. Lets get back to it and start analyzing.
There are 2 necessary things that both codes are doing. "iterating" through the code and "summming" the numbers that are not in a section to skip.
We wrote the code for it ourselves but Python has inbuilt function for it as well called iter and sum
iter is a function that returns an iterator object. whats special about iterators is that they are memory efficient and that they remove an element when proceeding to the next one.
e.g
if our iterator contains iter(3,6,4)
after one iteration the contents look like iter(6,4)
and after the second iteration there is only one element remaining i.e. iter(4)
sum as the name suggests returns the sum. the default is 0
def summer_69(lst):
it = iter(lst) # turn our input into an iterator object
return sum(x for x in it # add it to the total!
# but wait we need to check if we are in a section to skip first
if x != 6 # number is not a 6,
or 9 not in it # there are no 9s remaining in the iterator so its safe to add
)
Step by Step breakdown:
1st iteration -> x is 1 and `it` is `[1,2,6,7,9,5]`
2nd iteration -> x is 2 and `it` is `[2,6,7,9,5]`
3rd iteration -> x is 6 and `it` is `[6,7,9,5]`
4th iteration -> x is 7 and `it` is `[7,9,5]`
5th iteration -> x is 9 and `it` is `[9,5]`
6th iteration -> x is 5 and `it` is `[5]`
At each iteration the condition being checked is x != 6 or 9 not in it? this is how we know that we are in a section to skip or not.
I have been working on this assignment for about 2 weeks and have nothing done. I am a starter at coding and my teacher is really not helping me with it. She redirects me to her videos that I have to learn from every time and will not directly tell or help me on how I can do it. Here are the instructions to the assignment (said in a video, but made it into text.
Find the mean
Create a program that finds the mean of a list of numbers.
Iterate through it, and instead of printing each item, you want to add them together.
Create a new variable inside of that, that takes the grand total when you add things together,
And then you have to divide it by the length of your array, for python/java script you’ll need to use the method that lets you know the length of your list.
Bonus point for kids who can find the median, to do that you need to sort your list and then you need to remove items from the right and the left until you only have one left
All you’re doing is you need to create a variable that is your list
Create another variable that is a empty one at the moment and be a number
Iterate through your list and add each of the numbers to the variable you created
Then divide the number by the number of items that you had in the list.
Here's what I've done so far.
num = [1, 2, 3, 4, 5, 6];
total = 0;
total = (num[0] + total)
total = (num[1] + total)
total = (num[2] + total)
total = (num[3] + total)
total = (num[4] + total)
total = (num[5] + total)
print(total)
However, she tells me I need to shorten down the total = (num[_] + total) parts into a loop. Here is how she is telling me to do a loop in one of her videos.
for x in ____: print(x)
or
for x in range(len(___)): print (x+1, ____[x])
there is also
while i < len(___):
print(___[i])
i = i + 1
I really don't understand how to do this so explain it like I'm a total noob.
First of all, loops in python are of two types.
while: a while loop executes the code in a body until a condition is true. For example:
i = 0
while(i < 5):
i = i + 1
executes i = i + 1 until i < 5 is true, meaning that when i will be equal to 5 the loop will terminate because its condition becomes false.
for: a for loop in python iterates over the items of any sequence, from the first to the last, and execute its body at each iteration.
Note: in both cases, by loop body I mean the indented code, in the example above the body is i = i + 5.
Iterating over a list. You can iterate over a list:
Using an index
As each position of the array is indexed with a positive number from 0 to the length of the array minus 1, you can access the positions of the array with an incremental index. So, for example:
i = 0
while i < len(arr):
print(arr[i])
i = i + 1
will access arr[0] in the first iteration, arr[1] in the second iteration and so on, up to arr[len(arr)-1] in the last iteration. Then, when i is further incremented, i = len(arr) and so the condition in the while loop (i < arr[i]) becomes false. So the loop is broken.
Using an iterator
I won't go in the details of how an iterator works under the surface since it may be too much to absorb for a beginner. However, what matters to you is the following. In Python you can use an iterator to write the condition of a for loop, as your teacher showed you in the example:
for x in arr:
print(x)
An iterator is intuitively an object that iterates over something that has the characteristic of being "iterable". Lists are not the only iterable elements in python, however they are probably the most important to know. Using an iterator on a list allows you to access in order all the elements of the list. The value of the element of the list is stored in the variable x at each iteration. Therefore:
iter 1: x = arr[0]
iter 2: x = arr[1]
...
iter len(arr)-1: x = arr[len(arr)-1]
Once all the elements of the list are accessed, the loop terminates.
Note: in python, the function range(n) creates an "iterable" from 0 to n-1, so the for loop
for i in range(len(arr)):
print(arr[i])
uses an iterator to create the sequence of values stored in i and then i is in turn used on the array arr to access its elements positionally.
Summing the elements. If you understand what I explained to you, it should be straightforward to write a loop to sum all the elements of a list. You initialize a variable sum=0 before the loop. Then, you add the element accessed as we saw above at each iteration to the variable sum. It will be something like:
sum = 0
for x in arr:
sum = sum + x
I will let you write an equivalent code with the other two methods I showed you and do the other points of the assignment by yourself. I am sure that once you'll understand how it works you'll be fine. I hope to have answered your question.
She wants you to loop through the list.
Python is really nice makes this easier than other languages.
I have an example below that is close to what you need but I do not want to do your homework for you.
listName = [4,8,4,7,84]
for currentListValue in listName:
#Do your calculating here...
#Example: tempVar = tempVar + (currentListValue * 2)
as mentioned in the comments w3schools is a good reference for python.
The following code iterates through the whole matrix filled in with increasing numbers and checks the difference between every element in one row and elements in the same location of the previous row. For every iteration, if this difference of two elements is less than 3, the counter increases and then the loop breaks and continues to the next row. What I would like to do is trying to increase this loop every time there is a counter increase.
In other words, if for instance the loop runs into this condition after checking the first two rows and each row is length 3, the following iterations should be done considering row length = 6, and if this condition is met again later, then the considered row length should be 9 and so on.
To be clear, this code returns 3 but according to what I am trying to do, it should return 1.
I am not sure if this would be possible in python, but I will gladly consider suggestions.
I am sorry for not being clear but this is a bit hard to explain correctly, I will still try my best and feel free to ask me any specific questions that you may have, I'll be happy to answer. In this example, the loop subtracts the second row [4,6,6] from the first one [1,2,4] and since 4-1=3, 6-2=4 and 6-4=2, only the latter is less than 3 therefore k increases by 1. Then in the third with the second row, 7-6=1 which is < 3 therefore 8-6 does not need to be checked, and here too, k increases by 1, so now we have k=2, and in the last row, [9,9,10]-[7,7,8] gives us elements less than 3 therefore our k=3.
Now, what I am trying to do is the following:
once [4,6,6]-[1,2,4] increases k by 1, I would like the 1st and 2nd row to be treated as one sublist [1,2,4,4,6,6], therefore even the 3rd and 4th row will be one sublist [7,7,8,9,9,10] to subtract [1,2,4,4,6,6] from, which would not increase k as there are no elements whose difference is less than 3. If let's say this example had additional rows, then for each k increase, the matrix should be 'reshaped' every time by enlarging the sublist length of 3 additional elements.
I hope I am explaining this clearly enough. If not, feel free to ask.
matrix=[[1,2,4],
[4,6,6],
[7,7,8],
[9,9,10]]
cell_list=[]
for row in matrix:
for cell in row:
cell_list.append(cell)
len_cell_list=(len(cell_list))
len_matrix_row=len(matrix[0])
k=0
k_list=[]
for i in range(1,len(matrix)):
for j in range(len_matrix_row):
if abs(matrix[i][j]-matrix[i-1][j])<3:
k+=1
k_list.append(k)
break
continue
print(k_list[-1])
I think this is what you want.
import numpy
matrix=[[1,2,4],
[4,6,6],
[7,7,8],
[9,9,10]]
k = 0
end_of_matrix = False
changing_matrix = matrix[:]
while not end_of_matrix:
end_current_loop = False
for i in range(1, len(changing_matrix)):
for j in range(len(changing_matrix[i])):
if abs(changing_matrix[i][j] - changing_matrix[i-1][j]) < 3:
k += 1
end_current_loop = True
break
if end_current_loop:
break
if not end_current_loop:
end_of_matrix = True
else:
changing_matrix = []
for i in range(0, len(matrix), k+1):
changing_matrix.append(list(numpy.concatenate(matrix[i:i+k+1])))
print(changing_matrix)
print(k)
Output:
[[1, 2, 4, 4, 6, 6], [7, 7, 8, 9, 9, 10]]
1
That's my first question, I'm new at programming, sorry about any inconvinience !
I need to finish an exercise that consists in create a fuction to find the higher number and another function to find the lower number on a List, but when I print the results, it keeps giving me a wrong answer.
Here is my code:
lista_numeros = [1593, 200, 72, 8, 423, 2, 39, 293, 20120]
def menor_numero(arg1):
colector1 = arg1[0]
print(coletor1) # - Checking value added to COLECTOR1
for a in range(len(arg1)):
print(arg1[a]) # - Checking if the A argument is running through the list.
if colector1 < arg1[a]:
colector1 = arg1[a]
return colector1
resultado2 = menor_numero(lista_numeros)
print("menor ", str(resultado2)) # Result is the last position of the list, must be the 6th position.
Thank you very much.
Fist of all indentation is very important in python to tell it the order to execute your code and also to define where code sits within a loop etc.
Now you say you want to make a function that finds the smallest and largest number from the output of another function, for this I will assume this output is a list.
Please see code below with comments.
Mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] #assume this is output from other funtion
def func(alist): #define function
collector1 = 100 #keeping your collector idea
for i in alist: #iterate through input
if i < collector1: #check if the item you are currently looking at is smaller than the item currently stored in collector
collector1 = i #if is smaller overwitre colletor with new item
print(collector1) #after iterating through all items in input print final value of colletor
func(Mylist) #call function with input
This outputs,
1
Simply change this,
if i > collector1:
And it will now find the largest in input, so output is now.
9
Edit: if you are looking for the smallest number start collector1 at a large number, if you are looking for the largest start collector1 at = 1.
assuming your input is a list and not a string or some sort you can just use the min()/max() methods:
myList = [1,2,3,4,5]
print(max(myList)) >> 5
print(min(myList)) >> 1
you can find more info here :
https://www.tutorialspoint.com/python3/list_max.htm
https://www.tutorialspoint.com/python3/list_min.htm
Your function is finding the maximum instead of the minimum value. Changing the < to > should do what you want.
Python also has builtin methods min() and max() which should do what you want.
#! python3
import random
numbers = []
max = 1000
min = 0
for i in range(40):
numbers.append(random.randint(min,max))
maxNum = min
minNum = max
for num in numbers:
if num > maxNum:
maxNum = num
elif num < minNum:
minNum = num
print(maxNum, minNum)
This is my code, I use the random library in python to generate a random list of numbers, then I set max to equal the maximum number in that list.
The following for loop generates 40 random numbers and appends them to my list.
I then set maxNum to equal zero, so everything will be greater than it, thereby the initial value will not influence the outcome, and then I set minNum to equal max, so every number will be less than it.
The last block of code loops through the numbers list, and compares every number with the current maxNum and minNum variables to see whether that number is greater than the max or less than the min. If it is, the maxNum (or minNum) number will be updated and the code will move on to the next number.
The last statement prints or minimum and maximum values.
I don't know what course you are taking, but I would advise you to familiarize yourself with this code and understand what it is doing, as it's pretty basic and the stuff you encounter in the future will be much harder.
I am making a function which will make a list which includes a histogram of a requested list and requested values to use as the values of the histogram. Values above the requested value are included last.
The program is working with a list that is sorted in ascending order numerically, but when a list that is not sorted is used as input, the program seems to discard random values and not evaluate in the same way.
the code:
def histogram(sample, binBoundaries):
c=0
if not binBoundaries:
li = [len(sample)]
return print(li)
for x in sample:
if x > binBoundaries[-1]: #if the value is greater than last bin
c = c+1 #number of values greater increases
for eachbin in binBoundaries: #for each bin
dic[eachbin] = 0 #initial value = 0 to account for no number
for x in sample: #for each value wanted to calculate for
if x <= eachbin: #if the number falls into the bin
dic[eachbin] += 1 #the number of values in the bin increases
sample.remove(x)
for i in dic:
listofvalues.append(dic[i])
listofvalues.append(c)
print(listofvalues)
histogram([5, 4, 2, 3], [3])
this will result in an output of [1, 2], where the real output should be [2,2]
Is there something I'm just not seeing that is making the number not be calculated? Let me know where I have gone wrong if you could!
Your problem is that you are removing items from the list sample while you are iterating over it, this is a bad idea because it will result in skipping some elements.
Try taking out the line sample.remove(x), you should get the expected result. If you really do need to remove elements from the input list you should refactor to make sure you still check every element in the list. One option is to iterate over the list in reverse using for x in reversed(sample).
It also looks like you may be removing elements in the wrong place, sample.remove(x) looks like it should be inside of the if directly above it. Try the following code:
...
for eachbin in binBoundaries: #for each bin
dic[eachbin] = 0 #initial value = 0 to account for no number
for x in reversed(sample): #for each value wanted to calculate for
if x <= eachbin: #if the number falls into the bin
dic[eachbin] += 1 #the number of values in the bin increases
sample.remove(x)
...