Suppose we have two inputs a and b where a denotes the first integer and b denotes the second integer
for example :
if
a= 1 b = 2
a=1 b=3
a=2 b=3
here 1 is connected with two integers 2 and 3 and 2 is connected with one integer 3
how I can find this and print the result like this {1:{2,3}, 2:{3}}
Note: a is basically the first integer and b is the integer connected with a
Thanks in advance. and this is not homework.
You can have a function like this:
d = {}
def connect(a,b):
if a not in d:
d[a] = [b]
else:
d[a].append(b)
connect(1,2)
connect(1,3)
connect(2,3)
print(d)
output:
{1: [2, 3], 2: [3]}
If 'a' is already in the dictionary, it will add 'b' to the list connected to it. and otherwise a new item will be added to dictionary with 'a' as key and list with 'b' in it as value.
You need a data structure that is called a map, however in Python it is also called a dictionary.
A map stores entries consisting of one key and one value each.
As you want to store potentially multiple values for each key, you can use lists of int as values for your map.
Alternatively you can also use a multi map, however it is not part of the default Python library but there are additional libraries with this functionality.
Related
This question already has answers here:
How can you print a variable name in python? [duplicate]
(8 answers)
Closed 3 months ago.
I have an array of points and I'm looking to print the name of the points instead of the actual points.
A = (2,0)
B = (3, 4)
C = (5, 6)
array1 = [A, B, C]
when I do print(array1[0]) it ends up printing the values. But I want to print the letters such as A, B or C. How would I print the letters instead?
I've also tried print(array1) and it also just prints all the values instead.
A variable doesn't usually contain its own name. This is simply something you can use to target whatever value that is being referenced.
Obviously, the best answer will be related to the really why you want to print "A". If you just want to print the letter "A", then simply do:
print("A")
Obviously, that doesn't scale well depending on the reason why you want to print the name of the variable.
Instead, why don't you use a dictionary? A dictionary is a structure that contains a list of keys that each reference a different value.
dictionary = {"A": (2, 0), "B": (3, 4), "C": (5, 6)}
You can reference each tuple by using the key instead of an index.
print(dictionary["A"])
Will return (2,0)
If you want to print the first value of "B", you simply do dictionary["A"][0].
Alright, now, for the good stuff. Let's say that you want to print all keys AND their values together, you can use the items() method like this:
for key, value in dictionary.items():
print(f"{key}={value}")
What happens if that items() will return a generator of tuples that contains both the keys and their corresponding value. In this way, you And you can use both the key and the value to do whatever you want with them.
By the way, the f in front of the string tells python that this is a formatted string and will compute anything written in between curly brackets and include them as part of the string. In this case, the code written above will output the following:
A=(2,0)
B=(3,4)
C=(5,6)
Try writing array1=["A", "B", "C"] instead of array1=[A, B, C]. A, B, and C are variables so they represent their value, if you want the letters A, B, and C you should use strings instead.
I had a question regarding list operations.
Let's say I had the following two lists:
a = [1,2,3,4,5,6]
and
b = [7,8,9]
If I was to input a as a value for one parameter within a function, and b as the second input within a function. How could I use indexing and slicing to have the elements in list b substitute (in this case) the values [4,5,6] so that the output would look like this:
Answer returned:
[1,2,3,7,8,9]
lets say x is the length of b
use slicing to remove the last x values of a.
than add b to a.
def put_in(a,b):
a = a[:len(a)-len(b)]
a = a+b
return a
I want to know if you have a list of strings such as:
l = ['ACGAAAG', 'CAGAAGC', 'ACCTGTT']
How do you convert it to:
O = 'ACGAAAG'
P = 'CAGAAGC'
Q = 'ACCTGTT'
Can you do this without knowing the number of items in a list? You have to store them as variables.
(The variables don't matter.)
Welcome to SE!
Structure Known
If you know the structure of the string, then you might simply unpack it:
O, P, Q = my_list
Structure Unknown
Unpack your list using a for loop. Do your work on each string inside the loop. For the below, I am simply printing each one:
for element in l:
print(element)
Good luck!
If you don't know the number of items beforehand, a list is the right structure to keep the items in.
You can, though, cut off fist few known items, and leave the unknown tail as a list:
a, b, *rest = ["ay", "bee", "see", "what", "remains"]
print("%r, %r, rest is %r" % (a, b, rest))
a,b,c = my_list
this will work as long as the numbers of elements in the list is equal to the numbers of variables you want to unpack, it actually work with any iterable, tuple, list, set, etc
if the list is longer you can always access the first 3 elements if that is what you want
a = my_list[0]
b = my_list[1]
c = my_list[2]
or in one line
a, b, c = my_list[0], my_list[1], my_list[2]
even better with the slice notation you can get a sub list of the right with the first 3 elements
a, b, c = my_list[:3]
those would work as long as the list is at least of size 3, or the numbers of variables you want
you can also use the extended unpack notation
a, b, c, *the_rest = my_list
the rest would be a list with everything else in the list other than the first 3 elements and again the list need to be of size 3 or more
And that pretty much cover all the ways to extract a certain numbers of items
Now depending of what you are going to do with those, you may be better with a regular loop
for item in my_list:
#do something with the current item, like printing it
print(item)
in each iteration item would take the value of one element in the list for you to do what you need to do one item at the time
if what you want is take 3 items at the time in each iteration, there are several way to do it
like for example
for i in range(3,len(my_list),3)
a,b,c = my_list[i-3:i]
print(a,b,c)
there are more fun construct like
it = [iter(my_list)]*3
for a,b,c in zip(*it):
print(a,b,c)
and other with the itertools module.
But now you said something interesting "so that every term is assigned to a variable" that is the wrong approach, you don't want an unknown number of variables running around that get messy very fast, you work with the list, if you want to do some work with each element it there are plenty of ways of doing it like list comprehension
my_new_list = [ some_fun(x) for x in my_list ]
or in the old way
my_new_list = []
for x in my_list:
my_new_list.append( some_fun(x) )
or if you need to work with more that 1 item at the time, combine that with some of the above
I do not know if your use case requires the strings to be stored in different variables. It usually is a bad idea.
But if you do need it, then you can use exec builtin which takes the string representation of a python statement and executes it.
list_of_strings = ['ACGAAAG', 'CAGAAGC', 'ACCTGTT']
Dynamically generate variable names equivalent to the column names in an excel sheet. (A,B,C....Z,AA,AB........,AAA....)
variable_names = ['A', 'B', 'C'] in this specific case
for vn, st in zip(variable_names, list_of_strings):
exec('{} = "{}"'.format(vn, st))
Test it out, print(A,B,C) will output the three strings and you can use A,B and C as variables in the rest of the program
I have three lists of dictionaries, A, B and C. They look like:
A = [{propA1: valueA1}, {propA1: valueA2}, ...]
B = [{propB1: valueB1, propB2: valueB2}, {propB1: valueB3, propB2: value4}, ...]
C = [{propC1: valueC1}, {propC1: valueC2}, ...]
propA1 and propB1 are same properties but different name, propB2 and propC1 are same properties as well.
However, propA1 and propB1 do not always have same values, but I am only interested in the "set intersect" of array [valueA1, valueA2, ...] and [valueB1, valueB2, ...], here is the goal: I want to return all propB2 from B such that their propB1 counterpart (in the same dictionary) match with propA1 in A. Then I will use that propB2 set to match with propC1 in C.
What I have tried:
propB2_match = set()
for elementB in B:
for elementA in A:
if elementB['propB1'] == elementA['propA1']:
propB2_match(elementB['propB2'])
break
At the end of this loop, I have propB2_match containing all of propB2 that I can use to match with propC1.
However, as you can see from the loop, this is an expensive O(n^2) loop. I am wondering if there is a way to handle this with O(n)? If not, is there any pythonic optimization can be done on it?
Note: I do not want to put it in a database and use relational database SQL to handle the join operation.
If I understand correctly, you are trying to do a essentially do a JOIN on A and B where columns A['propA1'] == B['propB1'].
Here's one way using defaultdict that's O(len(A)+len(B)):
from collections import defaultdict
A = [{'pA1': 'vA1'}, {'pA1': 'vA2'}]
B = [{'pB1': 'vA1', 'pB2': 'vB2'}, {'pB1': 'vB3', 'pB2': 'v4'}]
# Key by the value you want to group on
kA = [(x['pA1'],x) for x in A]
kB = [(x['pB1'],x) for x in B]
# Combine the lists
kAB = kA+kB
# Map each unique key to a list of elements that have that key
results = defaultdict(list)
for x in kAB:
results[x[0]].append(x[1])
for x in results:
print results[x]
Outputs:
[{'pA1': 'vA2'}]
[{'pB1': 'vB3', 'pB2': 'v4'}]
[{'pA1': 'vA1'}, {'pB1': 'vA1', 'pB2': 'vB2'}]
At this point you could merge each list of dicts into a single dict or whatever you need, and use the result to JOIN with the third list C.
This question already has answers here:
Assigning values to variables in a list using a loop
(5 answers)
Closed 4 years ago.
I want to do the following:
a = 1
b = 2
c = 3
tom = [a,b,c]
for i in tom:
i = 6
The desired result is a = 6
The actual result is a = 1
I'm guessing that there is no way to do this without some kind of exec. Correct?
Initially I misunderstood your question, and I see that kindall got it right. But I think this question shows a need for a more detailed explanation of how Python works. The best way to think about variables in Python is to think of variable names as having arrows attached to them, and values as objects to which those arrows point. Variable names point to objects. So when you do this:
a = 1
You're really saying "a points to 1". And when you do this:
b = a
You're really saying "b points to the same object as a". Under normal circumstances, a variable can't point to another variable name; it can only point at the same object that the other variable points at. So when you do this:
tom = [a, b, c]
You aren't creating a list that points to the variable names a, b, and c; you're creating a list that points to the same objects as a, b, and c. If you change where a points, it has no effect on where tom[0] points. If you change where tom[0] points, it has no effect on where a points.
Now, as others have pointed out, you can programmatically alter the values of variable names, ether using exec as you suggested (not recommended), or by altering globals() (also not recommended). But most of the time, it's just not worth it.
If you really want to do this, my suggestion would be either simply to use a dictionary (as suggested by DzinX) or, for a solution that's closer to the spirit of your question, and still reasonably clean, you could simply use a mutable object. Then you could use getattr and setattr to programmatically alter the attributes of that object like so:
>>> class Foo():
... pass
...
>>> f = Foo()
>>> f.a = 1
>>> setattr(f, 'b', 2)
>>> getattr(f, 'a')
1
>>> f.b
2
Generally, the best solution is to just use a dictionary. But occasionally situations might arise in which the above is better.
tom = [a, b, c] puts the values 1, 2, and 3 into the list. Once these values are in the list, there's no way to know what name(s) are pointing to them. Assuming they are global variables, you could (but almost certainly shouldn't) do this:
tom = ["a", "b", "c"]
for n in tom:
globals()[n] = 1
Trying to set individual variables in a loop is almost always the wrong approach. The values clearly have something in common, otherwise you wouldn't want to change them all in a loop, so store them in a list (or a dictionary, if you need names for them) and access and change them there, instead of using individual variables.
More concisely,
a, b, c = map(lambda x: 6, [1, 2, 3])
or
a, b, c = 1, 2, 3
a, b, c = map(lambda x: 6, [a, b, c])
which could easily be generalised if you want to assign each to different values based on their original values.
It would be best if you didn't use variables, but keys in the dictionary, like this:
values = {
'a': 1,
'b': 2,
'c': 3
}
for k in values:
values[k] = 6
print values['a']
# prints: 6
If you want to change only some values, use:
for k in ['a', 'c']:
values[k] = 6
Here's an idea.
seniority = [range(1, 6)]
people = ["Richard", "Rob", "Steve", "Terry", "Micah"]
people = seniority
print people
output: [[1, 2, 3, 4, 5,]]