How to Append The Calculated Arithmetic to The List? - python

Let say we have this simple arithmetic:
y = 1 + 1
Can I append the result of the arithmetic to a list directly like so:
num_list = []
l = num_list.append(y)
I have tried to print the list to see if the result has been appended to the list, but I noticed it gives me "None" as output. Any idea how to approach this?

you should not print l, you should print num_list to see the appended list. Here is the sample test in python command line
>>> y = 1 + 1
>>> list1 = []
>>> list1.append(y)
>>> print list1
[2]
>>> print l
None
>>>

Related

Can't get value from the circular python's list

I have an empty list, then I'm creating a circular link and trying to get this list by index, but getting IndexError. Why this happening? Should it be possible for me to get this list forever? How can I get value from this list?
>>> a = []
>>> a = [a]
>>> len(a[0])
0
>>> a[0][0]
IndexError: list index out of range
Your list isn't circular, it's just an empty list within a list.
>>> a = []
>>> a = [a]
>>> a
[[]]
>>> len(a)
1
>>> a[0]
[]
>>> len(a[0])
0
You seem to have a misconception about how assignments work. a = [a] evaluates the right hand side first, which is [[]] and then the name a is rebound to that value.
You can get a circular list via
>>> a = []
>>> a.append(a)
>>> a
[[...]]
Of course it has length one, because there's only one thing in a: a.
>>> len(a)
1
It's happening because the initial a is empty. After the 2nd line of your code, you have:
a=[[]]. As such, a[0] = [], i.e an empty list. And a[0][0] is trying to access an element in an empty list which is why you see the error.

How to multiply two sublists within the same list?

I am new to python and SO. I want to multiply each element of lists in a list of lists to another list lying in the same list of lists and compare it with a reference value. This will be more clear with an example:
for L = [[1,2,3,4,5,10],[3,2,4,1,5,10]] ##there can be more than 2 lists in this list of lists
I want only those pairs whose product results in 10.
Out: L = [[1,10],[2,5]]
Edit: I prefer a method without any imports, since I am doing this for building logic and my editor doesn't contain any modules to import. Also, if there are more than 2 lists in a list of lists For eg. there are 3 Lists in a list of lists: then I want triplets for that sake. ANd if 4 lists then I need quadruples.
Here's my code attempt as requested.
N = []
J = []
F = []
Z = []
S = []
O = []
num = input("Enter no. of elements in list")
print ('Enter numbers')
prod = 1
for i in range(int(num)):
n = input("num :")
N.append(int(n))
for x in N:
prod = prod*x
print (prod)
k = int(input("Enter no. of splits:"))
##d = [[] for x in xrange(k)]
##var_dict = []
for o in range(1,prod+1):
if prod%o == 0:
J.append(o)
print (J)
for g in range(k):
O.append(J*(k-1))
print (O)
for a in range(len(O)):
for b in range(len(O)):
if O[i]*O[i+1] == prod:
Z.extend(O)
##Z = [[a, b] for a in J for b in F if a*b == prod] ##imp
print (Z)
for e in Z:
if e not in S and sorted(e) not in S:
S.append(e)
print (S)
You can use itertools.product to find groups of numbers and filter them based on their product
>>> from itertools import product
>>> from functools import reduce
>>> lst = [[1,2,3,4,5,10],[3,2,4,1,5,10]]
>>> ans = [p for p in product(*lst) if reduce(lambda x,y:x*y, p) == 10]
>>> # Remove duplicates
>>> ans = list(map(list, set(map(frozenset, ans))))
>>> print (ans)
[[1, 10], [2, 5]]
>>>
In a comment you say you say you want code without any imports. Importing product from itertools and reduce do simplify and speed the code, but the job can be done without imports. Here is a recursive solution. I am not quite satisfied with this code but it seems to work and passes all my tests. I generalized the problem somewhat so that the input can have tuples or other sequences and not just lists.
def prod_is_target(seq_of_seqs, target):
"""Return a list of lists, where each sublist contains one member
of each input subsequence in order, and the product of those
members equals the target value. If there is no such list possible,
return None. If seq_of_seqs is empty, return an empty list if the
target is 1 and return None otherwise.
"""
if not seq_of_seqs: # if is empty sequence
return [] if target == 1 else None
result = []
for val in seq_of_seqs[0]:
if target % val: # skip if target is not a multiple of val
continue
prodlists = prod_is_target(seq_of_seqs[1:], target // val)
if prodlists is None: # skip if failed with later sublists
continue
if not prodlists: # if is empty list
result.append([val])
else:
for prodlist in prodlists:
result.append([val] + prodlist)
return result if result else None
print(prod_is_target([[1,2,3,4,5,10], [3,2,4,1,5,10]], 10))
The printout from that code is
[[1, 10], [2, 5], [5, 2], [10, 1]]
I'll leave it to you to remove what you consider to be duplicates. I can think of situations where you would want this full list, however.

Edit List of Numbers n to contain only from 0 to n

The title isn't very good mainly because its become quite difficult for me to describe the problem in a very concise manner. If someone can improve the title after reading below then please do so.
The problem is this. The input is an array of numbers like this : [1,3,4,7] and output is to be an array something like this : [1,2,3,4]. This is to indicate what rank each number is in the input array based on its value.
Some other examples :
In[1] : [4,3,7,9]
Out[1] : [2,1,3,4]
In[2] : [0,4,1,9]
Out[2] : [0,2,1,3]
In[3] : [1,0,0,0]
Out[3] : [1,0,0,0]
A peculiarity to notice here is that when an array contains zero it must start ranking from zero whereas for In[1] since it doesn't contain zero, the array starts ranking from 1.
Currently, I am using this code :
def argsort(seq):
ix = list(range(len(seq)))
ix.sort(key=lambda x: seq[x])
out = [0] * len(i)
for i, x in enumerate(ix):
if seq[x] != 0:
out[x] = i
if 0 in seq:
return out
else:
return [each+1 for each in out]
Currently, the solution works for the first two cases. However, it fails on case 3 and returns this as the result : [3,0,0,0]
Looks like you've a python list not numpy array (as you've tagged), so you can simply do it like this:
inList = [4,3,7,9]
sortedinList = sorted(set(inList))
outList = [sortedinList.index(e)+ (0 not in inList) for e in inList]
Since you want the same index for the duplicates, so you can use set instead of a list to get the index.
OUTPUT
>>> inList = [4,3,7,9]
>>> outList
[2,1,3,4]
>>> inList = [0,4,1,9]
>>> outList
[0,2,1,3]
>>> inList = [1,0,0,0]
>>> outList
[1,0,0,0]
def argsort(seq):
sorted_seq = sorted(seq)
res = []
for _ in sorted_seq:
my_index = seq.index(_)
res.append(my_index)
seq[my_index] = '$'
return res
if __name__ == "__main__":
my_list = [4,3,7,9]
print argsort(seq=my_list)
output:
[1, 0, 2, 3]
Here is another alternative solution, I hope this resolves your question.

Check if there's an item inside a list and if True modify it

list1 = [1,2,3]
def ex(example_list):
for number in example_list:
if(number == 2):
number = 3
ex(list1)
print(list1)
I need to check if there is the number 2 inside of the list1 and if it's inside of it, I want to modify it to 3.
But if I run the command, number would be 3, but list1 would remain [1,2,3] and not [1,3,3]
You can use enumerate() to get the index of the number you need to change:
list1 = [1,2,3]
def ex(example_list):
for idx, number in enumerate(example_list):
if(number == 2):
example_list[idx] = 3
ex(list1)
print(list1)
The variable number is an object with its own reference and not a reference to the item in the list.
The logic for checking and replacing can be done altogether in a list comprehension using a ternary operator since you're not actually using the index:
list2 = [3 if num==2 else num for num in list1]
References:
List comprehensions
Conditional expressions
In order to modify a list item, you need to know which slot it is in. The .index() method of lists can tell you.
list1 = [1,2,3]
i = list1.index(2)
list1[i] = 2
Now what happens if the list does not contain 2? index() will throw an exception, which normally will terminate your program. You can catch that error, however, and do nothing:
list1 = [1,2,3]
try:
i = list1.index(2)
except ValueError:
pass
else: # no error occurred
list1[i] = 2
So... The problem you're having is that, since number contains a basic type (an int), modifying number doesn't modify the reference inside the list. Basically, you need to change the item within the list by using the index of the item to change:
list1 = [1,2,3]
def ex(example_list):
for i, number in enumerate(example_list):
if(number == 2):
example_list[i] = 3 # <-- This is the important part
ex(list1)
print(list1)
Of just using the index (might be clearer):
list1 = [1,2,3]
def ex(example_list):
for i in range(len(example_list)):
if(example_list[i] == 2):
example_list[i] = 3
ex(list1)
print(list1)
l.index(n) will return the index at which n can be found in list l or throw a ValueError if it's not in there.
This is useful if you want to replace the first instance of n with something, as seen below:
>>> l = [1,2,3,4]
>>> # Don't get to try in case this fails!
>>> l[l.index(2)] = 3
>>> l
[1, 3, 3, 4]
If you need to replace all 2's with 3's, just iterate through, adding elements. If the element isn't 2, it's fine. Otherwise, make it 3.
l = [e if e != 2 else 3 for e in l]
Usage:
>>> l = [1,2,3,4]
>>> l = [e if e != 2 else 3 for e in l]
>>> l
[1, 3, 3, 4]

Python: Convert a list into a normal value

I have a list
a = [3]
print a
[3]
I want ot convert it into a normal integer
print a
3
How do I do that?
a = a[0]
print a
3
Or are you looking for sum?
>>> a=[1]
>>> sum(a)
1
>>> a=[1,2,3]
>>> sum(a)
6
The problem is not clear. If a has only one element, you can get it by:
a = a[0]
If it has more than one, then you need to specify how to get a number from more than one.
I imagine there are many ways.
If you want an int() you should cast it on each item in the list:
>>> a = [3,2,'1']
>>> while a: print int(a.pop())
1
2
3
That would also empty a and pop() off each back handle cases where they are strings.
You could also keep a untouched and just iterate over the items:
>>> a = [3,2,'1']
>>> for item in a: print int(item)
3
2
1
To unpack a list you can use '*':
>>> a = [1, 4, 'f']
>>> print(*a)
1 4 f

Categories