Finding the max value in a python loop - python

I have a list of data that I'm trying to find the max value from with python. My current code will loop over the data and render all possible combinations of the data, however I can't figure out how to render the max from the results.
Below is my current setup:
street = %sql SELECT * FROM streets
for i in range(len(flight)):
for j in range(len(flight)):
for k in range(len(flight)):
A = flight[i][2]
B = flight[k][2]
num = flight[i][4] , flight[j][4] , flight[k][4]
numsum = sum(num)
print A, B, numsum
Printing flight will render the below
+----+-----------+----------------------+----------------------+---+
| id | flight | Start | End |dis|
+----+-----------+----------------------+----------------------+---+
| 0 | w | SFO | DEN | 4 |
| 1 | e | DEN | NYC | 7 |
| 1 | e | DEN | ORD | 7 |
However the max with throw the below error.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-283-770cd29ebd83> in <module>()
8 num = street[i][4] , street[j][4] , street[k][4]
9 numsum = sum(num)
---> 10 print A, B, max(numsum)
11
TypeError: 'int' object is not iterable
If I remove the max from the last line everything in the database will print. For example:
SFO ORD 35
DEN JFK 12
SFO JFK 94
LAX DEN 54
...
Can someone help me figure out how to get the max value in numsum so the result prints like this:
SFO JFK 94
Thanks in advance!

You're not doing what you're trying to do. Your algorithm isn't well thought-out. look at it this way:
for each_item in whatever_iterator:
a = each_item[some_element]
b = each_item[another_element]
num = some, other, numbers
sumnum = sum(num) # hey that was easy!
print a, b, sumnum # every time through, let's print it!
Nowhere does this find the LARGEST. In order to do that, you'd want to iterate through and save current_max = max(current_max, new_value)
Looks like what you're looking to do is:
max_sumnum = (0, 0, 0)
for i, j, k in itertools.product(len(x), repeat=3):
num = x[i][4], x[j][4], x[???][1][k][4]
cur_sumnum = x[i][2], x[k][2], sum(num)
max_sumnum = max(max_numsum, cur_sumnum, key=lambda tup: tup[2])
print max_sumnum
I use itertools.product here because it's a great shortcut for nested for loops.
for i in range(3):
for j in range(5):
for k in range(100):
for m in range(2):
foo(i, j, k, m)
# equivalent to....
for i, j, k, m in itertools.product(range(3), range(5),
range(100), range(2)):
And I use the repeat keyword since you're doing a bunch of the same loops.
for i in range(3):
for j in range(3):
for k in range(3):
# equivalent to....
for i, j, k in itertools.product(range(3), repeat=3):

Related

python pandas with parameter length changing

I want to do
df[(df['col']==50) | (df['col']==150) | etc ..]
"etc" is size changing from 1 to many
so I do a loop
result is like
str= "(df['col']==50) | (df['col']==150) | (df['col']==100)"
then I do this
df[str]
but this does not work
How can I make it work ?
A simple solution:
list_of_numbers = [50,150]
df[df["col"].isin(list_of_numbers)]
Where list_of_numbers are the numbers you want to include in the condition. I'm assuming here your condition is always or.
Use query to filter a dataframe from a string
df = pd.DataFrame({'col': range(25, 225, 25)})
l = [50, 100, 150]
q = ' | '.join([f"col == {i}" for i in l])
out = df.query(f)
>>> q
'col == 50 | col == 100 | col == 150'
>>> out
col
1 50
3 100
5 150

How to print content of an enumerated list?

I have created an enumerated list rank from a list total. But I am not able to print any specific value from the list rank.
I have tried to print the specific value from the rank list by traversing it using a for loop but getting the error
print(rank[i][0])
IndexError: list index out of range
n=int(input())
total=[]
rank=sorted(list(enumerate(total)), key=lambda x:x[1])
for i in range(n):
e,g,m,h=map(int, input().split())
total.append([-(e + g + m + h)])
#print(total)
#print(rank)
for i in range(n):
print(rank[i][0])
Input:
5
100 98 100 100
100 100 100 100
100 100 99 99
90 99 90 100
100 98 60 99
Expected Output:
(-398,0) if is rank[0][0] or so on.
You need to move rank creation after you fill total then it works fine.
n = int(input())
total = []
for i in range(n):
e, g, m, h = map(int, input().split())
total.append([-(e + g + m + h)])
rank = sorted(list(enumerate(total)), key=lambda x: x[1])
for i in range(n):
print(rank[i][0])
# print rank
for i in total:
print(i[0])

Adding None Value Always gives 0

I want to create a function that adds the numbers in the columns in a matrix and output a vector made of the sum. However if there is a "None" value in the matrix, the output vector gets a "None" value for that column automatically. I cannot figure out how to do the part for the "None" value.
I tried the following code.
def sum_matrix (matrix):
#
# | 1 2 3 |
# | 1 2 3 |
# | 1 2 3 | -> |4 8 12|
# | 1 2 3 |
# _________
# 4 8 12
vektor = [[0] for i in range(0,len(matrix[0]))]
for j in range(0, len(matrix[0])): #rows 0-3 4
buffer = 0
for i in range(0, len(matrix)): #columns 3
if matrix[i][j] !=None:
buffer = buffer + matrix[i][j]
#vektor[j][0] = buffer
elif matrix[i][j] ==None:
vektor[j][0] = None
vektor[j][0] = buffer
return vektor
print (sum_matrix ([[0,0,0],[0,0,1],[0,1,0],[0,0,0]]))
print (sum_matrix ([[0,0,0],[0,None,1],[0,1,None],[0,0,0]]))
For sum_matrix ([[0,0,0],[0,0,1],[0,1,0],[0,0,0]]), I get [[0],[1],[1]] which is good.
For sum_matrix ([[0,0,0],[0,None,1],[0,1,None],[0,0,0]]), I still get [[0],[1],[1]] even though I am supposed to get [[0],[None],[None]]
As I always say, you should differentiate a matrix (a mathematical abstraction) from its implementation (a list of lists).
Now, what we have here is basically a list of lists where each inner list represents a row, but we want to take the sum of each column, with the additional constraint that it should be None whenever it contains at least one None value.
The simplest way to do this, I would say, is using a list comprehension in conjunction with zip, which effectively transposes your matrix:
def sum_matrix(m):
transposed = zip(*m)
summed = [[sum(col) if None not in col else None]
for col in transposed]
return summed
print(sum_matrix([[0,0,0],[0,0,1],[0,1,0],[0,0,0]]))
print(sum_matrix([[0,0,0],[0,None,1],[0,1,None],[0,0,0]]))
Output:
[[0], [1], [1]]
[[0], [None], [None]]
Note: you can also couch the inner list comprehension as [None if None in col else sum(col)], but I prefer to put the "normal" case first.
You could also convert col to a set, which allows constant time lookups, but actual conversion to a set is linear time, and since we're only iterating over each column once, I don't think it'll be faster.
when matrix[i][j]==None you need to store in the buffer None, since you're changing the value of vektor when exiting the inner loop, so the vektor will always take the value of the buffer
def sum_matrix (matrix):
#
# | 1 2 3 |
# | 1 2 3 |
# | 1 2 3 | -> |4 8 12|
# | 1 2 3 |
# _________
# 4 8 12
vektor = [[0] for i in range(0,len(matrix[0]))]
for j in range(0, len(matrix[0])): #rows 0-3 4
buffer = 0
for i in range(0, len(matrix)): #columns 3
if matrix[i][j] !=None:
buffer = buffer + matrix[i][j]
#vektor[j][0] = buffer
elif matrix[i][j] ==None:
buffer = None
break
vektor[j][0] = buffer
return vektor

Python - Place a character in between a formatted string

Lets say I want to print out
Item 1 | Item 2
A Third item | #4
Which can be done without the | by doing
print('%s20 %20s' % (value1,value2))
How would I go about placing the | character so that it is evenly justified between the two formatted values?
I suppose I could manually could the length of the formatted string without the | character and then insert the | in the middle but I am hoping for a more elegant solution!
Thank you very much for your time.
Edit: Here is a solution that I suggested would be possible
def PrintDoubleColumn(value1, value2):
initial = '%s20 %20s' % (value1,value2)
lenOfInitial = len(initial)
print(initial[:lenOfInitial/2] +'|' + initial[lenOfInitial/2+1:])
There is a good source for string format operations: https://pyformat.info/#string_pad_align
x = [1, 2, 3, 4, 5]
y = ['a', 'b', 'c', 'd', 'e']
for i in range(0, 5):
print "{0:<20}|{1:>20}".format(x[i], y[i])
Result:
1 | a
2 | b
3 | c
4 | d
5 | e

How to create a table without using methods or for-loops?

I'm trying to create a 4x3 table without methods or for-loops.
I'd like to use what I learned in class, which is booleans, if-statements, and while-loops.
I want it so that if I input create_table('abcdefghijkl') it would start from the the left top most row and column and go down until the end of the column and then start again at the top of the next column and so on, like displayed below:
| a | e | i |
| b | f | j |
| c | g | k |
| d | h | l |
Below is what I have so far. It's not complete. How do I add to the function so that after 4 rows down, the string should continue to the next column starting from the top?
I'm wracking my brain over this.
All examples I can find online uses for loops and methods to create tables such as these, but I'd like to implement the while loop for this one.
Thanks in advance!
def create_table(table):
t = "" + "|" + ""
i = 0
while i < 12:
t = t + " " + "|" + table[i] + " "
i=i+1
print(t)
return table
Think about it in terms of rows instead of columns. You're writing out a row at a time, not a column at a time, so look at the indices of the individual cells in the original list:
| 0 | 4 | 8 |
| 1 | 5 | 9 |
| 2 | 6 | 10 |
| 3 | 7 | 11 |
Notice each row's cells' indices differ by 4. Find a simple expression for the nth row's cells and the task will become much easier, as you'll essentially be printing out a regular table.
You can translate most for loops to while loops with a simple recipe, so if you figure out how to do it with a for loop, then you are good to go. If you have
for x in s:
{statements}
Make it
i = 0
while i < len(s):
x = s[i]
{statements}
i += 1
It just won't work for some enumerable types that don't support length and indexing, such as generators.
Because you are printing to the terminal, you would want to think about printing each horizontal row, rather than each vertical column. Try something like:
table = 'abcdefghijkl'
i = 0
while i < 4:
print("| {} | {} | {} |".format(table[i], table[i+4], table[i+8]))
i += 1

Categories

Resources