create multiple ppt slides with python - python

I want to print the slides based on array list. But somehow I don't grasp the logic. My code right now is like this
totalSheets = [0, 1, 2]
totalSlides = ['slide', 'slide2', 'slide3']
prs = Presentation()
blank_slide_layout = prs.slide_layouts[6]
for sheet, slide in zip(totalSheets, totalSlides):
sheetExcel = excelFile.sheet_by_index(sheet)
slide = prs.slides.add_slide(blank_slide_layout)
I wrong at the slide one. I just thinking is it can doing like slide(n) and just do n += 1? Thanks for any help in advance

if you want to actually use random in the list, you can use this..
>>> import random
>>> totalSlides = ['slide', 'slide2', 'slide3']
>>> random.choice(totalSlides)
'slide3'
>>> random.choice(totalSlides)
'slide'
>>>
For mutiple on list, you can try this..
>>> import random
>>> totalSlides = ['slide', 'slide2', 'slide3']
>>> random.sample(totalSlides, len(totalSlides))
['slide2', 'slide3', 'slide']
>>> random.sample(totalSlides, len(totalSlides))
['slide3', 'slide', 'slide2']
>>> random.sample(totalSlides, len(totalSlides))
['slide2', 'slide', 'slide3']
>>> random.sample(totalSlides, len(totalSlides))
['slide3', 'slide2', 'slide']
>>>

Related

choosing multiple element in python list

How can i choose random multiple elements from list ? I looked it from internet but couldn't find anything.
words=["ar","aba","oto","bus"]
You could achieve that with random.sample():
from random import sample
words = ["ar", "aba", "oto", "bus"]
selected = sample(words, 2)
That would select 2 words randomly from the words list.
You can check Python docs for more details.
I think about that :
import random as rd
words=["ar","aba","oto","bus"]
random_words = [word for word in words if rd.random()>1/2]
You can adjust 1/2 by any value between 0 and 1 to approximate the percentage of words chosen in the initial list.
Use random
Here is example
random.choice
>>> import random
>>> words=["ar","aba","oto","bus"]
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
oto
>>> print(random.choice(words))
aba
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
bus
random.sample # sample takes one extra argument to pass a list with element is returned
>>> print(random.sample(words, 3))
['bus', 'ar', 'oto']
>>> print(random.sample(words, 3))
['ar', 'oto', 'aba']
>>> print(random.sample(words, 2))
['aba', 'bus']
>>> print(random.sample(words, 2))
['ar', 'aba']
>>> print(random.sample(words, 1))
['ar']
>>> print(random.sample(words, 1))
['ar']
>>> print(random.sample(words, 1))
['oto']
>>> print(random.sample(words, 1))
['bus']
You can use random library
Method 1 - random.choice()
from random import choice
words=["ar","aba","oto","bus"]
word = choice(words)
print(word)
Method 2 - Generate Random Index
from random import randint
words=["ar","aba","oto","bus"]
ind = randint(0, len(words)-1)
word = words[ind]
print(word)
Method 3 - Select Multiple Items
from random import choices
words=["ar","aba","oto","bus"]
selected = choices(words, k=2) # k is the elements count to select
print(selected)

How to select a number without replacement in python

So I'm trying to make a mix and match between numbers here is my code
import random
P1 = float(input("Person's name?"))
P2 = float(input("Person's name?"))
P3 = float(input("Person's name?"))
A1 = float(input("Activity?"))
A2 = float(input("Activity?"))
A3 = float(input("Activity?"))
s = (A1, A2, A3)
cool1 = random.sample([A1, A2, A3],1)
cool2 = random.sample([A1, A2, A3],1)
cool3 = random.sample([A1, A2, A3],1)
print ("%s job is %s." %(P1, cool1))
print ("%s job is %s." %(P2, cool2))
print ("%s job is %s." %(P3, cool3))
The problem is that it is randomizing but it keeps repeating numbers like here
**
1.0 job is [4.0].
2.0 job is [5.0].
3.0 job is [4.0].
**
What can I do to make it not repeat.
I'm using python 2.7.12
Also how can I use alphanumerical instead of float only.
Best way to achieve this will be to use random.shuffle (if you want to randomize the original sample list) or random.select (if you want to keep the original sample copy):
Example with random.shuffle:
>>> import random
>>> my_samples = ['A1', 'A2', 'A3']
>>> shuffle(my_samples)
>>> cool1, cool2, cool3 = my_samples
# Random Result: cool1 = 'A3', cool2='A1', cool3='A2'
Example with random.select:
>>> cool1, cool2, cool3 = random.sample(['A1', 'A2', 'A3'], 3)
If you want minimal changes in your solution. You may remove an entry from your samples based on random selection and get next choice from remaining samples like:
>>> import random
>>> cool1 = random.sample(my_samples,1)
>>> my_samples.remove(*cool1)
>>> my_samples
['A1', 'A3']
>>> cool2 = random.sample(my_samples,1)
>>> my_samples.remove(*cool2)
>>> cool3 = random.sample(my_samples,1)
>>> my_samples.remove(*cool3)
>>> my_samples
[]
>>> cool1, cool2, cool3
(['A2'], ['A3'], ['A1'])
write a class to pick a unique element from list
1. permutations finds all unique elements
2. rest can define new data and length of result
from itertools import permutations
class PickOne( object ):
def __init__(self,lst,l):
self.lst = lst
self.visit = set()
self.l = l
self.lenght = self.number(l)
def pick(self):
if len(self.visit) == self.lenght :
print 'run out numbers'
return
res = tuple(random.sample(self.lst,self.l))
while res in self.visit:
res = tuple(random.sample(self.lst,self.l))
self.visit.add( res )
return res
def reset(self,l,lst = None):
if not lst:
lst = self.lst
self.__init__(lst,l)
def number(self,l):
return len( list(permutations(self.lst,l)) )
Example:
a = PickOne([1,2,3,4],1)
>>> a.pick()
(2,)
>>> a.pick()
(1,)
>>> a.pick()
(4,)
>>> a.pick()
(3,)
>>> a.pick()
run out numbers
>>> a.reset(2)
>>> a.pick()
(3, 1)
>>> a.pick()
(3, 4)
>>> a.pick()
(2, 1)
Since you are selecting from a list, then you should delete the entry from the list after each check.
Create your original list, which will be used as needed.
Create a second list from the first to use as you select.
As you choose each element from the list, remove it
Put the chosen element into a list of chosen element.
Python remove method
Parameters
obj -- This is the object to be removed from the list.
Return Value
This method does not return any value but removes the
given object from the list.
Example
The following example shows the usage of remove() method.
#!/usr/bin/python
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.remove('xyz');
print "List : ", aList
aList.remove('abc');
print "List : ", aList
When we run above program, it produces following result −
List : [123, 'zara', 'abc', 'xyz']
List : [123, 'zara', 'xyz']
You could do this:
cool1, cool2, cool3 = random.sample([A1, A2, A3], 3)
Also how can I use alphanumerical instead of float only.
Have you tried not converting your inputs to float...?

Get values in string - Python

I am new to Python so I have lots of doubts. For instance I have a string:
string = "xtpo, example1=x, example2, example3=thisValue"
For example, is it possible to get the values next to the equals in example1 and example3? knowing only the keywords, not what comes after the = ?
You can use regex:
>>> import re
>>> strs = "xtpo, example1=x, example2, example3=thisValue"
>>> key = 'example1'
>>> re.search(r'{}=(\w+)'.format(key), strs).group(1)
'x'
>>> key = 'example3'
>>> re.search(r'{}=(\w+)'.format(key), strs).group(1)
'thisValue'
Spacing things out for clarity
>>> Sstring = "xtpo, example1=x, example2, example3=thisValue"
>>> items = Sstring.split(',') # Get the comma separated items
>>> for i in items:
... Pair = i.split('=') # Try splitting on =
... if len(Pair) > 1: # Did split
... print Pair # or whatever you would like to do
...
[' example1', 'x']
[' example3', 'thisValue']
>>>

I have a string that i need to put into an object, but i cant get it to work

I obtain a string: "{{39.830000, -98.580000}, {20.265710, 64.589962}}"
Afterwards, i am triyng to get it to get all the numbers and place it into variables, but it doesnt seem to work.
I was triyng to do
t = mystring.split("}, {");
t[0].split(","); #etc...
and a bunch of other things... but non seem to work.
Im trying to just place the 4 floats into variabes, a, b, c and d
How about this:
>>> import ast
>>> s = "{{39.830000, -98.580000}, {20.265710, 64.589962}}"
>>> s = s.replace("{", "[").replace("}", "]")
>>> l = ast.literal_eval(s)
>>> l
[[39.83, -98.58], [20.26571, 64.589962]]
Now you've got all your values as floats in a nice, indexable list.
If you want, you can then do
>>> (a, b), (c, d) = l # Thanks Lev!
>>> a
39.83
>>> # etc.

Move an entire element in with lxml.etree

Within lxml, is it possible, given an element, to move the entire thing elsewhere in the xml document without having to read all of it's children and recreate it? My best example would be changing parents. I've rummaged around the docs a bit but haven't had much luck. Thanks in advance!
.append, .insert and other operations do that by default
>>> from lxml import etree
>>> tree = etree.XML('<a><b><c/></b><d><e><f/></e></d></a>')
>>> node_b = tree.xpath('/a/b')[0]
>>> node_d = tree.xpath('/a/d')[0]
>>> node_d.append(node_b)
>>> etree.tostring(tree) # complete 'b'-branch is now under 'd', after 'e'
'<a><d><e><f/></e><b><c/></b></d></a>'
>>> node_f = tree.xpath('/a/d/e/f')[0] # Nothing stops us from moving it again
>>> node_f.append(node_b) # Now 'b' and its child are under 'f'
>>> etree.tostring(tree)
'<a><d><e><f><b><c/></b></f></e></d></a>'
Be careful when moving nodes having a tail text. In lxml tail text belong to the node and moves around with it. (Also, when you delete a node, its tail text is also deleted)
>>> tree = etree.XML('<a><b><c/></b>TAIL<d><e><f/></e></d></a>')
>>> node_b = tree.xpath('/a/b')[0]
>>> node_d = tree.xpath('/a/d')[0]
>>> node_d.append(node_b)
>>> etree.tostring(tree)
'<a><d><e><f/></e><b><c/></b>TAIL</d></a>'
Sometimes it's a desired effect, but sometimes you will need something like that:
>>> tree = etree.XML('<a><b><c/></b>TAIL<d><e><f/></e></d></a>')
>>> node_b = tree.xpath('/a/b')[0]
>>> node_d = tree.xpath('/a/d')[0]
>>> node_a = tree.xpath('/a')[0]
>>> # Manually move text
>>> node_a.text = node_b.tail
>>> node_b.tail = None
>>> node_d.append(node_b)
>>> etree.tostring(tree)
>>> # Now TAIL text stays within its old place
'<a>TAIL<d><e><f/></e><b><c/></b></d></a>'
You could use .append(), .insert() methods to add a subelement to the existing element:
>>> from lxml import etree
>>> from_ = etree.fromstring("<from/>")
>>> to = etree.fromstring("<to/>")
>>> to.append(from_)
>>> etree.tostring(to)
'<to><from/></to>'

Categories

Resources