I have two lists: list_1 and list_2 containing 32 bit - strings and each is of length 2^12.
I want to sort these lists to get those pairs which contain equal bits at 20 specified positions.
list_w = []
for i in range(0, 4096):
for j in range(0, 4096):
if list_1[i][12:32] == list_2[j][12:32]:
value = (list_1[i], list_2[j])
list_w.append(value)
else:
continue
I have assumed 20 positions at the end and sort all 2^24 pairs. But this takes too much time. The answer was we can do this in 2^12 time by sorting or hashing how?
Use a dictionary to map the values at these 20 positions to the list of strings that match those values at those positions.
Building a dict of lists is a very classical idiom in python:
d1 = {}
for s in list_1:
d1.setdefault(s[12:32], []).append(s)
d2 = {}
for s in list_2:
d2.setdefault(s[12:32], []).append(s)
Then you can find your pairs by iterating on the keys that are in both dictionaries; i.e., keys that are in the intersection of the two sets of keys.
list_w = [
(s1, s2)
for k in set(d1.keys()).intersection(d2.keys())
for s1 in d1[k] for s2 in d2[k]
]
Testing:
list_1 = ['abcdefghijklmnopqrstuvwxyzabcdef', 'aaaaaaaaaaaamnopqrstuvwxyzabcdef', 'aaaaaaaaaaaabbbbbbbbbbbbbbbbbbbb']
list_2 = ['ABCDEFGHIJKLmnopqrstuvwxyzabcdef', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb']
...
print(d1)
# {'mnopqrstuvwxyzabcdef': ['abcdefghijklmnopqrstuvwxyzabcdef',
# 'aaaaaaaaaaaamnopqrstuvwxyzabcdef'],
# 'bbbbbbbbbbbbbbbbbbbb': ['aaaaaaaaaaaabbbbbbbbbbbbbbbbbbbb']}
print(d2)
# {'mnopqrstuvwxyzabcdef': ['ABCDEFGHIJKLmnopqrstuvwxyzabcdef'],
# 'bbbbbbbbbbbbbbbbbbbb': ['bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb']}
print(list_w)
# [('aaaaaaaaaaaabbbbbbbbbbbbbbbbbbbb', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'),
# ('abcdefghijklmnopqrstuvwxyzabcdef', 'ABCDEFGHIJKLmnopqrstuvwxyzabcdef'),
# ('aaaaaaaaaaaamnopqrstuvwxyzabcdef', 'ABCDEFGHIJKLmnopqrstuvwxyzabcdef')]
Related
I am trying to generate the 1000 random key-val map pairs from the given(statically defined) 2 map key-val pairs in scala and also later i would want to break the key and value pairs and store them into separate variables
Whatever i have tried:
object methodTest extends App{
val testMap = Map("3875835"->"ABCDE","316067107"->"EFGHI")
def getRandomElement(seq: Map[String,String]): Map[String,String] = {
seq(Random.nextInt(seq.length))
}
var outList = List.empty[Map[String,String]]
for(i<-0 to 1000){
outList+=getRandomElement(testMap)
}
print(outList)
}
The Output should generate 1000 Key-val pairs of map like i am showing below
[3875835,ABCDE]
[316067107,EFGHI]
[3875835,ABCDE]
[316067107,EFGHI]
[316067107,EFGHI]
............
............
............. upto 1000 random key-val pairs
Please help me figure out where i am going wrong and let me know How to resolve it, if any issue regarding the requirement, please feel free to comment for it
You can transform your seed map testMap into sequence of key/value tuples using .toSeq and then generate key/value pairs by iterating over the list of numbers from 0 until 1000, associating each number to a random choice between first or second element of the seed:
import scala.util.Random
val testMap = Map("3875835" -> "ABCDE", "316067107" -> "EFGHI")
val seed = testMap.toSeq
val keyValuesList = (0 until 1000).map(index => seed(Random.nextInt(seed.size)))
Note: 0 until 1000 will return all the numbers from 0 to 1000 excluded, so 1000 numbers. If you use 0 to 1000 you will get all the numbers from 0 to 1000 included, so 1001 numbers.
If you want to print the resulting list, you can use .foreach method with println function as argument:
keyValuesList.foreach(println)
And you will get:
(3875835,ABCDE)
(316067107,EFGHI)
(3875835,ABCDE)
(3875835,ABCDE)
(316067107,EFGHI)
(3875835,ABCDE)
...
if you want to keep only the keys, you can iterate on the list using .map method, taking only the first element of the tuple by using ._1 method, that retrieve the first element of a tuple:
val keys = keyValuesList.map(keyValuePair => keyValuePair._1)
And if you want only a list containing all second elements of each pair:
val values = keyValuesList.map(keyValuePair => keyValuePair._2)
So I'm trying to make 2 lists with random variables compare to each other to find the probability of them being the same. What I've done is made 2 lists with random numbers using a for loop, but in order to find the probability I'm trying to create the lists within another for loop in order to make 10000 pairs of lists to compare but I can't get it to work.
import random
import collections
N= 10000
count = 0
playerPick=[]
randomPick=[]
for j in range (N):
for i in range(4):
playerPick.append(random.randrange(1,21))
print(playerPick)
for i in range(4):
randomPick.append(random.randrange(1,21))
print(randomPick)
if collections.Counter(playerPick) == collections.Counter(randomPick):
count+=1
probability = count/N
print("Probability of winning: ", probability)
The lists end up being super long but I just want them to be 4 long.
This may be a more efficient way to calculate the average match count.
import random
import collections
N = 10000 # main list length
L = 4 # each element is list of 4 elements
def getpct():
# create random list of lists
playerPick=[[random.randrange(1,21) for x in range(L)] for n in range(N)]
randomPick=[[random.randrange(1,21) for x in range(L)] for n in range(N)]
# create match list, 1=match else 0
matches = [1 if p==r else 0 for p,r in zip(playerPick,randomPick)]
return sum(matches)/N # percent matches
allpcts = [getpct() for r in range(1000)] # run test 1000 times
avgpct = sum(allpcts)/1000 # average percent
print(f'Avg Pct: {avgpct}%')
Output
Avg Pct: 6.2000000000000025e-06%
I have a list like below and need to firs add items in each list and then multiply all results 2+4 = 6 , 3+ (-2)=1, 2+3+2=7, -7+1=-6 then 6*1*7*(-6) = -252 I know how to do it by accessing indexes and it works (as below) but I also need to do it in a way that it will work no matter how many sublist there is
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
a= nested_lst[0][0] + nested_lst[0][1]
b= nested_lst[1][0] + nested_lst[1][1]
c= nested_lst[2][0] + nested_lst[2][1] + nested_lst[2][2]
d= nested_lst[3][0] + nested_lst[3][1]
def sum_then_product(list):
multip= a*b*c*d
return multip
print sum_then_product(nested_lst)
I have tried with for loop which gives me addition but I don't know how to perform here multiplication. I am new to it. Please, help
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
for i in nested_lst:
print sum(i)
Is this what you are looking for?
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]] # your list
output = 1 # this will generate your eventual output
for sublist in nested_lst:
sublst_out = 0
for x in sublist:
sublst_out += x # your addition of the sublist elements
output *= sublst_out # multiply the sublist-addition with the other sublists
print(output)
I want to print all elements in this list in reversed order and every element in this list must be on a new line.
For example if the list is ['i', 'am', 'programming', 'with', 'python'] it should print out:
python
with
programming
am
i
What is the best way to do this?
def list():
words = []
while True:
output = input("Type a word: ")
if output == "stop":
break
else:
words.append(output)
for elements in words:
print(elements)
list()
generic :
for(i=wordsArry.size();i--;i<0){
pritnln(wordsArry[i]+"/n")
}
Start iteration from the end of the list - last element in it.
Then iterate backwards - decrease iterator by 1 till you reach 0.
Print each element plus new line symbol - might depend on OS,
language.
In Python you can reverse a list in place by:
words = ['i', 'am', 'programming', 'with', 'python']
words.reverse()
for w in words:
print(w)
If you want to iterate in reverse but keep the original order, you can use a slice:
for w in words[::-1]:
print(w)
Slice syntax is [begin:end:step], where begin (incl) and end (excl) indices are omitted (get all elements) and the step -1 returns a slice with the elements in reverse order.
Both methods produce the same output.
I want to count total number of '1's in binary format of a number which is in a list.
z = ['0b111000','0b1000011'] # z is a list
d = z.count('1')
print(d)
The output is 0.
Whereas the required output should be in the form of [3,3]
which is number of ones in every element that Z is containing :
Here it is :
z=['0b111000','0b1000011']
finalData = []
for word in z:
finalData.append(word.count('1'))
print(finalData)
The problem with your code was you were trying to use count() method on list type and it is used for string. You first need to get the string from the list and then use count() method on it.
Hope this helps :)
z = ['0b111000','0b1000011']
d = z.count('1')
This attempts to find the number of times the string '1' is in z. This obviously returns 0 since z contains '0b111000' and '0b1000011'.
You should iterate over every string in z and count the numbers of '1' in every string:
z = ['0b111000','0b1000011']
output = [string.count('1') for string in z]
print(output)
# [3, 3]
list.count(x) will count the number of occurrences such that it only counts the element if it is equal to x.
Use list comprehension to loop through each string and then count the number of 1s. Such as:
z = ['0b111000','0b1000011']
d = [x.count("1") for x in z]
print(d)
This will output:
[3, 3]