Python-----Advanced Iterators

Source: Internet
Author: User
Tags assert ord

Python Note--9.5
Map/reduce
Both map () and reduce () are Python built-in functions

The map () function accepts two parameters, one is a function and the other is iterable. Map functions The passed-in function once to each element of the sequence and returns the result as a new iterator.
For example:
def f (x):
Return x*x
R=map (f,[1,2,3,4,5,6,7,8,9])
Print (list (R))
Result
[1,4,9,16,25,36,49,64,81]

Another example:
Print (List (map (str,[1,2,3,4,5,6,7,8,9)))
Result
[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']

Reduce () functions a function in a sequence [x1,x2,x3,...] , the function receives two parameters, and reduce accumulates the result and the next element of the sequence.
Such as:
Reduce (f,[x1,x2,x3,x4]) =f (f (f (x1,x2), x3), x4)
Requirement 1: Convert [1,2,3,4,5] to 12345 output

From Functools import reduce
DEF fn (x, y):
Return 10*x+y
Reduce (fn,[1,2,3,4,5])

Requirement 2: Convert string ' 13579 ' to digital 13579 output
From Functools import reduce
def str2int (s):
DEF fn (x, y):
Return X*10+y
def char2num (s):
Retuen return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[s]
return reduce (Fn,map (char2num,s))
Requirement 3: Convert string ' 123.456 ' to 123.456
def str2float (s):
DEF fn (x, y):
Return X*10+y
def FX (x, y):
Return X/10+y
def char2num (s):
return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[s]
L=s.split ('. ', 1)
return reduce (Fn,map (char2num,l[0)) +reduce (Fx,map (char2num,l[1][-1::-1]))/10
--------------------------------------------------------------------------------------------------------------- -
Build expressions (Generator expression)
Like a build function, but it's not a function
unique_characters={' E ', ' D ', ' M ', ' O ', ' N ', ' S ', ' R ', ' Y '}
Gen= (Ord (c) for C in Unique_characters)
Next (Gen) #69
Next (Gen) #68

Tuple (ord (c) for C in Unique_characters)
print (tuple) # (69,68,77,79,78,83,82,89)

Use the build function to accomplish the same task:
def ord_map (a_string):
For C in a_string:
Yield Ord (c)
Gen=ord_map (Unique_characters)


---------------------------------------------------------------------------------
Calculation of permutation combinatorial problems:
Import Itertools
There are lots of interesting things in Itertools, and permutations () is an interesting way to find all the permutations and combinations in them.


Import Itertools
Perms=itertools.permutations ([1,2,3],2)
Next (perms) #
Next (perms) # (1,3)
Next (perms) # (2,1)
Next (perms) # (2,3)
Next (perms) # (3,1)
Next (perms) # (3,2)

Permutations () receives two parameters, one is a sequence, and the other is an int integer representing the number of elements you want in each combination
Permutations () must not receive a list, can be any sequence, or even a string
For example:
Import Itertools
Perms=itertools.permutations (' ABC ', 3)
Print (list (perms))
‘‘‘
[
(' A ', ' B ', ' C '), (' A ', ' C ', ' B '),
(' B ', ' A ', ' C '), (' B ', ' C ', ' a '),
(' C ', ' A ', ' B '), (' C ', ' B ', ' a ')
]
‘‘‘
----------------------------------------------
Another interesting method in the Itertools module

Import Itertools
List (itertools.product (' ABC ', 123 '))
[
(' A ', ' 1 '), (' A ', ' 2 '), (' A ', ' 3 '),
(' B ', ' 1 '), (' B ', ' 2 '), (' B ', ' 3 '),
(' C ', ' 1 '), (' C ', ' 2 '), (' C ', ' 3 ')
]

List (itertools.combinations (' ABC ', 2))
[(' A ', ' B '), (' A ', ' C '), (' B ', ' C ')]

-------------------------------------------------
Example:
Names=list (Open (' Favorite-people.txt ', encoding= ' utf-8 '))
Print (names)
[' dora\n ', ' ethan\n ', ' wesley\n ', ' john\n ', ' anne\n ',
' mike\n ', ' chris\n ', ' sarah\n ', ' alex\n ', ' lizzie\n ']

List (filename) returns each row of data in a text file as a list, but ' \ n ' also contains a return

Use the Rstrip () method to remove the trailing ' \ n '
Names=[name.rstrip () for name in Names]
Print (names)
[' Dora ', ' Ethan ', ' Wesley ', ' John ', ' Anne ',
' Mike ', ' Chris ', ' Sarah ', ' Alex ', ' Lizzie '

Use the sorted () method to sort the list by default in alphabetical order
names=sorted (names)
Print (names)
[' Alex ', ' Anne ', ' Chris ', ' Dora ', ' Ethan ',
' John ', ' Lizzie ', ' Mike ', ' Sarah ', ' Wesley '

The sorted () method can receive a key parameter that indicates the Sort method
Names=sorted (Names,key=len)
Print (names)
[' Alex ', ' Anne ', ' Dora ', ' John ', ' Mike ',
' Chris ', ' Ethan ', ' Sarah ', ' Lizzie ', ' Wesley '
That is, sort by name length.

So how do you use Itertools for the same operation?
Import Itertools
Groups=itertools.groupby (Names,len)

The Itertools.groupby method receives two parameters, a sequence and a key method, and returns an iterator (iterator) that generates a pair of pairs. Each group pair (pair) contains
The result of Key_function (each item) and another iterator (containing all elements with the same key value)
The list (groups) operation can get the following results:
[(4, <itertools._grouper object at 0x00ba8bf0>),
(5, <itertools._grouper object at 0x00bb4050>),
(6, <itertools._grouper object at 0x00bb4030>)]


Below I try to traverse:
Groups=itertools.groupby (Name,len)
For Name_length,name_iter in groups:
Print (' Names with {0:d} letters: '. Format (name_length))
For name in Name_iter:
Print (name)

The following results can be obtained:
Names with 4 letters:
Alex
Anne
Dora
John
Mike
Names with 5 letters:
Chris
Ethan
Sarah
Names with 6 letters:
Lizzie
Wesley

Note: the Itertools.groupby () method is only valid if the input sequence has already been sorted, such as in this case, it is possible to group with Len because we have already made the names
Sorted (Names,key=len)

----------------Itertools.chain ()-------------------------------------
List (range (0,3)) #[0,1,2]
List (range (10,13)) #[10,11,12]

List (Itertools.chain (range (0,3), Range (10,13)) #[0,1,2,10,11,12]
The Itertools.chain () method can receive any number of iterators that can be connected in the order in which they are passed in

-------------zip ()--------------------------------------------
List (Zip (range 0,3), range (10,13)) #[(0,10), (1,11), (2,12)]
List (Zip (range (0,3), Range (10,13), Range (20,23))) #[(0, 10, 20), (1, 11, 21), (2, 12, 22)]
The ZIP () method receives any number of sequences, returns the tuple that consists of the first element of all sequences, and the second element consists of a tuple ....

List (Zip (range (0, 3), range (10, 14)) #[(0,10), (1,11), (2,12)]
The Zip () method stops at the end of the shortest sequence, as described in the previous example.

List (Itertools.zip_longest (range 0,3), range (10,14)) #[(0, ten), (1, one), (2,), (None, 13)]
But the Itertools.zip_longest () method ends at the end of the longest sequence, and the short sequence has no value corresponding to the fill with none


-------------------------------alphametics Solver (Arithmetic puzzle method)------------------------------------

characters= (' S ', ' M ', ' E ', ' D ', ' O ', ' N ', ' R ', ' Y ')
guess= (' 1 ', ' 2 ', ' 0 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ')
Tuple (Zip (characters,guess))
return Result:
(' S ', ' 1 '), (' M ', ' 2 '), (' E ', ' 0 '), (' D ', ' 3 '),
(' O ', ' 4 '), (' N ', ' 5 '), (' R ', ' 6 '), (' Y ', ' 7 ')
Dict (Zip (character,guess))
return Result:
{' E ': ' 0 ', ' D ': ' 3 ', ' M ': ' 2 ', ' O ': ' 4 ',
' N ': ' 5 ', ' S ': ' 1 ', ' R ': ' 6 ', ' Y ': ' 7 '}

The arithmetic puzzle method uses this technique to create a dictionary that maps the letters inside the puzzle to the numbers in the solution.

Characters=tuple (Ord (c) for C in Sorted_characters)
Digits=tuple (Ord (c) for C in ' 0123456789 ')
...
For guess in Itertools.permutations (Digits,len (characters)):
...
Equation=puzzle.translate (dict (Zip (characters,guess)))
-------------explain the translate () method first-----------------------------
There are many ways to strings in Python, including lower (), count (), format (), and so on, and now you want to introduce a rare but powerful method: translate ()
Translate_table={ord (' A '): Ord (' O ')}
Print (translate_table) #{65:79}
' MARK ' translate (translate_table) # ' Mork '

The conversion method of a string requires a conversion table (translate_table), which is a dictionary that maps one character to another, and of course the character is not very accurate, it should be said to be byte
Bytes in Python3 (integer), the Ord () method returns the ASCII value of one character (a-z:65-90)
The translate () method acting on the string takes a conversion table (Translate_table) and runs the string in that table, replacing any key that appears in the conversion table
value, replacing it with its corresponding value. (In this case, translate MARK to Mork)
-------------------------------------------------------------

Does this have anything to do with solving the problem of alphabet arithmetic? Please see below:
Characters=tuple (Ord (c) for C in ' Smedonry ')
Print (character) # (83, 77, 69, 68, 79, 78, 82, 89)
Guess=tuple (Ord (c) for C in ' 91570682 ')
Print (guess) # (57, 49, 53, 55, 48, 54, 56, 50)
Translate_table=dict (Zip (character,guess))
Print (translate_table) #{68:55, 69:53, 77:49, 78:54, 79:48, 82:56, 83:57, 89:50}

' Send+more==money '. Translate (translate_table) # ' 9567+1085==10652 '

-----------------------evaluates any string as a Python expression---------------------------------
Eval (' 1+1==2 ') #True
Eval (' 1+1=3 ') #False
Eval (' 9576+1085==10652 ') #True

The eval () method is much more than a Boolean expression
Eval (' "A" + "B" ') # ' AB '
Eval (' Mark '. Translate ({65:79}) ') #MORK
Eval (' AAAAA '. Count ("A") ') #5
Eval (' [' * ' * ']*5 ') #[' * ', ' * ', ' * ', ' * ', ' * '

X=5
Eval (' x*5 ') #25
Eval (' Pow (x,2) ') #25

Import Math
Eval (' math.sqrt (x) ') #2.2360679774997898


-----------------------------------------how to solve alphametic Puzzles-------------------------------------------
1,find All letters in the Puzzle:re.findall (), return a list
2,find all the unique letters in the Puzzle:with sets and the set () Function,return a Set;with ". Join () function join words
Together;with Set () to get seperate letters
3,check If there is more than a unique letters:with an assert stateme NT (meaning that the puzzle if definitely unsolvable)
4,convert The letters to their ASCII equivalents:with a generator Object (Unique_character={ord (c) for C-unique_characters})
5,calculates all the possible solutions:with the Itertools.permutation () function
6,convert possible solution to a Python Expression:with translate () string Method
7,test Each possible solution by evaluating the Python expression:with eval () function
8,return the first Solu tion that evaluates to True

---------------------Codes----------------------------------------------
Import re
Import Itertools

def solve (puzzle):
Words = Re.findall (' [a-z]+ ', Puzzle.upper ())
Unique_characters = Set (". join (words))
Assert Len (unique_characters) <=, ' Too many letters '
First_letters = {Word[0] for word in words}
n = Len (first_letters)
Sorted_characters = '. Join (first_letters) + \
'. Join (Unique_characters-first_letters)
characters = tuple (ord (c) for C in Sorted_characters)
digits = tuple (ord (c) for C in ' 0123456789 ')
Zero = digits[0]
For guess in itertools.permutations (digits, Len (characters)):
If zero in guess[:n]:
Equation = puzzle.translate (dict (Zip (characters, guess))
If eval (equation):
return equation

if __name__ = = ' __main__ ':
Import Sys
For puzzle in Sys.argv[1:]:
Print (Puzzle)
Solution = Solve (puzzle)
If solution:
Print (solution)

Python-----Advanced Iterators

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.