I have this piece of python code below.
def m(list):
v = list[0]
for e in list:
if v < e: v = e
return v
values = [[3, 4, 5, 1], [33, 6, 1, 2]]
for row in values:
print(m(row), end = " ")
The result is 5, 33.
Can somebody explain me that following if statement if v < e: v = e?
if v < e: v = e
can be read: "If v is less than e, make v the value of e."
As above you should put a new line to make it read easier:
if v < e:
v = e
In [8]: v = 1
In [9]: e = 2
In [10]: if v < e: v = e
In [11]: v
Out[11]: 2
In [12]: e
Out[12]: 2
is same as:
In [13]: v = 1
In [14]: e = 2
In [15]: if v < e: # if True execute next statement
....: v = e
....:
In [16]: v
Out[16]: 2
In [17]: e
Out[17]: 2
It's called a colon in english, not a double colon or double comma.
I urge you to read a basic Python introduction.
if v < e: v = e
Is the same as:
if v < e:
v = e
Another way to write that code is like this, just for learning purposes:
def max_nest_list(lst):
max_numbers = []
for sub_list in lst:
max_num = sub_list[0]
for num in sub_list[1:]:
if num > max_num:
max_num = num
max_numbers.append(max_num)
return max_numbers
values = [[3, 4, 5, 1], [33, 6, 1, 2]]
for item in max_nest_list(values):
print(item, end = " ")
#Output
5 33
Or even more concise:
def max_nest_list2(lst):
return [max(i) for i in lst]
values = [[3, 4, 5, 1], [33, 6, 1, 2]]
for item in max_nest_list(values):
print(item, end = " ")
Related
I have a series of data and would like to perform the following opperation:
AA = [2, 4, 6, 8]
a = []
a = AA[0]
b = AA[1]
sum_1 = a+b
c = AA[2]
sum_2 = sum_1 + c
d = AA[3]
sum_3 = sum_2 + d
To make it more concise, I'd like to put it in a for loop, but I can't figure out how.
The desired output for me will be the updated sum_3
That will do it for you:
AA = [2, 4, 6, 8]
s = 0
for a in AA:
s += a
print(s)
20
Cheers
input_dict = {'ab':12, 'cd':4, 'ef':1, 'gh':8, 'kl':9}
out_dict = 2
Is there any way to find the length of keys of the dictionary, if the values in dictionary are greater than 2 and less than 9?
Try this,
In [61]: len([v for v in d.values() if 2 < v < 9])
Out[61]: 2
I think you want to find number of items in dictionary where value is 2 < v < 9:
input_dict = {"ab": 12, "cd": 4, "ef": 1, "gh": 8, "kl": 9}
out = sum(2 < v < 9 for v in input_dict.values())
print(out)
Prints:
2
Just returning the relevant lengths:
[len(k) for k, v in input_dict.items() if 2 < v < 9]
Returns:
[2, 2]
For a list of integers, such as A = [2, 10, -5], I get the error
Traceback (most recent call last):
File "so.py", line 6, in <module>
v, A[v-1] = A[v-1], v
IndexError: list assignment index out of range
Code:
for i, v in enumerate(A):
while 1<=v<=len(A) and v != A[v-1]:
v, A[v-1] = A[v-1], v
but this works:
for i, v in enumerate(A):
while 1<=v<=len(A) and v != A[v-1]:
A[v-1], v = v, A[v-1]
Why the order of the swapping elements matters here? v is always being checked to be in bound.
Weirdly enough cannot reproduce a smaller example. But,
A = [6, 5, 4, 3, 2]
becomes an infinite loop.
Python swaps the variables in the order provided, so v is assigned the value at A[v-1], and then tries to reassign A[v-1] - but since v has been modified to be a list element, v-1 is out of range of A.
I reproduced this with [2, 10, -5].
The detailed sequence of operations is
i, v = 0, 2
1 <= 2 ? OK
2 != A[1] ? OK ... stay in loop
v, A[v-1] = 10, 2
# This assignment breaks into ...
v = 10
A[10-1] = 2
# ... and this second assignment is out of range.
If you switch the assignment order:
A[v-1], v = 2, 10
# This assignment breaks into ...
A[2-1] = 2
v = 10
In this case, your while conditions have properly guarded a legal assignment.
Note that you are not swapping list values; v is a local variable; it is not a reference to A[i]. For instance, in the above example, you do get v=10, but this does not affect the value of A[0].
A = [6, 5, 4, 3, 2]
for i, v in enumerate(A):
while 1<=v<=len(A) and v != A[v-1]:
v, A[v-1] = A[v-1], v
You need to try running out your algorithm in your head:
Start:
i = 0, v = 6
v(6) is not between 1 and 5: next iteration
i = 1, v = 5, A[5-1] = 2
5 is between 1 and 5; v is not equal to 2: swap ->
v = 2; A[4] = 2
i = 1, v = 2, A[2-1] = 5
2 is between 1 and 5; v is not equal to 5: swap ->
v = 5; A[1] = 5
i = 1, v = 5, A[5-1] = 2
5 is between 1 and 5; v is not equal to 2: swap ->
v = 2; A[4] = 2
i = 1, v = 2, A[2-1] = 5
2 is between 1 and 5; v is not equal to 5: swap ->
v = 5; A[1] = 5
... and on and on
I don't think your algorithm makes sense. It's unclear why you are using the values in your list to index the list during your loop. I think this confusion about the index and values is at the root of your problem.
Can I ask how to achieve this in Python:
Input:
I = [10,-22,0]
Output:
O = [1,-1,-1]
I was thinking
O=I/abs(I)
But how to deal with zero?
The following should do what you want:
>>> I = [10,-22,0]
>>> O = [1 if v > 0 else -1 for v in I]
>>> O
[1, -1, -1]
>>>
If you want to use map with a lambda, you can do:
>>> O = map(lambda v: 1 if v > 0 else -1, I)
>>> O
[1, -1, -1]
>>>
You can just do this:
I = [10,-22,0]
output = []
for num in I:
if num <=0:
output.append(-1)
else:
output.append(1)
print output
I have written the following code:
def count():
a = 1
b = 5
c = 2
d = 8
i = 0
list1 = [a, b, c, d]
le = len(list1)
while (i < le):
x = max(list1)
print(x)
list1.remove(x)
i = i + 1
What I want to do is to print the largest number with its variable name like:
d:8
b:5
c:2
but using the above code I can only print the ascending list of numbers, not the corresponding variable names. Please suggest a way to fix this.
Use a dict instead:
In [2]: dic=dict(a=1, b=5, c=2, d=8)
In [3]: dic
Out[3]: {'a': 1, 'b': 5, 'c': 2, 'd': 8}
In [5]: sortedKeys=sorted(dic, key=dic.get, reverse=True)
In [6]: sortedKeys
Out[6]: ['d', 'b', 'c', 'a']
In [7]: for i in sortedKeys:
...: print i, dic[i]
...:
d 8
b 5
c 2
a 1
I think you can use OrderedDict()
from collections import OrderedDict
a, b, c, d = 1, 2, 3, 6
vars = {
'a' : a,
'b' : b,
'c' : c,
'd' : d
}
d_sorted_by_value = OrderedDict(sorted(vars.items(), key=x.get, reverse=True))
for k, v in d_sorted_by_value.items():
print "{}: {}".format(k,v)
List don't save variable names