rearranging list using for loop and random choice [duplicate] - python

This question already has answers here:
Difference between list += ‘string’ and list +=[‘string’]
(2 answers)
Python append() vs. + operator on lists, why do these give different results?
(7 answers)
Closed last month.
import random
a=['sai','raju','phani']
b=[]
for I in a:
b += random.Choice(a)
print(b)
result:
['s', 'a', 'i', 's', 'a', 'i', 'r', 'a', 'j', 'u']
but expected to be total string not individual
['sai','sai','raju']
What did I do wrong?

You can use random.choices and pass in the number of samples for b in the argument k.
import random
a=['sai','raju','phani']
b=[]
b = random.choices(a, k=len(a))
print(b)
EDIT: if you want it in a for loop:
for i in range(len(a)):
b.append(random.choice(a))

Related

How to print a jagged array vertically? [duplicate]

This question already has answers here:
Transpose list of lists
(14 answers)
Closed 3 years ago.
I have an array like this:
arr = [['a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h'],
['i', 'j']]
How to get the output like this?
str = aei bfj cg dh
So basically, how to print a jagged array vertically?
from itertools import zip_longest
for row in zip_longest(*arr, fillvalue=''):
print(' '.join(row))
You can use itertools.zip_longest to stride column-wise, and then filter out when None is encountered. Then pass that as a generator expression through str.join to create a single space-delimited string.
>>> import itertools
>>> ' '.join(''.join(filter(None, i)) for i in itertools.zip_longest(*arr))
'aei bfj cg dh'

Assigning Random Numbers to Variables Without Duplicates in Python [duplicate]

This question already has answers here:
How do I create a list of random numbers without duplicates?
(21 answers)
Closed 4 years ago.
I am new to Python and need help regarding assigning numbers to variables. How would I assign a random number from 0 to 9 to the variables "a" through "j" so that each variable gets a random number with no duplicates? Thanks in advance!
You could do something like this to return a dictionary where the letters have been randomly mapped to numbers as well. It's a bit longer than other answers, but maybe easier for a beginner to follow the logic
import random
numbers_list = []
combined = {}
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
while True:
number = random.randint(0, 9)
if number in numbers_list:
pass
else:
numbers_list.append(number)
combined.update({alphabet.pop(): number})
if len(numbers_list) == 10:
break
Here's one way:
import random
vals = list(range(10))
random.shuffle(vals)
a,b,c,d,e,f,g,h,i,j = vals

Print same index of lists within lists [duplicate]

This question already has answers here:
Matrix Transpose in Python [duplicate]
(19 answers)
How do I transpose a List? [duplicate]
(4 answers)
Closed 4 years ago.
I have a list with lists in it.
[['H','J','K','L'],['Q','W','E','R'],['R','W','Q','T']]
I want to print the same indexes within one line with a space between them.the So output would be:
H Q R
J W W
K E Q
L R T
I tried using for loop using enumerate and while loop. Nothing seems to work and I'm just a beginner so I don't even know the correct way to approach this. I'd be really grateful if someone could help me out.
Thanks a lot! Have a nice day!
You can use str.join with zip:
s = [['H', 'J', 'K', 'L'], ['Q', 'W', 'E', 'R'], ['R', 'W', 'Q', 'T']]
new_s = '\n'.join(' '.join(i) for i in zip(*s))
Output:
H Q R
J W W
K E Q
L R T
'''
OP has 3 nested lists. OP wants to print each row of the list unto a line with
a space in between each line item.
'''
sample_list = [['H', 'J', 'K', 'L'], ['Q', 'W', 'E', 'R'], ['R', 'W', 'Q', 'T']]
import numpy as np
sample_array = np.array(sample_list)
print(sample_array.reshape(4, 3))
Here is the output:
[['H' 'J' 'K']
['L' 'Q' 'W']
['E' 'R' 'R']
['W' 'Q' 'T']]
As a beginner, it may be useful to learn about numpy. It simplifies tasks such as this when you are working with data in lists. What I did here is I created a numpy array from the nested list that you showed. numpy has a method called. reshape() that allows you to align the amount of rows and columns that you want for the data. In your example you wanted 4 rows and 3 columns for the letter, so passing 4, 3 to the .reshape() function will allow you to get 4 rows and 3 columns for the data. As a beginner, there are libraries in Python such as numpy that can help you simplify tasks such as this. I hope that this answer helps as you learn more.
For your specific case it's sufficient to do the following:
for i in range(len(list_a[0])):
print(" ".join([l[i] for l in list_a]))
The for loop makes sure that you are getting element in the order you want and the list comprehension just gets elements from sublists at specified index and prints them in order.

How to convert a string to a list? [duplicate]

This question already has answers here:
How to create a list with the characters of a string? [duplicate]
(5 answers)
Closed 7 years ago.
If I have a string:
a = 'hello'
How do I convert it into a list?
a = ['h', 'e', 'l', 'l', 'o']
A string is an iterable, and a list can be constructed from an iterable. So all you need is
a = list(a)
print(a)
Output:
['h', 'e', 'l', 'l', 'o']
Tried to do it differently
Code:
map(None,"sart")#for python 2.x
#list(map(None,"sart")) for python 3.x
Output:
['s', 'a', 'r', 't']

Compare lists to find common elements in python [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python - Intersection of two lists
i'm trying to compare two lists in order to find the number of elements they have in common.
The main problem I'm having is when either list contains repeated elements, for example
A = [1,1,1,1] and
B = [1,1,2,3]
using the code
n = 0
for x in A:
if x in B:
n += 1
print n
gives me the output that n = 4, as technically all elements of A are in B
I'd like to get the output that n = 2, preferably without using sets, Is there anyway I can adapt my code, or a new way of thinking about the problem to achieve this?
Thanks
It's not entirely clear what your specification is, but if you want the number of elements in A that appear in B, without regard to order, but with regard to multiplicity, use collections.Counter:
>>> from collections import Counter
>>> A = [1,1,1,1]
>>> B = [1,1,2,3]
>>> C = Counter(A) & Counter(B)
>>> sum(C.itervalues())
2
>>> list(C.elements())
[1, 1]
Here is an efficient (O(n logn)) way to do it without using sets:
def count_common(a, b):
ret = 0
a = sorted(a)
b = sorted(b)
i = j = 0
while i < len(a) and j < len(b):
c = cmp(a[i], b[j])
if c == 0:
ret += 1
if c <= 0:
i += 1
if c >= 0:
j += 1
return ret
print count_common([1,1,1,1], [1,1,2,3])
If your lists are always sorted, as they are in your example, you can drop the two sorted() calls. This would give an O(n) algorithm.
Here's an entirely different way of thinking about the problem.
Imagine I've got two words, "hello" and "world". To find the common elements, I could iterate through "hello", giving me ['h', 'e', 'l', 'l', 'o']. For each element in the list, I'm going to remove it from the second list(word).
Is 'h' in ['w', 'o', 'r', 'l', 'd']? No.
Is 'e' in ['w', 'o', 'r', 'l', 'd']? No.
Is 'l' in ['w', 'o', 'r', 'l', 'd']? Yes!
Remove it from "world", giving me ['w', 'o', 'r', 'd'].
is 'l' in ['w', 'o', 'r', 'd']? No.
Is 'o' in ['w', 'o', 'r', 'd']?
Yes! Remove it ['w', 'o', 'r', 'd'], giving me ['w', 'r', 'd']
Compare the length of the original object (make sure you've kept a copy around) to the newly generated object and you will see a difference of 2, indicating 2 common letters.
So you want the program to check whether only elements at the same indices in the two lists are equal? That would be pretty simple: Just iterate over the length of the two arrays (which I presume, are supposed to be of the same length), say using a variable i, and compare each by the A.index(i) and B.index(i) functions.
If you'd like, I could post the code.
If this is not what you want to do, please do make your problem clearer.

Categories

Resources