How to print content of an enumerated list? - python

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])

Related

How to get multiples of 100 rounded to the nearest thousand

I'm learning Python and I'm trying to come up with a for loop (or any other method) that can return multiples of 100 but rounded to the nearest thousand, here's what I have right now:
huneds = [h * 100 for h in range(1,50)]
for r in huneds:
if r % 3 == float:
print(r)
else:
break
The built-in round() function will accept a negative number that you can use to round to thousands:
for r in huneds:
print(round(r, -3))
Which prints:
0
0
0
0
0
1000
1000
1000
1000
1000
1000
1000
1000
1000
2000
...
4000
4000
5000
5000
5000
5000
You can see use
for n in range(0,2500,100):
print(n, ' -> ',1000 * round(n / 1000))
For any number m, m is a multiple of n if the remainder of n / m is 0. I.e. n % m == 0 or in your case; r % 100 == 0, as the modulus operator (%) returns the remainder of a division. Use:
for r in huneds:
if r % 100 == 0:
print(r)
But every number is already a multiple of 100, as you multiplied all of them by 100.
You may be after something like:
# Range uses (start, stop, step) params
# print(list(range(0, 200, 10))) --> [0, 10, 20, ... 170, 180, 190]
for r in range(0, 200, 10):
if r % 100 == 0 and r != 0:
print(r)
Outputs
100
But you would like to round to the nearest 1000. The round() function can do that.
for r in range(0, 2000, 10):
if r % 100 == 0 and r != 0:
print(f"{r} | {round(r, -3)}")
100 | 0
200 | 0
300 | 0
400 | 0
500 | 0
600 | 1000
700 | 1000
800 | 1000
...
The f string does the same as r + ' | ' + round(r, -3)
This shows the number that is a multiple of 100 which is r, and then it rounded to the nearest 1000
round()'s second argument is the amount of digits to round too, as we are going to the nearest 1000, we use -3 as you are going on the left side of the decimal
I suggest having a read of:
https://www.w3schools.com/python/ref_func_range.asp
And I highly reccomend: this site (python principles) for learning python. Pro membership is currently free
Simply do this,
list(map(lambda x: round(x/1000) * 1000, huneds))
It'll return you a list of rounded values for all the items of the list huneds.

How to quickly sum elements in a given range in array?

I have trouble solving this problem:
First line of input - N. N+1 is number of train stations.
Second line of input - N integers c(i) - price of a ticket between stations i-1 and i.
Third line of input - k - number of passengers.
Next k lines: int a and int b (first and last station for each passenger).
Desired output: price of ticket for each client. I.E.
Input:
4
12 23 34 45
3
0 4
1 3
3 2
Output:
114
57
34
My code:
n = int(input())
prices = list(map(int, input().split()))
x = int(input())
for i in range(x):
a, b = sorted(map(int, input().split()))
print(sum(prices[a:b]))
I guess my solution is far from optimal as I get Time Limit Exceeded error.
Solution using accumulated array
def accum(a):
" creates the accumulation of array a as input "
b = [0] * (len(a) + 1)
for i, v in enumerate(a):
b[i+1] = b[i] + v
return b
def price(acc, t):
" Price using accumulated array "
# t provides the start, stop points (e.g. [0, 4])
mini, maxi = min(t), max(t)
return acc[maxi] - acc[mini]
Usage of above functions
prices = [12, 23, 34, 45]
# create assumulation of prices
acc = accum(prices)
# Using your test cases
tests = [[0, 4], [1, 3], [3, 2]]
for t in tests:
print(t, price(acc, t))
Output
[0, 4] 114
[1, 3] 57
[3, 2] 34

Combinations of Combinations

There are nearly 14 million combinations from a selection of 6 numbers from a range of 1-49. From the 14 million, I've cut the combinations down to 8.9 million by selecting only those where the sum of the 6 number combination must equate to between 120 and 180.
Example: 5, 10, 20, 27, 29, 40 = 131
Of the remaining 8.9 million combinations, I'm trying to remove all combinations that contain less than 2 and more than 4 odd numbers.
Basically, I want Python to show me how many combinations of those 8.9 million combinations have between 2-4 odd numbers in their combinations. All combinations of only 1 or less odd numbers and 5 or more odd numbers would be excluded from the results.
Example: 5, 10, 20, 27, 32, 40 = 2 odd numbers (it would be included in the amount of combinations).
Thank you!
import functools
_MIN_SUM = 120
_MAX_SUM = 180
_MIN_NUM = 1
_MAX_NUM = 49
_NUM_CHOICES = 6
#functools.lru_cache(maxsize=None)
def f(n, l, s):
assert(all(isinstance(v, int) and v >= 0 for v in (n, l, s)))
return 0 if s > _MAX_SUM else (
int(s >= _MIN_SUM) if n == 0 else (
sum(f(n-1, i+1, s+i) for i in range(l, _MAX_NUM+1))
)
)
result = f(_NUM_CHOICES, _MIN_NUM, 0)
print('Number of choices = {}'.format(result))
You can use the combinations() function from itertools and just brutally count the combinations that are eligible:
from itertools import combinations
eligible = 0
for combo in combinations(range(1,50),6):
total = sum(combo)
if total < 120 or total > 180:
continue
odds = sum(n&1 for n in combo)
if odds < 2 or odds > 4:
continue
eligible += 1
print(eligible) # 7221936
It only takes a few seconds (10-12)
You can do almost exactly the same as you are currently doing. Just add a parameter that counts how many odd numbers there are and increase it when you add an odd. Then you can adjust your tests accordingly:
import functools
_MIN_SUM = 120
_MAX_SUM = 180
_MIN_NUM = 1
_MAX_NUM = 49
_NUM_CHOICES = 6
_MIN_ODDS = 2
_MAX_ODDS = 4
#functools.lru_cache(maxsize=None)
def f(n, l, s = 0, odds = 0):
if s > _MAX_SUM or odds > _MAX_ODDS:
return 0
if n == 0 :
return int(s >= _MIN_SUM and odds >= _MIN_ODDS)
return sum(f(n-1, i+1, s+i, odds + i % 2) for i in range(l, _MAX_NUM+1))
result = f(_NUM_CHOICES, _MIN_NUM)
print('Number of choices = {}'.format(result))
Because it's memoized and prunes branches, this runs quickly:
150 ns ± 13 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Running it with the more managable:
_MIN_SUM = 1
_MAX_SUM = 8
_MIN_NUM = 1
_MAX_NUM = 8
_NUM_CHOICES = 2
_MIN_ODDS = 2
_MAX_ODDS = 4
returns 4 which corresponds to the set:
(1, 3),
(1, 5),
(1, 7),
(3, 5)

get value from data that depend on other data

i am trying to get the l input which will be between 0,1. the l input will be for A column. and second input will be the 'mesafe' column so the result must be 23 which is for A and mesafe's zero column. I get some error.
import pandas as pd
import numpy as np
def var():
df = pd.read_csv('l_y.txt')
l=float(input("speed of the wind:"))
w=int(input("range:"))
for l in range(0, 1) and w in range(0, 100) :
print(df['A'].values[0])
l_y.txt=( mesafe A B C D E F
0 100 23 18 14 8 4 0
1 1000 210 170 110 60 40 30
2 5000 820 510 380 300 230 160
3 10000 1600 1200 820 560 400 250
4 20000 2800 2100 1600 1000 820 500
5 50000 5900 4600 3400 3200 1600 1100
6 100000 10000 8100 6100 3900 2800 2000 )
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
var()
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\ml.py", line
8, in var
for l in range(0, 1) and w in range(0, 100) :
TypeError: 'bool' object is not iterable
You have to follow the format of the language. In this case if you want to run a double loop with l and w:
for l in range(0, 1):
for w in range(0, 100) :
print(df['A'].values[0])
Note the indent, if you don't indent properly then the python codes won't work correctly.
Also your code here doesn't seem to accomplish anything except printing the same thing for 200 times. What are you trying to do?
Ok, I assume you want to get a certain value from your matrix, depending on two input values l and w, so that if l is between 0 and 1 column 'A' should be selected. (I further assume, that if l is between 1 nd 2 it's column 'B', 2 <= l < 3 -> 'c', and so on...)
The row is directly derived from w with the data in the mesafe-column: if w is between 0 and 100 -> row 0, between 100 and 1000 -> row 1 and so on...
Well, this can be achieved as follows:
l = .3 # let's say user types 0.3
There is some mapping between l and the letters:
l_mapping = [1, 5, 12, 20, 35, 50] # These are the thresholds between the columns A...F
l_index = np.searchsorted(l_mapping, l) # calculate the index of the column letter
col = df.columns[1:][l_index] # this translates l to the column names from A...F
col # look what col is when l was < 1
Out: 'A'
w = 42 # now the user Input for w is 42
row = np.searchsorted(df.mesafe.values, w) # this calculates the fractional index of w in df.mesafe
row
Out: 0
So with these two formulas you get column and row Information to index your desired result:
df[col].iloc[row]
Out: 23
Summing this all up in a function would look like this:
def get_l_y(l, w, df_ly):
l_mapping = [1, 5, 12, 20, 35, 50]
l_index = np.searchsorted(l_mapping, l)
col = df_ly.columns[1:][l_index]
row = np.searchsorted(df.mesafe.values, w)
print(l, w, col, row) # print Input and calculated row- and column- values for testing purpose, can be deleted/commented out if everything works as you want
return df[col].iloc[row]
This function expects l, w and the pandas-dataframe of your matrix as input Parameters and returns l_y.

Finding the max value in a python loop

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):

Categories

Resources