Matrix 2015/11/18 Hongfei Yan zip(*a) is matrix transposition

Slides:



Advertisements
Similar presentations
The Game of Algebra or The Other Side of Arithmetic The Game of Algebra or The Other Side of Arithmetic © 2007 Herbert I. Gross by Herbert I. Gross & Richard.
Advertisements

Computer Science 1620 Loops.
Introduction to Analysis of Algorithms
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
A Data Locality Optimizing Algorithm based on A Data Locality Optimizing Algorithm by Michael E. Wolf and Monica S. Lam.
C++ for Engineers and Scientists Third Edition
Copyright © Cengage Learning. All rights reserved. CHAPTER 11 ANALYSIS OF ALGORITHM EFFICIENCY ANALYSIS OF ALGORITHM EFFICIENCY.
Lecture 2 MATLAB fundamentals Variables, Naming Rules, Arrays (numbers, scalars, vectors, matrices), Arithmetical Operations, Defining and manipulating.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
Decision Making and Branching (cont.)
Arrays Department of Computer Science. C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
CS 115 Lecture 17 2-D Lists Taken from notes by Dr. Neil Moore.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Arrays Chapter 7.
Chapter 11 - JavaScript: Arrays
Introduction to Analysis of Algorithms
REPETITION CONTROL STRUCTURE
EGR 2261 Unit 10 Two-dimensional Arrays
Merge Sort 5/28/2018 9:55 AM Dynamic Programming Dynamic Programming.
Loops BIS1523 – Lecture 10.
Repetition Structures Chapter 9
© 2016 Pearson Education, Ltd. All rights reserved.
What to do when a test fails
Topics Introduction to Repetition Structures
CS1371 Introduction to Computing for Engineers
Matrix 2016/11/30 Hongfei Yan zip(*a) is matrix transposition
2-D Lists Taken from notes by Dr. Neil Moore
Algorithm Analysis CSE 2011 Winter September 2018.
JavaScript: Functions.
( Iteration / Repetition / Looping )
Topics Introduction to Repetition Structures
While Loops BIS1523 – Lecture 12.
Ruth Anderson UW CSE 160 Spring 2018
C Passing arrays to a Function
Efficiency (Chapter 2).
Repeating Instructions And Advance collection
Algorithm design and Analysis
INFO/CSE 100, Spring 2006 Fluency in Information Technology
One-Dimensional Array Introduction Lesson xx
Python Primer 2: Functions and Control Flow
Algorithm An algorithm is a finite set of steps required to solve a problem. An algorithm must have following properties: Input: An algorithm must have.
CNG 140 C Programming (Lecture set 8)
Use of Mathematics using Technology (Maltlab)
Unit-2 Divide and Conquer
EKT150 : Computer Programming
Ruth Anderson UW CSE 140 Winter 2014
Iteration: Beyond the Basic PERFORM
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Topics Sequences Introduction to Lists List Slicing
Nested Loops & The Step Parameter
Loop Statements & Vectorizing Code
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
For loops Taken from notes by Dr. Neil Moore
Data Structures & Algorithms
Topics Introduction to Repetition Structures
Topics Sequences Introduction to Lists List Slicing
2-Dimensional Lists (Matrices) in Python
Loop Statements & Vectorizing Code
DETERMINANT MATH 80 - Linear Algebra.
2-D Lists Taken from notes by Dr. Neil Moore
Arrays.
Control flow: Loops UW CSE 160.
Introduction to Computer Science
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

Matrix 2015/11/18 Hongfei Yan http://stackoverflow.com/questions/10169919/python-matrix-transpose-and-zip zip(*a) is matrix transposition >>> A = [[0,0],[1,1],[2,2]] >>> zip(*A) [(0, 1, 2), (0, 1, 2)] --------------------------------------------- How to get the transpose of this matrix.. Any easier ,algorithmic way to do this... 1st question: Input a=[[1,2,3],[4,5,6],[7,8,9]] Expected output a=[[1, 4, 7], [2, 5, 8], [3, 6, 9]] 2nd Question: Zip gives me the following output said below, how can i zip when i dont know how many elements are there in the array,in this case i know 3 elements a[0],a[1],a[2] but how can i zip a[n] elements >>> zip(a[0],a[1],a[2]) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] question answers: >>> import numpy as np >>> first_answer = np.transpose(a) >>> second_answer = [list(i) for i in zip(*a)]

Multi-Dimensional Arrays or Matrices  a simple two-dimensional tabular summary. When rolling two dice, there are 36 possible outcomes a multi-dimensional table can be implemented as a sequence of sequences. A table is a sequence of rows. Each row is a sequence of individual cells. This allows us to use mathematical-like notation. Where the mathematician might say Ai,j , in Python we can say A[i][j]. In Python, we want the row i from table A, and column j from that row. http://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch20s05.html Let's look at a simple two-dimensional tabular summary. When rolling two dice, there are 36 possible outcomes. We can tabulate these in a two-dimensional table with one die in the rows and one die in the columns:

List of lists example build a table using a nested list comprehension. The following example creates a table as a sequence of sequences and then fills in each cell of the table. This program did two things. It created a six by six table of zeroes. It then filled this with each possible combination of two dice. This is not the most efficient way to do this, but we want to illustrate several techniques with a simple example. We'll look at each half in detail. The first part of this program creates and prints a 6-item list, named table; each item in the table is a 6-item list of zeroes. It uses a list comprehension to create an object for each value of j in the range of 0 to 6. Each of the objects is a list of zeroes, one for each value of i in the range of 0 to 6. After this initialization, the two-dimensional table of zeroes is printed. The comprehension can be read from inner to outer, like an ordinary expression. The inner list, [ 0 for i in range(6) ], creates a simple list of six zeroes. The outer list, [ [...] for j in range(6) ] creates six copies of these inner lists. The second part of this program then iterates over all combinations of two dice, filling in each cell of the table. This is done as two nested loops, one loop for each of the two dice. The outer enumerates all values of one die, d1. The loop enumerates all values of a second die, d2. Updating each cell involves selecting the row with table[d1]; this is a list of 6 values. The specific cell in this list is selected by ...[d2]. We set this cell to the number rolled on the dice, d1+d2+2.

Explicit Index Values use a simple list with 13 buckets (numbered from 0 to 12) for the frequency of each die roll fq= 13*[0] for i in range(6): for j in range(6): c= table[i][j] fq[ c ] += 1 We initialize the frequency table, fq, to be a list of 13 zeroes. The outer loop sets the variable i to the values from 0 to 5. The inner loop sets the variable j to the values from 0 to 5. We use the index value of i to select a row from the table, and the index value of j to select a column from that row. This is the value, c. We then accumulate the frequency occurances in the frequency table, fq. This looks very mathematical and formal. However, Python gives us an alternative, which can be somewhat simpler.

Using List Iterators Instead of Index Values Since our table is a list of lists, we can make use of the power of the for statement to step through the elements without using an index. fq= 13*[0] print fq for row in table: for c in row: fq[c] += 1 print fq[2:] We initialize the frequency table, fq, to be a list of 13 zeroes. The outer loop sets the variable row to each element of the original table variable. This decomposes the table into individual rows, each of which is a 6-element list. The inner loop sets the variable c to each column's value within the row. This decomposes the row into the individual values. We count the actual occurances of each value, c by using the value as an index into the frequency table, fq. The increment the frequency value by 1.

Mathematical Matrices We use the explicit index technique for managing the mathematically-defined matrix operations. Matrix operations are done more clearly with this style of explicit index operations. We'll show matrix addition as an example created two input matrices, m1 and m2, each three by four. We initialized a third matrix, m3, to three rows of four zeroes, using a comprehension. Then we iterated through all rows (using the i variable), and all columns (using the j variable) and computed the sum of m1 and m2.

Transpose a Matrix Implement a matrix as nested list (list inside a list). Treat each element as a row of the matrix. For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First row can be selected as X[0] and the element in first row, first column can be selected as X[0][0]. http://www.programiz.com/python-programming/examples/transpose-matrix

Matrix Transpose using Nested Loop In this program we have used nested for loops to iterate through each row and each column. At each point we place the X[i][j] element into result[j][i].

Matrix Transpose using Nested List Comprehension

Multiply Two Matrices Implement a matrix as nested list (list inside a list). Treat each element as a row of the matrix. For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First row can be selected as X[0] and the element in first row, first column can be selected as X[0][0]. http://www.programiz.com/python-programming/examples/multiply-matrix

Matrix Multiplication using Nested Loop Use nested for loops to iterate through each row and each column. Accumulate the sum of products in the result. This technique is simple but computationally expensive as we increase the order of matrix. For larger matrix operations recommend optimized software packages like NumPy which is several (in the order of 1000) times faster than the above code.

Using Modules A Python module extends the Python execution environment by adding new classes, functions and helpful constants. Tell the Python interpreter to fetch a module with a variation on the import statement. There are several variations on import , For now, we'll use the simple import : import m This will import module m. Only the module's name, m is made available. Every name inside the module m must be qualified by prepending the module name and a .. So if module m had a function called spam, we'd refer to it as m.spam. http://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch05.html

Matrix Multiplication using Nested List Comprehension zip(*Y)是把Y转置 zip(*Y)的意思是:zip(Y[0], Y[1], Y[2]) 然后把这三个数组zip起来,就变成了Y的转置形式了~ To understand the above code we must first know about built-in function zip() and unpacking argument list using * operator. Use nested list comprehension to iterate through each element in the matrix. The code looks complicated and unreadable at first. But once you get the hang of list comprehensions, you will probably not go back to nested loops.

zip() in conjunction with the * operator can be used to unzip a list: https://docs.python.org/3/library/functions.html?#zip

Unpacking Argument Lists The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple: https://docs.python.org/3/tutorial/controlflow.html#tut-unpacking-arguments http://openbookproject.net/thinkcs/python/english3e/lists.html http://wiki.ubuntu.org.cn/index.php?title=Python_%E5%AE%98%E6%96%B9%E7%AE%80%E6%98%8E%E6%95%99%E7%A8%8B_4&variant=zh-cn

http://stackoverflow.com/questions/19777612/python-range-and-zip-object-type zip(*Y)是把Y转置 They used to behave as the left display in python 2.x, but they were changed to generator-like objects which produce the elements on demand rather than expand an entire list into memory. One advantage was greater efficiency in their typical use-cases (e.g. iterating over them).