how to remove python list cage - python

Like this, let's assume I have a script like this:
a = ['a','b','c','d','e']
b = random.choices(a)
print (b)
if you run that that will show like this right
['*random range a until e']
what I want the list change from this ['*random range a until e'] to '*random range a until we' can anyone help me

random.choices(), returns a LIST, as you can read here - https://www.w3schools.com/python/ref_random_choices.asp
So workaround would be to do it like this:
import random
a = ['a','b','c','d','e']
n = random.randint(0, len(a) - 1) # The randint() takes in 2 parameters, the
#lowest and the highest choice, the highest here is the length of a list
b = a[n]
print(b)

You need to join the letters obtained from random.choices.
With the argument k=<size> you can specify the length of the generated string.
>>> import random
>>> a = ['a','b','c','d','e']
>>> size = 10
>>> b = "".join(random.choices(a, k=size))
>>> b
'caccbbaade'

Related

Adding text in front of separate numbers in list

Im new to python and hit a wall with my last print in my program
I got a list of numbers created with math int(numbers that when printed looks like this
[0, 0, 0, 0] #just with random numbers from 1 - 1000
I want to add text in front of every random number in list and print it out like this
[Paul 0 Frederick 0 Ape 0 Ida 0]
Any help would be appreciated. Thanks !
Sounds like you want to make a dictionary. You could type:
d = dict()
d["Paul"] = random.randint(1,100)
....
print(d)
#output: {"Paul":1, "Fredrick":50, "Ape":25, "Ida":32}
Alternatively there is nothing stopping you from using strings and integers in the same list! Python is not strongly statically typed.
If you have a list of numbers [45,5,59,253] and you want to add names to them you probably need a loop.
nums = [45,5,59,253]
names = ["Paul", "Frederick", "Ape", "Ida"]
d = dict()
i = 0
for n in nums:
d[names[i]] = n
i+=1
or if you wanted a list
nums = [45,5,59,253]
names = ["Paul", "Frederick", "Ape", "Ida"]
list = [x for y in zip(names, nums) for x in y]
You'd have to turn your random integers into strings and add them to the text (string) you want.
Example:
lst=[]
x = str(randint(0,1000))
text = 'Alex'
final_text = text+' '+x
lst.append(final_text)
Just added the space like in your example. It'll just be a little more complex to access the numbers if you do it this way.

Get average difference between all numbers in a list (python)

I have a list where I'd like to get a sense of the difference between all the numbers in it. Algorithmically, it seems like I should take the absolute value of the subtraction of each item from a list from each other and then to find the average of the sum of subtractions. Don't worry about absolute value part. That's only relevant to my application.
For example:
list_a = [1,2,3,4]
list_a0 = (abs(1-2) + abs(1-3) + abs(1-4))/3 = 1+2+3 = 2
list_a1 = (abs(2-1) + abs(2-3) + abs(2-4))/3 = 1+1+2 = 1.33
list_a2 = (abs(3-1) + abs(3-2) + abs(3-4))/3 = 2+1+1 = 1.33
list_a3 = (abs(4-1) + abs(4-2) + abs(4-3))/3 = 3+2+1 = 2
avg = (lista0 + lista1 + lista2 + lista3)/4 = 1.67
I'm newer to python. Would someone be able to give a tip on how to loop through list_a to do this?
Consider using numpy package which is super efficient and rubust.
here is example:
>>> import numpy as np
>>> list_a = [1,2,3,4]
>>> a = np.array(list_a)
>>> np.diff(a)
[1,1,1]
takes 9.489059448242188e-05 seconds which is 0.00009 second
From your example, it appears that you are trying to loop over all permutations of the list of length 2. Luckily, itertools has a function just for that:
>>> import itertools
>>> list_a = [1,2,3,4]
>>> diffs = [abs(e[1] - e[0]) for e in itertools.permutations(list_a, 2)]
>>> sum(diffs)/len(diffs)
1.6666666666666667
If you don't want to use itertools, I advise using a for loop rather than trying to squish this into a nested list comprehension:
>>> list_a = [1,2,3,4]
>>> diffs = []
>>> for i, e in enumerate(list_a):
for j, f in enumerate(list_a):
if i != j: diffs.append(abs(e-f))
>>> sum(diffs)/len(diffs)
1.6666666666666667

find all possible rotation of a given string using python

Given string is "abc" then it should print out "abc", "bca", "cba"
My approach: find length of the given string and rotate them till length
def possible_rotation():
a = "abc"
b = len(a)
for i in range (b-1):
c = a[:i] + a[i:]
print c
Above code simply prints abc, abc. Any idea what am I missing here?
def possible_rotation():
a = "abc"
b = len(a)
for i in range (b):
c = a[i:]+a[:i]
print c
possible_rotation()
Output:
abc
bca
cab
You have 2 issues.The range issue and the rotation logic.it should be a[i:]+a[:i] not the other way round.For range range(b-1) should be range(b)
You have two errors:
range(b-1) should be range(b);
a[:i] + a[i:] should be a[i:] + a[:i].
This is what I did. I used a deque, A class in collections and then used the rotate function like this
from collections import deque
string = 'abc'
for i in range(len(string)):
c = deque(string)
c.rotate(i)
print ''.join(list(c))
And gives me this output.
abc
cab
bca
What it does. It creates a deque object, A double ended queue object, which has a method rotate, rotate takes the number of steps to rotate and returns the objects shifted to the right with the number of steps kinda like rshift in binary operations. Through the loops it shifts ad produces a deque object that I convert to list and finally to a string.
Hope this helps
for i in range(b):
print(a[i:] + a[:i])
0 - [a,b,c] + []
1 - [b,c] + [a]
2 - [c ] + [a,b]
swap the lists
No need to do (b-1),You simply do it by:
def possible_rotation():
a = "abc"
for i in range(0,len(a)):
strng = a[i:]+a[:i]
print strng
possible_rotation()
`
This looks to be homework, but here's a solution using the built-in collections.deque:
from collections import deque
def possible_rotations(string):
rotated = deque(string)
joined = None
while joined != string:
rotated.rotate(1)
joined = ''.join(x for x in rotated)
print(joined)
Test it out:
>>> print(possible_rotations('abc'))
cab
bca
abc
Two things:
Firstly, as already pointed out in the comments, you should iterate over range(b) instead of range(b-1). In general, range(b) is equal to [0, 1, ..., b-1], so in your example that would be [0, 1, 2].
Secondly, you switched around the two terms, it should be: a[i:] + a[:i].

Compare numbers in form: 12,3K , 1,84M in python

In need to compare numbers which look like: 12,3K , 1,84M, etc
eg:
a = 12,3K
b = 1,84M
if b > a :
print b
You need to use replace for it:
a = ("12,3K", "1,84M")
numbers = {"K": 1000, "M": 1000000}
result = []
for value in a:
if value:
i = value[-1]
value = float(value[:-1].replace(',', '.')) * numbers[i]
result.append(int(value))
print max(result)
You can add more numbers to dictionary and you will get more results.
I would recommend a function to convert a and b into the corresponding number like so (also I'd make a and b strings:
def convert(num):
return num.replace(',','').replace('K','000').replace('M','000000')
a = '12,3K'
b = '1,84M'
if convert(b) > convert(a) :
print b
If your values are strings, then the re module would make it easy to replace commas with '' and K or M with 3 or 6 zeroes. Then wrap in int() and compare. Where / how are you getting the values you're comparing?

Create a Python list filled with the same string over and over and a number that increases based on a variable.

I'm trying to create a list that is populated by a reoccurring string and a number that marks which one in a row it is. The number that marks how many strings there will be is gotten from an int variable.
So something like this:
b = 5
a = range(2, b + 1)
c = []
c.append('Adi_' + str(a))
I was hoping this would create a list like this:
c = ['Adi_2', 'Adi_3', 'Adi_4', 'Adi_5']
Instead I get a list like this
c = ['Adi_[2, 3, 4, 5]']
So when I try to print it in new rows
for x in c:
print"Welcome {0}".format(x)
The result of this is:
Welcome Adi_[2, 3, 4, 5]
The result I want is:
Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5
If anybody has Ideas I would appreciate it.
You almost got it:
for i in a:
c.append('Adi_' + str(i))
Your initial line was transforming the whole list a as a string.
Note that you could get rid of the loop with a list comprehension and some string formatting:
c = ['Adi_%s' % s for s in a]
or
c = ['Adi_{0}'.format(s) for s in a] #Python >= 2.6
Or as a list comprehension:
b = 5
a = range(2, b + 1)
c = ["Adi_" + str(i) for i in a]
Using list comprehensions:
b = 5
a = range(2, b + 1)
c = ['Adi_'+str(i) for i in a]
for x in c:
print"Welcome {0}".format(x)
Or all on one line:
>>> for s in ['Welcome Adi_%d' % i for i in range(2,6)]:
... print s
...
Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5

Categories

Resources