id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
6,200 | if it violates the constraint we stop--the bst property has been violated otherwisewe add its children along with the corresponding constraint for the example in figure on page we initialize the queue with ( [-]each time we pop nodewe first check the constraint we pop the first entry( [-])and add its childrenwith the corresponding constraintsi ( [- ]and ( [ ]next we pop ( [- ])and add its childreni ( [- ]and ( [ ]continuing through the nodeswe check that all nodes satisfy their constraintsand thus verify the tree is bst if the bst property is violated in subtree consisting of nodes within particular depththe violation will be discovered without visiting any nodes at greater depth this is because each time we enqueue an entrythe lower and upper bounds on the node' key are the tightest possible def is_binary_tree_bst (tree)queueentry collections namedtuple ('queueentry '('node ''lower ''upper ')bfs_queue collections deque queueentry (tree float ('-inf ')float('inf '))]while bfs_queue front bfs_queue popleft (if front nodeif not front lower <front node data <front upper return false bfs_queue +queueentry front node left front lower front node data)queueentry front node right front node data front upper return true the time complexity is ( )and the additional space complexity is ( |
6,201 | recursion the power of recursion evidently lies in the possibility of defining an infinite set of objects by finite statement in the same manneran infinite number of computations can be described by finite recursive programeven if this program contains no explicit repetitions -"algorithms data structures programs, wirth recursion is an approach to problem solving where the solution depends partially on solutions to smaller instances of related problems it is often appropriate when the input is expressed using recursive rulessuch as computer grammar more generallysearchingenumerationdivideand-conquerand decomposing complex problem into set of similar smaller instances are all scenarios where recursion may be suitable recursive function consists of base cases and calls to the same function with different arguments two key ingredients to successful use of recursion are identifying the base caseswhich are to be solved directlyand ensuring progressthat is the recursion converges to the solution both backtracking and branch-and-bound are naturally formulated using recursion recursion boot camp the euclidean algorithm for calculating the greatest common divisor (gcdof two numbers is classic example of recursion the central idea is that if xthe gcd of and is the gcd of and for examplegcd( gcd(( by extensionthis implies that the gcd of and is the gcd of and mod xi gcd( gcd(( mod gcd( mod def gcd(xy)return if = else gcd(yx ysince with each recursive step one of the arguments is at least halvedit means that the time complexity is (log max(xy)put another waythe time complexity is ( )where is the number of bits needed to represent the inputs the space complexity is also ( )which is the maximum depth of the function call stack (the program is easily converted to one which loopsthereby reducing the space complexity to ( now we describe problem that can be elegantly solved using recursive divide-and-conquer algorithm triomino is formed by joining three unit-sized squares in an -shape mutilated chessboard (henceforth mboardis made up of unit-sized squares arranged in an squareminus the top-left squareas depicted in figure (aon the next page suppose you are asked to design an algorithm that computes placement of triominoes that covers the |
6,202 | cannot have overlapping triominoes or triominoes which extend out of the mboard (aan mboard (bfour mboards figure mutilated chessboards divide-and-conquer is good strategy for this problem instead of the mboardlet' consider an mboard mboard can be covered with one triomino since it is of the same exact shape you may hypothesize that triomino placement for an mboard with the top-left square missing can be used to compute placement for an ( ( mboard howeveryou will quickly see that this line of reasoning does not lead you anywhere another hypothesis is that if placement exists for an mboardthen one also exists for mboard now we can apply divide-and-conquer take four mboards and arrange them to form square in such way that three of the mboards have their missing square set towards the center and one mboard has its missing square outward to coincide with the missing corner of mboardas shown in figure (bthe gap in the center can be covered with triomino andby hypothesiswe can cover the four mboards with triominoes as well hencea placement exists for any that is power of in particulara placement exists for the mboardthe recursion used in the proof directly yields the placement generate the power set the power set of set is the set of all subsets of sincluding both the empty set and itself the power set of { is graphically illustrated in figure on the next page write function that takes as input set and returns its power set hintthere are subsets for given set of size there are -bit words solutiona brute-force way is to compute all subsets that do not include particular element (which could be any single elementthen we compute all subsets which do include that element each subset set must appear in or in vso the final result is just uv the construction is recursiveand the base case is when the input set is emptyin which case we return {{} |
6,203 | computer grammar recursion is good choice for searchenumerationand divide-and-conquer use recursion as alternative to deeply nested iteration loops for examplerecursion is much better when you have an undefined number of levelssuch as the ip address problem generalized to substrings if you are asked to remove recursion from programconsider mimicking call stack with the stack data structure recursion can be easily removed from tail-recursive program by using while-loop--no stack is needed (optimizing compilers do this if recursive function may end up being called with the same arguments more than oncecache the results--this is the idea behind dynamic programming (table top tips for recursion { { { { { { { figure the power set of { is {{ }{ }{ }{ }{ }{ }{ }as an examplelet { pick any elemente firstwe recursively compute all subsets of { to do thiswe select this leaves us with { now we pick and get to base case so the set of subsets of { is {union with { } {{}{ }the set of subsets of { then is {{}{ }union with {{ }{ }} {{}{ }{ }{ }the set of subsets of { then is {{}{ }{ }{ }union with {{ }{ }{ }{ }} {{}{ }{ }{ }{ }{ }{ }{ }}def generate_power_set input_set )generate all subsets whose intersection with input_set [ input_set to_be_selected is exactly selected_so_far def directed_power_set to_be_selected selected_so_far )if to_be_selected =leninput_set )power_set append (listselected_so_far )return directed_power_set to_be_selected selected_so_far generate all subsets that contain input_set to_be_selected directed_power_set to_be_selected |
6,204 | power_set [directed_power_set ( []return power_set the number of recursive callsc(nsatisfies the recurrence ( ( )which solves to (no( since we spend (ntime within callthe time complexity is ( the space complexity is ( )since there are subsetsand the average subset size is / if we just want to print the subsetsrather than returning all of themwe simply perform print instead of adding the subset to the resultwhich reduces the space complexity to ( )--the time complexity remains the same for given ordering of the elements of sthere exists one-to-one correspondence between the bit arrays of length and the set of all subsets of --the in the -length bit array indicate the elements of in the subset corresponding to for exampleif {abcd}the bit array denotes the subset {acdthis observation can be used to derive nonrecursive algorithm for enumerating subsets in particularwhen is less than or equal to the width of an integer on the architecture (or languagewe are working onwe can enumerate bit arrays by enumerating integers in [ and examining the indices of bits set in these integers these indices are determined by first isolating the lowest set bit by computing &~( )and then getting the index by computing log def generate_power_set ( )power_set [for int_for_subset in range ( <len( ))bit_array int_for_subset subset [while bit_array subset append (int(math log bit_array ~bit_array )))bit_array &bit_array power_set append subset return power_set since each set takes (ntime to computethe time complexity is ( in practicethis approach is very fast furthermoreits space complexity is (nwhen we want to just enumerate subsetse to print themrather that to return all the subsets variantsolve this problem when the input array may have duplicatesi denotes multiset you should not repeat any multiset for exampleif id then you should return hih ih ih , ih ih ih , ih ih ih |
6,205 | dynamic programming the important fact to observe is that we have attempted to solve maximization problem involving particular value of and particular value of by first solving the general problem involving an arbitrary value of and an arbitrary value of -"dynamic programming, bellman dp is general technique for solving optimizationsearchand counting problems that can be decomposed into subproblems you should consider using dp whenever you have to make choices to arrive at the solutionspecificallywhen the solution relates to subproblems like divide-and-conquerdp solves the problem by combining the solutions of multiple smaller problemsbut what makes dp different is that the same subproblem may reoccur thereforea key to making dp efficient is caching the results of intermediate computations problems whose solutions use dp are popular choice for hard interview questions to illustrate the idea underlying dpconsider the problem of computing fibonacci numbers the first two fibonacci numbers are and successive numbers are the sums of the two previous numbers the first few fibonacci numbers are the fibonacci numbers arise in many diverse applications--biologydata structure analysisand parallel computing are some examples mathematicallythe nth fibonacci number (nis given by the equation (nf( ( )with ( and ( function to compute (nthat recursively invokes itself has time complexity that is exponential in this is because the recursive function computes some ( ) repeatedly figure on the following page graphically illustrates how the function is repeatedly called with the same arguments caching intermediate results makes the time complexity for computing the nth fibonacci number linear in nalbeit at the expense of (nstorage def fibonacci (ncache ={})if < return elif not in cache cache [nfibonacci ( fibonacci ( return cache [nminimizing cache space is recurring theme in dp now we show program that computes (nin (ntime and ( space conceptuallyin contrast to the above programthis program iteratively fills in the cache in bottom-up fashionwhich allows it to reuse cache storage to reduce the space complexity of the cache def fibonacci ( ) |
6,206 | ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) figure tree of recursive calls when naively computing the th fibonacci numberf( each node is callf(xindicates call with argument xand the italicized numbers on the right are the sequence in which calls take place the children of node are the subcalls made by that call note how there are calls to ( )and calls to each of ( ) ( )and ( if < return f_minus_ f_minus_ for in range ( ) f_minus_ f_minus_ f_minus_ f_minus_ f_minus_ return f_minus_ the key to solving dp problem efficiently is finding way to break the problem into subproblems such that the original problem can be solved relatively easily once solutions to the subproblems are availableand these subproblem solutions are cached usuallybut not alwaysthe subproblems are easy to identify here is more sophisticated application of dp consider the following problemfind the maximum sum over all subarrays of given array of integer as concrete examplethe maximum subarray for the array in figure starts at index and ends at index - - - - [ [ [ [ [ [ [ [ [ figure an array with maximum subarray sum of the brute-force algorithmwhich computes each subarray sumhas ( time complexity- ( + there are subarraysand each subarray sum takes (ntime to compute the brute-force algorithm can be improved to ( )at the cost of (nadditional storageby first computing [ka[ kfor all the sum for [ijis then sjs[ ]where [- is taken to be here is natural divide-and-conquer algorithm take to be the middle index of solve the problem for the subarrays [ mand [ in addition to the answers for eachwe also return the maximum subarray sum for subarray ending at the last entry in land the maximum subarray sum for subarray starting at the first entry of the maximum subarray |
6,207 | analysis is similar to that for quicksortand the time complexity is ( log nbecause of off-by-one errorsit takes some time to get the program just right now we will solve this problem by using dp natural thought is to assume we have the solution for the subarray [ howevereven if we knew the largest sum subarray for subarray [ ]it does not help us solve the problem for [ instead we need to know the subarray amongst all subarrays [ ] with the smallest subarray sum the desired value is [ minus this subarray' sum we compute this value by iterating through the array for each index jthe maximum subarray sum ending at is equal to [jmink< [kduring the iterationwe track the minimum [kwe have seen so far and compute the maximum subarray sum for each index the time spent per index is constantleading to an (ntime and ( space solution it is legal for all array entries to be negativeor the array to be empty the algorithm handles these input cases correctly def find_maximum_subarray ( )min_sum max_sum for running_sum in itertools accumulate ( )min_sum min(min_sum running_sum max_sum max(max_sum running_sum min_sum return max_sum dynamic programming boot camp the programs presented in the introduction for computing the fibonacci numbers and the maximum subarray sum are good illustrations of dp count the number of ways to traverse array in this problem you are to count the number of ways of starting at the top-left corner of array and getting to the bottom-right corner all moves must either go right or down for examplewe show three ways in array in figure (as we will seethere are total of possible ways for this example figure paths through array write program that counts how many ways you can go from the top-left to the bottom-right in array hintif and you can get to (ijfrom ( jor |
6,208 | dp is applicable when you can construct solution to the given instance from solutions to subinstances of smaller problems of the same kind in addition to optimization problemsdp is also applicable to counting and decision problems--any problem where you can express solution recursively in terms of the same computation on smaller instances although conceptually dp involves recursionoften for efficiency the cache is built "bottomup" iteratively when dp is implemented recursively the cache is typically dynamic data structure such as hash table or bstwhen it is implemented iteratively the cache is usually oneor multi-dimensional array to save spacecache space may be recycled once it is known that set of entries will not be looked up again common mistake in solving dp problems is trying to think of the recursive case by splitting the problem into two equal halvesa la quicksorti solve the subproblems for subarrays [ cand [ nand combine the results howeverin most casesthese two subproblems are not sufficient to solve the original problem dp is based on combining solutions to subproblems to yield solution to the original problem howeverfor some problems dp will not work for exampleif you need to compute the longest path from city to city without repeating an intermediate cityand this longest path passes through city then the subpaths from city to city and city to city may not be individually longest paths without repeated cities table top tips for dynamic programming solutiona brute-force approach is to enumerate all possible paths this can be done using recursion howeverthere is combinatorial explosion in the number of pathswhich leads to huge time complexity the problem statement asks for the number of pathsso we focus our attention on that key observation is that because paths must advance down or rightthe number of ways to get to the bottom-right entry is the number of ways to get to the entry immediately above itplus the number of ways to get to the entry immediately to its left let' treat the origin ( as the top-left entry generalizingthe number of ways to get to (ijis the number of ways to get to ( jplus the number of ways to get to (ij (if or there is only one way to get to (ijfrom the origin this is the basis for recursive algorithm to count the number of paths implemented naivelythe algorithm has exponential time complexity--it repeatedly recurses on the same locations the solution is to cache results for examplethe number of ways to get to (ijfor the configuration in figure on the previous page is cached in matrix as shown in figure on the facing page def number_of_ways (nm)def compute_number_of_ways_to_xy (xy)if = = return if number_of_ways [ ][ = |
6,209 | ways_left if = else compute_number_of_ways_to_xy (xy number_of_ways [ ][yways_top ways_left return number_of_ways [ ][ynumber_of_ways [[ for in range( )return compute_number_of_ways_to_xy ( the time complexity is (nm)and the space complexity is (nm)where is the number of rows and is the number of columns figure the number of ways to get from ( to (ijfor <ij < more analytical way of solving this problem is to use the fact that each path from ( to ( is sequence of horizontal steps and vertical steps there are + - - ( + - ) + - ( - )!( - )such paths - variantsolve the same problem using (min(nm)space variantsolve the same problem in the presence of obstaclesspecified by boolean arraywhere the presence of true value represents an obstacle varianta fisherman is in rectangular sea the value of the fish at point (ijin the sea is specified by an array write program that computes the maximum value of fish fisherman can catch on path from the upper leftmost point to the lower rightmost point the fisherman can only move down or rightas illustrated in figure figure alternate paths for fisherman different types of fish have different valueswhich are known to the fisherman variantsolve the same problem when the fisherman can begin and end at any point he must still move down or right (note that the value at (ijmay be negative |
6,210 | has to be of length or moreand the first element in the sequence cannot be call decimal number monotone if [ < [ ] < |dwrite program which takes as input positive integer and computes the number of decimal numbers of length that are monotone variantcall decimal number das defined abovestrictly monotone if [id[ ] < |dwrite program which takes as input positive integer and computes the number of decimal numbers of length that are strictly monotone |
6,211 | greedy algorithms and invariants the intended function of programor part of programcan be specified by making general assertions about the values which the relevant variables will take after execution of the program -"an axiomatic basis for computer programming, hoare sometimesthere are multiple greedy algorithms for given problemand only some of them are optimum for exampleconsider cities on linehalf of which are whiteand the other half are black suppose we need to pair white with black cities in one-to-one fashion so that the total length of the road sections required to connect paired cities is minimized multiple pairs of cities may share single section of roade if we have the pairing ( and ( then the section of road between cities and can be used by cities and the most straightforward greedy algorithm for this problem is to scan through the white citiesandfor each white citypair it with the closest unpaired black city this algorithm leads to suboptimum results consider the case where white cities are at and at and black cities are at and at if the white city at is processed firstit will be paired with the black city at forcing the cities at and to pair upleading to road length of in contrastthe pairing of cities at and and and leads to road length of slightly more sophisticated greedy algorithm does lead to optimum resultsiterate through all the cities in left-to-right orderpairing each city with the nearest unpaired city of opposite color note that the pairing for the first city must be optimumsince if it were to be paired with any other citywe could always change its pairing to be with the nearest black city without adding any road this observation can be used in an inductive proof of overall optimality greedy algorithms boot camp for us currencywherein coins take values centsthe greedy algorithm for making change results in the minimum number of coins here is an implementation of this algorithm note that once it selects the number of coins of particular valueit never changes that selectionthis is the hallmark of greedy algorithm def change_making cents )coins [ num_coins for coin in coins num_coins +cents coin cents %coin return num_coins we perform iterationsand each iteration does constant amount of computationso the time complexity is ( |
6,212 | set of choices to select from it' often easier to conceptualize greedy algorithm recursivelyand then implement it using iteration for higher performance even if the greedy approach does not yield an optimum solutionit can give insights into the optimum algorithmor serve as heuristic sometimes the correct greedy algorithm is not obvious table top tips for greedy algorithms invariants common approach to designing an efficient algorithm is to use invariants brieflyan invariant is condition that is true during execution of program this condition may be on the values of the variables of the programor on the control logic well-chosen invariant can be used to rule out potential solutions that are suboptimal or dominated by other solutions for examplebinary searchmaintains the invariant that the space of candidate solutions contains all possible solutions as the algorithm executes sorting algorithms nicely illustrate algorithm design using invariants intuitivelyselection sort is based on finding the smallest elementthe next smallest elementetc and moving them to their right place more preciselywe work with successively larger subarrays beginning at index and preserve the invariant that these subarrays are sortedtheir elements are less than or equal to the remaining elementsand the entire array remains permutation of the original array invariants boot camp suppose you were asked to write program that takes as input sorted array and given target value and determines if there are two entries in the array that add up to that value for exampleif the array is - ithen there are entries adding to and to but not to and the brute-force algorithm for this problem consists of pair of nested for loops its complexity is ( )where is the length of the input array faster approach is to add each element of the array to hash tableand test for each element if ewhere is the target valueis present in the hash table while reducing time complexity to ( )this approach requires (nadditional storage for the hash the most efficient approach uses invariantsmaintain subarray that is guaranteed to hold solutionif it exists this subarray is initialized to the entire arrayand iteratively shrunk from one side or the other the shrinking makes use of the sortedness of the array specificallyif the sum of the leftmost and the rightmost elements is less than the targetthen the leftmost element can never be combined with some element to obtain the target similar observation holds for the rightmost element def has_two_sum (at)ij len( while <jif [ia[ =treturn true elif [ia[jti + |
6,213 | - return false the time complexity is ( )where is the length of the array the space complexity is ( )since the subarray can be represented by two variables identifying the right invariant is an art the key strategy to determine whether to use an invariant when designing an algorithm is to work on small examples to hypothesize the invariant oftenthe invariant is subset of the set of input spacee ga subarray table top tips for invariants the -sum problem design an algorithm that takes as input an array and numberand determines if there are three entries in the array (not necessarily distinctwhich add up to the specified number for exampleif the array is then there are three entries in the array which add up to ( and (note that we can use twicesince the problem statement said we can use the same entry more than once howeverno three entries add up to hinthow would you check if given array entry can be added to two more entries to get the specified numbersolutionfirstwe consider the problem of computing pair of entries which sum to assume is sorted we start with the pair consisting of the first element and the last element( [ ] [ ]let [ [ if kwe are done if kwe increase the sum by moving to pair ( [ ] [ ]we need never consider [ ]since the array is sortedfor all ia[ [ < [ [ kwe can decrease the sum by considering the pair ( [ ] [ ])by analogous reasoningwe need never consider [ again we iteratively continue this process till we have found pair that sums up to or the indices meetin which case the search ends this solution works in (ntime and ( space in addition to the space needed to store now we describe solution to the problem of finding three entries which sum to we sort and for each [ ]search for indices and such that aja[kt [ithe additional space needed is ( )and the time complexity is the sum of the time taken to sorto( log )and then to run the (nalgorithm described in the previous paragraph times (one for each entry)which is ( overall the code for this approach is shown below def has_three_sum (at) sort (finds if the sum of two numbers in equals to return anyhas_two_sum (at afor in athe additional space needed is ( )and the time complexity is the sum of the time taken to sorto( log )and then to run the (nalgorithm to find pair in sorted array that sums to specified valuewhich is ( overall variantsolve the same problem when the three elements must be distinct for exampleif and then [ [ [ is not acceptablea[ [ [ is not acceptablebut [ [ [ and [ [ [ are acceptable |
6,214 | variantwrite program that takes as input an array of integers and an integer tand returns -tuple ( [ ] [ ] [ ]where pqr are all distinctminimizing | ( [pa[qa[ ])|and [ < [ < [svariantwrite program that takes as input an array of integers and an integer tand returns the number of -tuples (pqrsuch that [pa[qa[ < and [ < [ < [ |
6,215 | graphs concerning these bridgesit was asked whether anyone could arrange route in such way that he would cross each bridge once and only once -"the solution of problem relating to the geometry of position, euler informallya graph is set of vertices and connected by edges formallya directed graph is set of vertices and set of edges given an edge (uv)the vertex is its sourceand is its sink graphs are often decoratede by adding lengths to edgesweights to verticesa start vertexetc directed graph can be depicted pictorially as in figure path in directed graph from to vertex is sequence of vertices hv vn- where uvn- vand each (vi vi+ is an edge the sequence may consist of single vertex the length of the path hv vn- is intuitivelythe length of path is the number of edges it traverses if there exists path from to vv is said to be reachable from for examplethe sequence hacedhi is path in the graph represented in figure figure directed graph with weights on edges directed acyclic graph (dagis directed graph in which there are no cyclesi paths which contain one or more edges and which begin and end at the same vertex see figure on the following page for an example of directed acyclic graph vertices in dag which have no incoming edges are referred to as sourcesvertices which have no outgoing edges are referred to as sinks topological ordering of the vertices in dag is an ordering of the vertices in which each edge is from vertex earlier in the ordering to vertex later in the ordering an undirected graph is also tuple (ve)howevere is set of unordered pairs of vertices graphicallythis is captured by drawing arrowless connections between verticesas in figure |
6,216 | figure directed acyclic graph vertices agm are sources and vertices lfhn are sinks the ordering habcedghkijflmni is topological ordering of the vertices figure an undirected graph if is an undirected graphvertices and are said to be connected if contains path from to votherwiseu and are said to be disconnected graph is said to be connected if every pair of vertices in the graph is connected connected component is maximal set of vertices such that each pair of vertices in is connected in every vertex belongs to exactly one connected component for examplethe graph in figure is connectedand it has single connected component if edge (hiis removedit remains connected if additionally fiis removedit becomes disconnected and there are two connected components directed graph is called weakly connected if replacing all of its directed edges with undirected edges produces an undirected graph that is connected it is connected if it contains directed path from to or directed path from to for every pair of vertices and it is strongly connected if it contains directed path from to and directed path from to for every pair of vertices and graphs naturally arise when modeling geometric problemssuch as determining connected cities howeverthey are more generaland can be used to model many kinds of relationships graph can be implemented in two ways--using adjacency lists or an adjacency matrix in the adjacency list representationeach vertex vhas list of vertices to which it has an edge the adjacency matrix representation uses |vx |vboolean-valued matrix indexed by verticeswith indicating the presence of an edge the time and space complexities of graph algorithm are usually expressed as function of the number of vertices and edges tree (sometimes called free treeis special sort of graph--it is an undirected graph that is |
6,217 | only if there exists unique path between every pair of vertices there are number of variants on the basic idea of tree rooted tree is one where designated vertex is called the rootwhich leads to parent-child relationship on the nodes an ordered tree is rooted tree in which each vertex has an ordering on its children binary treeswhich are the subject of differ from ordered trees since node may have only one child in binary treebut that node may be left or right childwhereas in an ordered tree no analogous notion exists for node with single child specificallyin binary treethere is position as well as order associated with the children of nodes as an examplethe graph in figure is tree note that its edge set is subset of the edge set of the undirected graph in figure on the facing page given graph (ve)if the graph (ve where eis treethen is referred to as spanning tree of figure tree graphs boot camp graphs are ideal for modeling and analyzing relationships between pairs of objects for examplesuppose you were given list of the outcomes of matches between pairs of teamswith each outcome being win or loss natural question is as followsgiven teams and bis there sequence of teams starting with and ending with such that each team in the sequence has beaten the next team in the sequencea slick way of solving this problem is to model the problem using graph teams are verticesand an edge from one team to another indicates that the team corresponding to the source vertex has beaten the team corresponding to the destination vertex now we can apply graph reachability to perform the check both dfs and bfs are reasonable approaches--the program below uses dfs matchresult collections namedtuple ('matchresult '('winning_team ''losing_team ')def can_team_a_beat_team_b (matches team_a team_b )def build_graph ()graph collections defaultdict (setfor match in matches graph match winning_team addmatch losing_team return graph def is_reachable_dfs (graph curr dest visited =set ())if curr =destreturn true elif curr in visited or curr not in graph return false visited add(curr |
6,218 | return is_reachable_dfs build_graph (team_a team_b the time complexity and space complexity are both ( )where is the number of outcomes it' natural to use graph when the problem involves spatially connected objectse road segments between cities more generallyconsider using graph when you need to analyze any binary relationshipbetween objectssuch as interlinked webpagesfollowers in social graphetc in such casesquite often the problem can be reduced to well-known graph problem some graph problems entail analyzing structuree looking for cycles or connected components dfs works particularly well for these applications some graph problems are related to optimizatione find the shortest path from one vertex to another bfsdijkstra' shortest path algorithmand minimum spanning tree are examples of graph algorithms appropriate for optimization problems table top tips for graphs graph search computing vertices which are reachable from other vertices is fundamental operation which can be performed in one of two idiomatic waysnamely depth-first search (dfsand breadth-first search (bfsboth have linear time complexity-- (| | |to be precise in the worst-case there is path from the initial vertex covering all vertices without any repeatsand the dfs edges selected correspond to this pathso the space complexity of dfs is (| |(this space is implicitly allocated on the function call stackthe space complexity of bfs is also (| |)since in worst-case there is an edge from the initial vertex to all remaining verticesimplying that they will all be in the bfs queue simultaneously at some point dfs and bfs differ from each other in terms of the additional information they providee bfs can be used to compute distances from the start vertex and dfs can be used to check for the presence of cycles key notions in dfs include the concept of discovery time and finishing time for vertices paint boolean matrix let be boolean array encoding black-and-white image the entry (abcan be viewed as encoding the color at entry (abcall two entries adjacent if one is to the leftrightabove or below the other note that the definition implies that an entry can be adjacent to at most four other entriesand that adjacency is symmetrici if is adjacent to entry then is adjacent to define path from entry to entry to be sequence of adjacent entriesstarting at ending at with successive entries being adjacent define the region associated with point (ijto be all points ( such that there exists path from (ijto ( in which all entries are the same color in particular this implies (ijand ( must be the same color implement routine that takes an boolean array together with an entry (xyand flips the color of the region associated with (xysee figure for an example of flipping |
6,219 | ( (cfigure the color of all squares associated with the first square marked with in (ahave been recolored to yield the coloring in (bthe same process yields the coloring in (chintsolve this conceptuallythen think about implementation optimizations solution |
6,220 | parallel computing the activity of computer must include the proper reacting to possibly great variety of messages that can be sent to it at unpredictable momentsa situation which occurs in all information systems in which number of computers are coupled to each other -"cooperating sequential processes, dijkstra parallel computation has become increasingly common for examplelaptops and desktops come with multiple processors which communicate through shared memory high-end computation is often done using clusters consisting of individual computers communicating through network parallelism provides number of benefitshigh performance--more processors working on task (usuallymeans it is completed faster better use of resources-- program can execute while another waits on the disk or network fairness--letting different users or programs share machine rather than have one program run at time to completion convenience--it is often conceptually more straightforward to do task using set of concurrent programs for the subtasks rather than have single program manage all the subtasks fault tolerance--if machine fails in cluster that is serving web pagesthe others can take over concrete applications of parallel computing include graphical user interfaces (gui( dedicated thread handles ui actions while other threads arefor examplebusy doing network communication and passing results to the ui threadresulting in increased responsiveness)java virtual machines ( separate thread handles garbage collection which would otherwise lead to blockingwhile another thread is busy running the user code)web servers ( single logical thread handles single client request)scientific computing ( large matrix multiplication can be split across cluster)and web search (multiple machines crawlindexand retrieve web pagesthe two primary models for parallel computation are the shared memory modelin which each processor can access any location in memoryand the distributed memory modelin which processor must explicitly send message to another processor to access its memory the former is more appropriate in the multicore setting and the latter is more accurate for cluster the questions in this are focused on the shared memory model writing correct parallel programs is challenging because of the subtle interactions between parallel components one of the key challenges is races--two concurrent instruction sequences access the same address in memory and at least one of them writes to that address other challenges to correctness are starvation ( processor needs resource but never gets it)deadlock (thread acquires lock and thread acquires lock following which tries to acquire and tries to acquire )and |
6,221 | bugs caused by these issues are difficult to find using testing debugging them is also difficult because they may not be reproducible since they are usually load dependent it is also often true that it is not possible to realize the performance implied by parallelism--sometimes critical task cannot be parallelizedmaking it impossible to improve performanceregardless of the number of processors added similarlythe overhead of communicating intermediate results between processors can exceed the performance benefits parallel computing boot camp semaphore is very powerful synchronization construct conceptuallya semaphore maintains set of permits thread calling acquire(on semaphore waitsif necessaryuntil permit is availableand then takes it thread calling release(on semaphore adds permit and notifies threads waiting on that semaphorepotentially releasing blocking acquirer import threading class semaphore ()def __init__ (self max_available )self cv threading condition (self max_available max_available self taken def acquire (self)self cv acquire (while (self taken =self max_available )self cv wait (self taken + self cv release (def release (self)self cv acquire (self taken - self cv notify (self cv release (start with an algorithm that locks aggressively and is easily seen to be correct then add back concurrencywhile ensuring the critical parts are locked when analyzing parallel codeassume worst-case thread scheduler in particularit may choose to schedule the same thread repeatedlyit may alternate between two threadsit may starve threadetc try to work at higher level of abstraction in particularknow the concurrency libraries-don' implement your own semaphoresthread poolsdeferred executionetc (you should know how these features are implementedand implement them if asked to table top tips for concurrency |
6,222 | implement timer class consider web-based calendar in which the server hosting the calendar has to perform task when the next calendar event takes place (the task could be sending an email or short message service (smsyour job is to design facility that manages the execution of such tasks develop timer class that manages the execution of deferred tasks the timer constructor takes as its argument an object which includes run method and string-valued name field the class must support--( starting threadidentified by nameat given time in the futureand ( canceling threadidentified by name (the cancel request is to be ignored if the thread has already startedhintthere are two aspects--data structure design and concurrency solutionthe two aspects to the design are the data structures and the locking mechanism we use two data structures the first is min-heap in which we insert key-value pairsthe keys are run times and the values are the thread to run at that time dispatch thread runs these threadsit sleeps from call to call and may be woken up if thread is added to or deleted from the pool if woken upit advances or retards its remaining sleep time based on the top of the min-heap on waking upit looks for the thread at the top of the min-heap--if its launch time is the current timethe dispatch thread deletes it from the min-heap and executes it it then sleeps till the launch time for the next thread in the min-heap (because of deletionsit may happen that the dispatch thread wakes up and finds nothing to do the second data structure is hash table with thread ids as keys and entries in the min-heap as values if we need to cancel threadwe go to the min-heap and delete it each time thread is addedwe add it to the min-heapif the insertion is to the top of the min-heapwe interrupt the dispatch thread so that it can adjust its wake up time since the min-heap is shared by the update methods and the dispatch threadwe need to lock it the simplest solution is to have single lock that is used for all read and writes into the min-heap and the hash table |
6,223 | domain specific problems |
6,224 | design problems don' be fooled by the many books on complexity or by the many complex and arcane algorithms you find in this book or elsewhere although there are no textbooks on simplicitysimple systems work and complex don' -"transaction processingconcepts and techniques, gray you may be asked in an interview how to go about creating set of services or larger systempossibly on top of an algorithm that you have designed these problems are fairly open-endedand many can be the starting point for large software project in an interview setting when someone asks such questionyou should have conversation in which you demonstrate an ability to think creativelyunderstand design trade-offsand attack unfamiliar problems you should sketch key data structures and algorithmsas well as the technology stack (programming languagelibrariesoshardwareand servicesthat you would use to solve the problem the answers in this are presented in this context--they are meant to be examples of good responses in an interview and are not comprehensive state-of-the-art solutions we review patterns that are useful for designing systems in table some other things to keep in mind when designing system are implementation timeextensibilityscalabilitytestabilitysecurityinternationalizationand ip issues table system design patterns design principle key points algorithms and data structures identify the basic algorithms and data structures decomposition split the functionalityarchitectureand code into manageablereusable components scalability break the problem into subproblems that can be solved relatively independently on different machines shard data across machines to make it fit decouple the servers that handle writes from those that handle reads use replication across the read servers to gain more performance consider caching computation and later look it up to save work decomposition good decompositions are critical to successfully solving system-level design problems functionalityarchitectureand code all benefit from decomposition |
6,225 | goals into categories based on the stake holders we decompose the architecture itself into frontend and back-end the front-end is divided into user managementweb page designreporting functionalityetc the back-end is made up of middlewarestoragedatabasecron servicesand algorithms for ranking ads decomposing code is hallmark of object-oriented programming the subject of design patterns is concerned with finding good ways to achieve code-reuse broadly speakingdesign patterns are grouped into creationalstructuraland behavioral patterns many specific patterns are very natural--strategy objectsadaptersbuildersetc appear in number of places in our codebase freeman et al ' "head first design patternsisin our opinionthe right place to study design patterns scalability in the context of interview questions parallelism is useful when dealing with scalei when the problem is too large to fit on single machine or would take an unacceptably long time on single machine the key insight you need to display is that you know how to decompose the problem so that each subproblem can be solved relatively independentlyand the solution to the original problem can be efficiently constructed from solutions to the subproblems efficiency is typically measured in terms of central processing unit (cputimerandom access memory (ram)network bandwidthnumber of memory and database accessesetc consider the problem of sorting petascale integer array if we know the distribution of the numbersthe best approach would be to define equal-sized ranges of integers and send one range to one machine for sorting the sorted numbers would just need to be concatenated in the correct order if the distribution is not known then we can send equal-sized arbitrary subsets to each machine and then merge the sorted resultse using min-heap caching is great tool whenever computations are repeated for examplethe central idea behind dynamic programming is caching results from intermediate computations caching is also extremely useful when implementing service that is expected to respond to many requests over timeand many requests are repeated workloads on web services exhibit this property design system for detecting copyright infringement youtv com is successful online video sharing site hollywood studios complain that much of the material uploaded to the site violates copyright design feature that allows studio to enter set of videos that belong to itand to determine which videos in the youtv com database match videos in hintnormalize the video format and create signatures solutionvideos differ from documents in that the same content may be encoded in many different formatswith different resolutionsand levels of compression one way to reduce the duplicate video problem to the duplicate document problem is to reencode all videos to common formatresolutionand compression level this in itself does not |
6,226 | the resulting videos howeverwe can now "signaturethe normalized video trivial signature would be to assign or to each frame based on whether it has more or less brightness than average more sophisticated signature would be bit measure of the redgreenand blue intensities for each frame even more sophisticated signatures can be developede by taking into account the regions on individual frames the motivation for better signatures is to reduce the number of false matches returned by the systemand thereby reduce the amount of time needed to review the matches the solution proposed above is algorithmic howeverthere are alternative approaches that could be effectiveletting users flag videos that infringe copyright (and possibly rewarding them for their effort)checking for videos that are identical to videos that have previously been identified as infringinglooking at meta-information in the video headeretc variantdesign an online music identification service |
6,227 | language questions the limits of my language means the limits of my world - wittgenstein closure what does the following program printand whyincrement_by_i lambda xx for in range ( )printincrement_by_i [ ]( solutionthe program prints (= rather than the (= than might be expected this is because the the functions created in the loop have the same scope they use the same variable nameand consequentlyall refer to the same variableiwhich is at the end of the loophence the (= there are many ways to get the desired behavior reasonable approach is to return the lambda from functionthereby avoiding the naming conflict def create_increment_function ( )return lambda yy increment_by_i create_increment_function (ifor in range ( )printincrement_by_i [ ]( shallow and deep copy describe the differences between shallow copy and deep copy when is each appropriateand when is neither appropriatehow is deep copy implementedsolutionfirstwe note that assignment in python does not copy--it simply variable to target for objects that are mutableor contain mutable itemsa copy is needed if we want to change the copy without changing the original for exampleif [ and we assign to bi athen if we change be append( )then will also change there are two ways to make copyshallow and deep these are implemented in the copy modulespecifically as copy copy(xand copy deepcopy(xa shallow copy constructs new compound object and then (to the extent possibleinserts references into it to the objects found in |
6,228 | into it of the objects found in the original as concrete examplesuppose [[ ],[ ]and copy copy(athen if we update as [ ][ [ ][ also changes to howeverif copy deepcopy( )then the same update will leave unchanged the difference between shallow and deep copying is only relevant for compound objectsthat is objects that contain other objectssuch as lists or class instances if [ and copy copy( )then if we update as [ is unchanged diving under the hooddeep copy is more challenging to implement since recursive objects (compound objects thatdirectly or indirectlycontain reference to themselvesresult in infinite recursion in naive implementation of deep copy furthermoresince deep copy copies everythingit may copy too muche book-keeping data structures that should be shared even between copies the copy deepcopy(function avoids these problems by caching objects already copiedand letting user-defined classes override the copying operation in particulara class can override one or both of __copy__(and __deepcopy__(copying is defensive--it may avoided if it' known that the client will not mutate the object similarlyif the object is itself immutablee tuplethen there' no need to copy it |
6,229 | object-oriented design one thing expert designers know not to do is solve every problem from first principles -"design patternselements of reusable object-oriented software, gammar helmr johnsonand vlissides class is an encapsulation of data and methods that operate on that data classes match the way we think about computation they provide encapsulationwhich reduces the conceptual burden of writing codeand enable code reusethrough the use of inheritance and polymorphism howevernaive use of object-oriented constructs can result in code that is hard to maintain design pattern is general repeatable solution to commonly occurring problem it is not complete design that can be coded up directly--ratherit is description of how to solve problem that arises in many different situations in the context of object-oriented programmingdesign patterns address both reuse and maintainability in essencedesign patterns make some parts of system vary independently from the other parts adnan' design pattern course materialavailable freely onlinecontains lecture noteshomeworksand labs that may serve as good resource on the material in this creational patterns explain what each of these creational patterns isbuilderstatic factoryfactory methodand abstract factory solutionthe idea behind the builder pattern is to build complex object in phases it avoids mutability and inconsistent state by using an mutable inner class that has build method that returns the desired object its key benefits are that it breaks down the construction processand can give names to steps compared to constructorit deals far better with optional parameters and when the parameter list is very long static factory is function for construction of objects its key benefits are as followthe function' name can make what it' doing much clearer compared to call to constructor the function is not obliged to create new object--in particularit can return flyweight it can also return subtype that' more optimizede it can choose to construct an object that uses an integer in place of boolean array if the array size is not more than the integer word size factory method defines interface for creating an objectbut lets subclasses decide which class to instantiate the classic example is maze game with two modes--one with regular roomsand one with magic rooms from abc import abc abstractmethod |
6,230 | @abstractmethod def connect (self room )pass class mazegame (abc)@abstractmethod def make_room (self)print(abstract make_room "pass def addroom (self room)print(adding room"def __init__ (self)room self make_room (room self make_room (room connect room self addroom room self addroom room this snippet implements the regular rooms this snippet implements the magic rooms class magicmazegame mazegame )def make_room (self)return magicroom (class magicroom (room)def connect (self room )print(connecting magic room"here' how you use the factory to create regular and magic games ordinary_maze_game ordinary_maze_game ordinarymazegame (magic_maze_game magic_maze_game magicmazegame ( drawback of the factory method pattern is that it makes subclassing challenging an abstract factory provides an interface for creating families of related objects without specifying their concrete classes for examplea class documentcreator could provide interfaces to create number of productssuch as createletter(and createresume(concrete implementations of this class could choose to implement these products in different wayse with modern or classic fontsright-flush or right-ragged layoutetc client code gets documentcreator object and calls its factory methods use of this pattern makes it possible to interchange concrete implementations without changing the code that uses themeven at runtime the price for this flexibility is more planning and upfront codingas well as and code that may be harder to understandbecause of the added indirections |
6,231 | common tools unix is general-purposemulti-userinteractive operating system for the digital equipment corporation pdp- / and / computers it offers number of features seldom found even in larger operating systemsincluding( hierarchical file system incorporating demountable volumes( compatible filedeviceand inter-process / ( the ability to initiate asynchronous processes( system command language selectable on per-user basisand ( over subsystems including dozen languages -"the unix timesharing system, ritchie and thompson the problems in this are concerned with toolsversion control systemsscripting languagesbuild systemsdatabasesand the networking stack such problems are not commonly asked--expect them only if you are interviewing for specialized roleor if you claim specialized knowledgee network security or databases we emphasize these are vast subjectse networking is taught as sequence of courses in university curriculum our goal here is to give you flavor of what you might encounter adnan' advanced programming tools course materialavailable freely onlinecontains lecture noteshomeworksand labs that may serve as good resource on the material in this version control version control systems are cornerstone of software development--every developer should understand how to use them in an optimal way merging in version control system what is merging in version control systemspecificallydescribe the limitations of line-based merging and ways in which they can be overcome solutionmodern version control systems allow developers to work concurrently on personal copy of the entire codebase this allows software developers to work independently the price for this mergingperiodicallythe personal copies need to be integrated to create new shared version there is the possibility that parallel changes are conflictingand these must be resolved during the merge by farthe most common approach to merging is text-based text-based merge tools view software as text line-based merging is kind of text-based mergingspecifically one in which each line is treated as an indivisible unit the merging is "three-way"the lowest common ancestor in the revision history is used in conjunction with the two versions with line-based merging of text filescommon text lines can be detected in parallel modificationsas well as text lines that have been |
6,232 | line-based merge one issue with line-based merging is that it cannot handle two parallel modifications to the same linethe two modifications cannot be combinedonly one of the two modifications must be selected bigger issue is that line-based merge may succeedbut the resulting program is broken because of syntactic or semantic conflicts in the scenario in figure on the facing page the changes made by the two developers are made to independent linesso the line-based merge shows no conflicts howeverthe program will not compile because function is called incorrectly in spite of thisline-based merging is widely used because of its efficiencyscalability,and accuracy three-wayline-based merge tool in practice will merge of the changed files without any issues the challenge is to automate the remaining of the situations that cannot be merged automatically text-based merging fails because it does not consider any syntactic or semantic information syntactic merging takes the syntax of the programming language into account text-based merge often yields unimportant conflicts such as code comment that has been changed by different developers or conflicts caused by code reformatting syntactic merge can ignore all theseit displays merge conflict when the merged result is not syntactically correct we illustrate syntactic merging with small exampleif ( % = then / two developers change this code in different waysbut with the same overall effect the first updates it to if ( % = then / else ( - / and the second developer' update is / both changes to the same thing howevera textual-merge will likely result in : div else :( - / which is syntactically incorrect syntactic merge identifies the conflictit is the integrator' responsibility to manually resolve ite by removing the else portion syntactic merge tools are unable to detect some frequently occurring conflicts for examplein the merge of versions and in figure on the next page will not compilesince the call to sum( has the wrong signature syntactic merge will not detect this conflict since the program is still syntactically correct the conflict is semantic conflictspecificallya static semantic conflictsince it is detectable at compile-time (the compile will return something like "function argument mismatch errortechnicallysyntactic merge algorithms operate on the parse trees of the programs to be merged more powerful static semantic merge algorithms have been proposed that operate on graph representation of the programswherein definitions and usage are linkedmaking it easier to identify mismatched usage static semantic merging also has shortcomings for examplesuppose point is class representing -points using cartesian coordinatesand that this class has distance function that returns suppose alice checks out the projectand subclasses point to create class that supports polar coordinatesand uses points' distance function to return the radius concurrentlybob checks out the project and changes point' distance function to return | |ystatic semantic |
6,233 | behavior is not what was expected both syntactic merging and semantic merging greatly increase runtimesand are very limiting since they are tightly coupled to specific programming languages in practiceline-based merging is used in conjunction with small set of unit tests ( "smoke suite"invoked with pre-commit hook script compilation finds syntax and static semantics errorsand the tests (hopefullyidentify deeper semantic issues int sum(int nint total for (int ni++total total ireturn total}version int sum(int nif ( return int total for (int ni++total +ireturn total}int sum( )void sum(int nintresultint total for (int ni++total total *result total}version version void sum(int nintresultif ( return int total for (int ni++total total *result total}int sum( )merge of versions and figure an example of -way line based merge scripting languages scripting languagessuch as awkperland python were originally developed as tools for quick hacksrapid prototypingand gluing together other programs they have evolved into mainstream |
6,234 | text strings are the basic (sometimes onlydata type associative arrays are basic aggregate type regexps are usually built in programs are interpreted rather than compiled declarations are often not required they are easy to get started withand can often do great deal with very little code build systems program typically cannot be executed immediately after changeintermediate steps are required to build the program and test it before deploying it other components can also be affected by changessuch as documentation generated from program text build systems automate these steps database most software systems today interact with databasesand it' important for developers to have basic knowledge of databases networking most software systems today interact with the networkand it' important for developers even higher up the stack to have basic knowledge of networking here are networking questions you may encounter in an interview setting |
6,235 | the honors class |
6,236 | honors class the supply of problems in mathematics is inexhaustibleand as soon as one problem is solved numerous others come forth in its place -"mathematical problems, hilbert this contains problems that are more difficult to solve than the ones presented earlier many of them are commonly asked at interviewsalbeit with the expectation that the candidate will not deliver the best solution there are several reasons why we included these problemsalthough mastering these problems is not essential to your successif you do solve themyou will have put yourself into very strong positionsimilar to training for race with ankle weights if you are asked one of these questions or variant thereofand you successfully derive the best solutionyou will have strongly impressed your interviewer the implications of this go beyond being made an offer--your salarypositionand status will all go up some of the problems are appropriate for candidates interviewing for specialized positionse optimizing large scale distributed systemsmachine learning for computational financeetc they are also commonly asked of candidates with advanced degrees finallyif you love good challengethese problems will provide ityou should be happy if your interviewer asks you hard question--it implies high expectationsand is an opportunity to shinecomparedfor exampleto being asked to write program that tests if string is palindromic intractability coding problems asked in interviews almost always have one (or moresolutions that are faste (ntime complexity sometimesyou may be asked problem that is computationally intractable-there may not exist an efficient algorithm for it (such problems are common in the real world there are number of approaches to solving intractable problemsbrute-force solutionsincluding dynamic programmingwhich have exponential time complexitymay be acceptableif the instances encountered are smallor if the specific parameter that the complexity is exponential in is smallsearch algorithmssuch as backtrackingbranch-and-boundand hill-climbingwhich prune much of the complexity of brute-force search |
6,237 | heuristics based on insightcommon case analysisand careful tuning that may solve the problem reasonably wellparallel algorithmswherein large number of computers can work on subparts simultaneously compute the greatest common divisor the greatest common divisor (gcdof nonnegative integers and is the largest integer such that divides evenlyand divides evenlyi mod and mod (when both and are take their gcd to be design an efficient algorithm for computing the gcd of two nonnegative integers without using multiplicationdivision or the modulus operators hintuse case analysisboth evenboth oddone even and one odd solutionthe straightforward algorithm is based on recursion if ygcd(xyxotherwiseassume without loss of generalitythat then gcd(xyis the gcd( yythe recursive algorithm based on the above does not use multiplicationdivision or modulusbut for some inputs it is very slow as an exampleif the input is the algorithm makes - recursive calls the time complexity can be improved by observing that the repeated subtraction amounts to divisioni when ygcd(xygcd(yx mod )but this approach uses integer division which was explicitly disallowed in the problem statement here is fast solutionwhich is also based on recursionbut does not use general multiplication or division instead it uses case-analysisspecificallythe cases of onetwoor none of the numbers being even an example is illustrative suppose we were to compute the gcd of and instead of repeatedly subtracting from we can observe that since both are eventhe result is gcd( dividing by is right shift by so we do not need general division operation since and are both evengcd( gcd( since is oddthe gcd of and is the same as the gcd of and since cannot divide the gcd of and is the gcd of and repeatedly applying the same logicgcd( gcd( gcd( gcd( gcd( gcd( this implies gcd( more generallythe base case is when the two arguments are equalin which case the gcd is that valuee gcd( or one of the arguments is zeroin which case the other is the gcde gcd( otherwisewe check if noneoneor both numbers are even if both are evenwe compute the gcd of the halves of the original numbersand return that result times if exactly one is evenwe half itand return the gcd of the resulting pairif both are oddwe subtract the smaller from the larger and return the gcd of the resulting pair multiplication by is trivially implemented with single left shift division by is done with single right shift def gcd(xy)if yreturn gcd(yxelif = |
6,238 | elif not and not and are even return gcd( > > < elif not and is even is odd return gcd( > yelif and not is odd is even return gcd(xy > return gcd(xy xboth and are odd note that the last step leads to recursive call with one even and one odd number consequentlyin every two callswe reduce the combined bit length of the two numbers by at least onemeaning that the time complexity is proportional to the sum of the number of bits in and yi (log log ) compute the maximum product of all entries but one suppose you are given an array of integersand are asked to find the largest product that can be made by multiplying all but one of the entries in (you cannot use an entry more than once for exampleif ithe result is if - ithe result is and if - - ithe result is - - one approach is to form the product of all the elementsand then find the maximum of / [iover all this takes multiplications (to form pand divisions (to compute each / [ ]suppose because of finite precision considerations we cannot use division-based approachwe can only use multiplications the brute-force solution entails computing all products of elementseach such product takes multiplicationsi ( time complexity given an array of length whose entries are integerscompute the largest product that can be made using entries in you cannot use an entry more than once array entries may be positivenegativeor your algorithm cannot use the division operatorexplicitly or implicitly hintconsider the products of the first and the last elements alternativelycount the number of negative entries and zero entries solutionthe brute-force approach to compute / [iis to multiplying the entries appearing before with those that appear after this leads to ( multiplicationssince for each term / [iwe need multiplications note that there is substantial overlap in computation when computing / [iand / [ in particularthe product of the entries appearing before is [itimes the product of the entries appearing before we can compute all products of entries before with multiplicationsand all products of entries after with multiplicationsand store these values in an array of prefix productsand an array of suffix products the desired result then is the maximum prefix-suffix product slightly more space efficient approach is to build the suffix product array and then iterate forward through the arrayusing single variable to compute the prefix products this prefix product is multiplied with the corresponding suffix product and the maximum prefix-suffix product is updated if required def find_biggest_n_minus_one_product ( )builds suffix products suffix_products list |
6,239 | finds the biggest product of ( numbers prefix_product max_product float ('-inf 'for in range(len( ))suffix_product suffix_products [ if len(aelse max_product maxmax_product prefix_product suffix_product prefix_product * [ireturn max_product the time complexity is ( )the space complexity is ( )since the solution uses single array of length we now solve this problem in (ntime and ( additional storage the insight comes from the fact that if there are no negative entriesthe maximum product comes from using all but the smallest element (note that this result is correct if the number of entries is zerooneor more if the number of negative entries is oddregardless of how many entries and positive entriesthe maximum product uses all entries except for the negative entry with the smallest absolute valuei the least negative entry going furtherif the number of negative entries is eventhe maximum product again uses all but the smallest nonnegative elementassuming the number of nonnegative entries is greater than zero (this is correcteven in the presence of entries if the number of negative entries is evenand there are no nonnegative entriesthe result must be negative since we want the largest productwe leave out the entry whose magnitude is largesti the greatest negative entry this analysis yields two-stage algorithm firstdetermine the applicable scenarioe are there an even number of negative entriesconsequentlyperform the actual multiplication to get the result def find_biggest_n_minus_one_product ( )number_of_negatives least_nonnegative_idx least_negative_idx greatest_negative_idx none identify the least negative greatest negative and least nonnegative entries for ia in enumerate ( )if number_of_negatives + if least_negative_idx is none or aleast_negative_idx aleast_negative_idx if greatest_negative_idx is none or agreatest_negative_idx ]greatest_negative_idx elsea > if least_nonnegative_idx is none or aleast_nonnegative_idx ]least_nonnegative_idx idx_to_skip least_negative_idx if number_of_negatives else least_nonnegative_idx if least_nonnegative_idx is not none else greatest_negative_idx return functools reduce lambda product aproduct ause generator rather than list comprehension to avoid extra space |
6,240 | the algorithm performs traversal of the arraywith constant amount of computation per entrya nested conditionalfollowed by another traversal of the arraywith constant amount of computation per entry hencethe time complexity is (no( (no(nthe additional space complexity is ( )corresponding to the local variables variantlet be as above compute an array where [iis the product of all elements in except [iyou cannot use division your time complexity should be ( )and you can only use ( additional space variantlet be as above compute the maximum over the product of all triples of distinct elements of |
6,241 | notation and index |
6,242 | to speak about notation as the only way that you can guarantee structure of course is already very suspect - parker we use the following convention for symbolsunless the surrounding text specifies otherwisea -dimensional array linked list or doubly linked list set tree graph set of vertices of graph set of edges of graph symbolism meaning (dk- ) radix- representation of numbere ( ) logb logarithm of to the base bif is not specifiedb |scardinality of set \ set differencei sometimes written as |xabsolute value of bxc greatest integer less than or equal to dxe smallest integer greater than or equal to ha an- (kf (ksequence of elements sum of all (ksuch that relation (kis true minr(kf (kminimum of all (ksuch that relation (kis true maxr(kf (kpb = (kmaximum of all (ksuch that relation (kis true shorthand for <= <= ( { ( )set of all such that the relation (atrue [lrclosed interval{ < < [lrleft-closedright-open interval{ < {abwell-defined collection of elementsi set ai or [ithe ith element of one-dimensional array [ijsubarray of one-dimensional array consisting of elements at indices to inclusive [ ][jthe element in ith row and jth column of array |
6,243 | contents |
6,244 | introduction pyexcel provides one application programming interface to readmanipulate and write data in various excel formats this library makes information processing involving excel files an enjoyable task the data in excel files can be turned into array or dict with minimal code and vice versa this library focuses on data processing using excel files as storage media hence fontscolors and charts were not and will not be considered the idea originated from the common usability problemwhen an excel file driven web application is delivered for non-developer users (ieteam assistanthuman resource administrator etcthe fact is that not everyone knows (or caresabout the differences between various excel formatscsvxlsxlsx are all the same to them instead of training those users about file formatsthis library helps web developers to handle most of the excel file formats by providing common programming interface to add specific excel file format type to you applicationall you need is to install an extra pyexcel plugin hence no code changes to your application and no issues with excel file formats any more looking at the communitythis library and its associated ones try to become small and easy to install alternative to pandas |
6,245 | introduction |
6,246 | support the project if your company has embedded pyexcel and its components into revenue generating productplease support me on githubpatreon or bounty source to maintain the project and develop it further if you are an individualyou are welcome to support me too and for however long you feel like as my backeryou will receive early access to pyexcel related contents and your issues will get prioritized if you would like to become my patreon as pyexcel pro user with your financial supporti will be able to invest little bit more time in codingdocumentation and writing interesting posts installation you can install pyexcel via pippip install pyexcel or clone it and install itgit clone cd pyexcel python setup py install suppose you have the following data in dictionaryname adam beatrice ceri dean age you can easily save it into an excel file using the following code |
6,247 | import pyexcel make sure you had pyexcel-xls installed a_list_of_dictionaries "name"'adam'"age" }"name"'beatrice'"age" }"name"'ceri'"age" }"name"'dean'"age" pyexcel save_as(records=a_list_of_dictionariesdest_file_name="your_file xls"and here' how to obtain the recordsimport pyexcel as records iget_records(file_name="your_file xls"for record in recordsprint("% is aged at % (record['name']record['age'])adam is aged at beatrice is aged at ceri is aged at dean is aged at free_resources(custom data renderingpip install pyexcel-text= import pyexcel as ccs_insight sheet(ccs_insight name "worldwide mobile phone shipments (billions) - ccs_insight ndjson ""{"year"[" "" "" "" "" "]{"smart phones"[ ]{"feature phones"[ ]""strip(ccs_insight pyexcel sheet++++++year ++++++smart phones ++++++feature phones ++++++ support the project |
6,248 | advanced usage :fireif you are dealing with big dataplease consider these usagesdef increase_everyones_age(generator)for row in generatorrow['age'+ yield row def duplicate_each_record(generator)for row in generatoryield row yield row records iget_records(file_name="your_file xls"io= isave_as(records=duplicate_each_record(increase_everyones_age(records))dest_file_type='csv'dest_lineterminator='\ 'print(io getvalue()age,name ,adam ,adam ,beatrice ,beatrice ,ceri ,ceri ,dean ,dean two advantages of above method add as many wrapping functions as you want constant memory consumption for individual excel file formatsplease install them as you wishtable list of file formats supported by external plugins package name supported file formats dependencies pyexcel-io csvcsvz tsvtsvz pyexcel-xls xlsxlsx(read only)xlsm(read onlyxlrdxlwt pyexcel-xlsx xlsx openpyxl pyexcel-ods ods pyexcel-ezodflxml pyexcel-ods ods odfpy table dedicated file reader and writers package name supported file formats dependencies pyexcel-xlsxw xlsx(write onlyxlsxwriter pyexcel-libxlsxw xlsx(write onlylibxlsxwriter pyexcel-xlsxr xlsx(read onlylxml pyexcel-xlsbr xlsb(read onlypyxlsb pyexcel-odsr read only for odsfods lxml pyexcel-odsw write only for ods loxun pyexcel-htmlr html(read onlylxml,html lib pyexcel-pdfr pdf(read onlycamelot zipped csv file zipped tsv file advanced usage :fire |
6,249 | plugin shopping guide since all pyexcel-io plugins have dropped the support for python versions which are lower than if you want to use any of those python versionsplease use pyexcel-io and its plugins versions that are lower than except csv filesxlsxlsx and ods files are zip of folder containing lot of xml files the dedicated readers for excel files can stream read in order to manage the list of plugins installedyou need to use pip to add or remove plugin when you use virtualenvyou can have different plugins per virtual environment in the situation where you have multiple plugins that does the same thing in your environmentyou need to tell pyexcel which plugin to use per function call for examplepyexcel-ods and pyexcel-odsrand you want to get_array to use pyexcel-odsr you need to append get_arraylibrary='pyexcel-odsr'table other data renderers package name pyexcel-text pyexcelhandsontable pyexcelpygal pyexcelsortable pyexcel-gantt supported file formats write only:rstmediawikihtmllatexgridpipeorgtblplain simple read onlyndjson /wjson handsontable in html dependencies tabulate python versions pypy same as above svg chart handsontable pygal sortable table in html csvtotable pypy same as above gantt chart in html frappegantt except pypysame as above for compatibility tables of pyexcel-io pluginsplease click here pyexcel pyexcel-io table plugin compatibility table pyexcel-text pyexcel-handsontable pyexcel-pygal pyexcel-gantt support the project |
6,250 | table list of supported file formats file format csv tsv csvz tsvz xls xlsx xlsm ods fods json html simple rst mediawiki definition comma separated values tab separated values zip file that contains one or many csv files zip file that contains one or many tsv files spreadsheet file format created by ms-excel - ms-excel extensions to the office open xml spreadsheetml file format an ms-excel macro-enabled workbook file open document spreadsheet flat open document spreadsheet java script object notation html table of the data structure simple presentation rstructured text presentation of the data media wiki table usage suppose you want to process the following excel data here are the example usagesimport pyexcel as pe records pe iget_records(file_name="your_file xls"for record in recordsprint("% is aged at % (record['name']record['age'])adam is aged at beatrice is aged at ceri is aged at dean is aged at pe free_resources( design introduction this section introduces excel data modelsits representing data structures and provides an overview of formattingtransformationmanipulation supported by pyexcel data models and data structures when dealing with excel filespyexcel pay attention to three primary objectscellsheet and book book contains one or more sheets and sheet is consisted of sheet name and two dimensional array of cells although sheet can contain charts and cell can have formulastyling propertiesthis library ignores them and only pays attention to the data in the cell and its data type soin the context of this librarythe definition of those three concepts are usage |
6,251 | concept cell sheet book definition is data unit is named two dimensional array of data units is dictionary of two dimensional array of data units pyexcel data model python data type sheet book data source data source is storage format of structured data the most popular data source is an excel file libre office/microsoft excel can easily be used to generate an excel file of your desired format besides physical filethis library recognizes three additional types of source excel files in computer memory for examplewhen file is uploaded to python server for information processing if it is relatively smallit can be stored in memory database tables for examplea client would like to have snapshot of some database table in an excel file and asks it to be sent to him python structures for examplea developer may have scraped site and have stored data in python array or dictionary he may want to save this information as file reading from and writing to data source is modelled as parsers and renderers in pyexcel excel data sources and database sources support read and write other data sources may only support read onlyor write only methods here is list of data sourcesdata source array dictionary records excel files excel files in memory excel files on the web django models sql models database querysets textual sources read and write properties read and write same as above same as above same as above same as above read only read and write read and write read only write only data format this library and its plugins support most of the frequently used excel file formats support the project |
6,252 | file format csv tsv csvz tsvz xls xlsx xlsm ods json html simple rst mediawiki definition comma separated values tab separated values zip file that contains one or many csv files zip file that contains one or many tsv files spreadsheet file format created by ms-excel - ms-excel extensions to the office open xml spreadsheetml file format an ms-excel macro-enabled workbook file open document spreadsheet java script object notation html table of the data structure simple presentation rstructured text presentation of the data media wiki table see also list of file formats supported by external plugins data transformation often developer would like to have excel data imported into python data structure this library supports the conversions from previous three data source to the following list of data structuresand vice versa table list of supported data structures pesudo name python name two dimensional array list of lists dictionary of key value pair dictionary dictionary of one dimensional arrays dictionary of lists list of dictionaries list of dictionaries dictionary of two dimensional arrays dictionary of lists of lists related model pyexcel sheet pyexcel sheet pyexcel sheet pyexcel sheet pyexcel book data manipulation the main operation on cell involves cell accessformatting and cleansing the main operation on sheet involves group access to row or columndata filteringand data transformation the main operation in book is obtain access to individual sheets data transcoding for various reasons the data in one format needs to be transcoded into another this library provides transcoding tunnel for data transcoding between supported file formats data visualization via pyexcel renderer abstractrenderer interfacedata visualization is made possible pyexcel-chart is the interface plugin to formalize this effort pyexcel-pygal is the first plugin to provide barpiehistogram charts and more quoted from whatis com technical details can be found at msdn xls xlsx is used by ms-excel more information can be found at msdn xlsx design |
6,253 | examples of supported data structure here is list of examplesimport pyexcel as two_dimensional_list [ ][ ][ ] get_sheet(array=two_dimensional_listpyexcel_sheet +---+----+----+---- +---+----+----+---- +---+----+----+---- +---+----+----+----a_dictionary_of_key_value_pair "ie" "firefox" get_sheet(adict=a_dictionary_of_key_value_pairpyexcel_sheet ++firefox ie ++ ++a_dictionary_of_one_dimensional_arrays "column "[ ]"column "[ ]"column "[ ] get_sheet(adict=a_dictionary_of_one_dimensional_arrayspyexcel_sheet +++column column column +++ +++ +++ +++ +++a_list_of_dictionaries "name"'adam'"age" }"name"'beatrice'"age" }(continues on next page support the project |
6,254 | (continued from previous page"name"'ceri'"age" }"name"'dean'"age" get_sheet(records=a_list_of_dictionariespyexcel_sheet ++age name ++ adam ++ beatrice ++ ceri ++ dean ++a_dictionary_of_two_dimensional_arrays 'sheet '[ ][ ][ ]'sheet '[' '' '' '][ ][ ]'sheet '[' '' '' '][ ][ get_book(bookdict=a_dictionary_of_two_dimensional_arrayssheet +++ +++ +++ +++sheet +++ +++ +++ (continues on next page design |
6,255 | (continued from previous page+++sheet +++ +++ +++ +++signature functions import data into python this library provides one application programming interface to read data from one of the following data sourcesphysical file memory file sqlalchemy table django model python data structuresdictionaryrecords and array and to transform them into one of the following data structurestwo dimensional array dictionary of one dimensional arrays list of dictionaries dictionary of two dimensional arrays sheet book four data access functions python data can be handled well using listsdictionaries and various mixture of both this library provides four module level functions to help you obtain excel data in these data structures please refer to " list of module level functions"the first three functions operates on any one sheet from an excel book and the fourth one returns all data in all sheets in an excel book functions get_array(get_dict(get_records(get_book_dict(table list of module level functions name python name two dimensional array list of lists dictionary of one dimensional arrays an ordered dictionary of lists list of dictionaries list of dictionaries dictionary of two dimensional arrays dictionary of lists of lists see alsoget_an_array_from_an_excel_sheet support the project |
6,256 | how to get dictionary from an excel sheet how to obtain records from an excel sheet how to obtain dictionary from multiple sheet book the following two variants of the data access function use generator and should work well with big data files functions iget_array(iget_records(table list of variant functions name memory efficient two dimensional array memory efficient list list of dictionaries python name generator of list of lists generator of list of dictionaries howeveryou will need to call free_resource(to make sure file handles are closed two pyexcel functions in cases where the excel data needs custom manipulationsa pyexcel user got few choicesone is to use sheet and bookthe other is to look for more sophisticated onespandasfor numerical analysis do-it-yourself functions get_sheet(get_book(returns sheet book for all six functionsyou can pass on the same command parameters while the return value is what the function says export data from python this library provides one application programming interface to transform them into one of the data structurestwo dimensional array (ordereddictionary of one dimensional arrays list of dictionaries dictionary of two dimensional arrays sheet book and write to one of the following data sourcesphysical file memory file sqlalchemy table django model design |
6,257 | python data structuresdictionaryrecords and array here are the two functionsfunctions save_as(isave_as(save_book_as(isave_book_as(description works well with single sheet file works well with big data files works with multiple sheet file and big data files works with multiple sheet file and big data files if you would only use these two functions to do format transcodingyou may enjoy speed boost using isave_as(and isave_book_as()because they use yield keyword and minimize memory footprint howeveryou will need to call free_resource(to make sure file handles are closed and save_as(and save_book_as(reads all data into memory and will make all rows the same width see alsohow to save an python array as an excel file how to save dictionary of two dimensional array as an excel file how to save an python array as csv file with special delimiter data transportation/transcoding this library is capable of transporting your data between any of the following data sourcesphysical file memory file sqlalchemy table django model python data structuresdictionaryrecords and array see alsohow to import an excel sheet to database using sqlalchemy how to open an xls file and save it as xlsx how to open an xls file and save it as csv architecture pyexcel uses loosely couple plugins to fullfil the promise to access various file formats lml is the plugin management library that provide the specialized support for the loose coupling what is loose couplingthe components of pyexcel is designed as building blocks for your projectyou can cherry-pick the file format support without affecting the core functionality of pyexcel each plugin will bring in additional dependences for exampleif you choose pyexcel-xlsxlrd and xlwt will be brought in as nd level depndencies support the project |
6,258 | looking at the following architectural diagrampyexcel hosts plugin interfaces for data sourcedata renderer and data parser pyexcel-pygalpyexcel-matplotliband pyexcel-handsontable extend pyexcel using data renderer interface pyexcel-io package takes away the responsibilities to interface with excel librariesfor examplexlrdopenpyxlezodf as in list of file formats supported by external pluginsthere are overlapping capabilities in reading and writing xlsxods files because each third parties express different personalities although they may read and write data in the same file formatyou as the pyexcel is left to pick which suit your task best dotted arrow means the package or module is loaded later new tutorial one liners this section shows you how to get data from your excel files and how to export data to excel files in one line read from the excel files get list of dictionaries suppose you want to process history of classical musiclet' get list of dictionary out from the xls filerecords get_records(file_name="your_file xls"and let' check what do we havefor row in recordsprint( "{row['representative composers']are from {row['name']period ({row'-'period']})"machautlandini are from medieval period ( - gibbonsfrescobaldi are from renaissance period ( - js bachvivaldi are from baroque period ( - joseph haydnwolfgan amadeus mozart are from classical period ( - chopinmendelssohnschumannliszt are from early romantic period ( - wagner,verdi are from late romantic period ( - sergei rachmaninoff,calude debussy are from modernist period ( th centuryget two dimensional array insteadwhat if you have to use pyexcel get_array to do the samefor row in get_array(file_name="your_file xls"start_row= )print( "{row[ ]are from {row[ ]period ({row[ ]})"machautlandini are from medieval period ( - gibbonsfrescobaldi are from renaissance period ( - js bachvivaldi are from baroque period ( - joseph haydnwolfgan amadeus mozart are from classical period ( - chopinmendelssohnschumannliszt are from early romantic period ( - (continues on next page new tutorial |
6,259 | (continued from previous pagewagner,verdi are from late romantic period ( - sergei rachmaninoff,calude debussy are from modernist period ( th centurywhere start_row skips the header row get dictionary you can get dictionary toomy_dict get_dict(file_name="your_file xls"name_columns_by_row= and let' have look insidefrom pyexcel _compact import ordereddict isinstance(my_dictordereddicttrue for keyvalues in my_dict items()print(key ',join([str(itemfor item in values])name medieval,renaissance,baroque,classical,early romantic,late romantic,modernist period - , - , - , - , - , '- , th century representative composers machautlandini,gibbonsfrescobaldi,js bachvivaldi'-joseph haydnwolfgan amadeus mozart,chopinmendelssohnschumannliszt,wagner'-verdi,sergei rachmaninoff,calude debussy please note that my_dict is an ordereddict get dictionary of two dimensional array suppose you have multiple sheet book as the followinghere is the code to obtain those sheets as single dictionarybook_dict get_book_dict(file_name="book xls"and checkisinstance(book_dictordereddicttrue import json for keyitem in book_dict items()print(json dumps({keyitem}){"most expensive violins"[["name""estimated value""location"]["messiah '-stradivarious"" , , ""ashmolean museum in oxfordengland"]'-"vieuxtemps guarneri"" , , ""on loan to anne akiko meyers"]["lady blunt '-"" , , ""anonymous bidder"]]{"noteable violin makers"[["maker""period""country"]["antonio stradivari"'-" - ""cremonaitaly"]["giovanni paolo maggini"" - ""botticino'-italy"]["amati family"" - ""cremonaitaly"]["guarneri family"" '- ""cremonaitaly"]["rugeri family"" - ""cremonaitaly"]["carlo '-bergonzi"" - ""cremonaitaly"]["jacob stainer"" - ""austria '-"]]{"top violinist"[["name""period""nationality"]["antonio vivaldi"" - "'"italian"]["niccolo paganini"" - ""italian"]["pablo de sarasate"'-" - ""spainish"]["eugene ysaye"" - ""belgian"]["fritz kreisler (continues on next page'-"" - ""astria-american"]["jascha heifetz"" - ""russian'-american"]["david oistrakh"" - ""russian"]["yehundi menuhin"" '- ""american"]["itzhak perlman"" -""israeli-american"]["hilary hahn" support the project '" -""american"]] |
6,260 | (continued from previous pagewrite data export an array suppose you have the following arraydata [[' '' '' '' ']['thomastik-infield domaints''thomastik-infield '-domaints''thomastik-infield domaints''pirastro']['silver wound''''-'aluminum wound''gold label steel']and here is the code to save it as an excel file save_as(array=datadest_file_name="example xls"let' verify itp get_sheet(file_name="example xls"pyexcel_sheet +++'--+ ' +++'--+thomastik-infield domaints thomastik-infield domaints thomastik-infield '-domaints pirastro +++'--+silver wound aluminum wound 'gold label steel +++'--+and here is the code to save it as csv file save_as(array=datadest_file_name="example csv"dest_delimiter=':'let' verify itwith open("example csv"as ffor line in readlines()print(line rstrip() : : : thomastik-infield domaints:thomastik-infield domaints:thomastik-infield '-domaints:pirastro silver wound::aluminum wound:gold label steel new tutorial |
6,261 | export list of dictionaries records {"year" "country""germany""speed"" km/ "}{"year" "country""japan""speed"" km/ "}{"year" "country""china""speed"" km/ " save_as(records=recordsdest_file_name='high_speed_rail xls'export dictionary of single key value pair henley_on_thames_facts "area"" square meters""population"" , ""civial parish""henley-on-thames""latitude"" ""longitude""- save_as(adict=henley_on_thames_factsdest_file_name='henley xlsx'export dictionary of single dimensonal array ccs_insights "year"[" "" "" "" "" "]"smart phones"[ ]"feature phones"[ save_as(adict=ccs_insightsdest_file_name='ccs csv'export dictionary of two dimensional array as book suppose you want to save the below dictionary to an excel file a_dictionary_of_two_dimensional_arrays 'sheet '[ ][ ][ ]'sheet '[' '' '' '][ ][ ]'sheet '[' '' '' '][ ][ (continues on next page support the project |
6,262 | (continued from previous pagehere is the codep save_book_asbookdict=a_dictionary_of_two_dimensional_arraysdest_file_name="book xlsif you want to preserve the order of sheets in your dictionaryyou have to pass on an ordered dictionary to the function itself for exampledata ordereddict(data update({"sheet "a_dictionary_of_two_dimensional_arrays['sheet ']}data update({"sheet "a_dictionary_of_two_dimensional_arrays['sheet ']}data update({"sheet "a_dictionary_of_two_dimensional_arrays['sheet ']} save_book_as(bookdict=datadest_file_name="book xls"let' verify its orderbook_dict get_book_dict(file_name="book xls"for keyitem in book_dict items()print(json dumps({keyitem}){"sheet "[[" "" "" "][ ][ ]]{"sheet "[[ ][ ][ ]]{"sheet "[[" "" "" "][ ][ ]]please notice that "sheet is the first item in the book_dictmeaning the order of sheets are preserved transcoding noteplease note that pyexcel-cli can perform file transcoding at command line no need to open your editorsave the problemthen python run the following code does simple file format transcoding from xls to csvp save_as(file_name="birth xls"dest_file_name="birth csv"again it is really simple let' verify what we have gottensheet get_sheet(file_name="birth csv"sheet birth csv+++name weight birth +++adam +++smith +++ new tutorial |
6,263 | noteplease note that csv(comma separate valuefile is pure text file formulachartsimages and formatting in xls file will disappear no matter which transcoding tool you use hencepyexcel is quick alternative for this transcoding job let use previous example and save it as xlsx instead save_as(file_name="birth xls"dest_file_name="birth xlsx"change the file extension again let' verify what we have gottensheet get_sheet(file_name="birth xlsx"sheet pyexcel_sheet +++name weight birth +++adam +++smith +++excel book merge and split operation in one line merge all excel files in directory into book where each file become sheet the following code will merge every excel files into one filesay "output xls"from pyexcel cookbook import merge_all_to_a_book import glob merge_all_to_a_book(glob glob("your_csv_directory\csv")"output xls"you can mix and match with other excel formatsxlsxlsm and ods for exampleif you are sure you have only xlsxlsmxlsxods and csv files in your_excel_file_directoryyou can do the followingfrom pyexcel cookbook import merge_all_to_a_book import glob merge_all_to_a_book(glob glob("your_excel_file_directory\*")"output xls"split book into single sheet files suppose you have many sheets in work book and you would like to separate each into single sheet excel file you can easily do thisfrom pyexcel cookbook import split_a_book split_a_book("megabook xls""output xls"import glob outputfiles glob glob("*_output xls"(continues on next page support the project |
6,264 | (continued from previous pagefor file in sorted(outputfiles)print(filesheet _output xls sheet _output xls sheet _output xls for the output fileyou can specify any of the supported formats extract just one sheet from book suppose you just want to extract one sheet from many sheets that exists in work book and you would like to separate it into single sheet excel file you can easily do thisfrom pyexcel cookbook import extract_a_sheet_from_a_book extract_a_sheet_from_a_book("megabook xls""sheet ""output xls"if os path exists("sheet _output xls")print("sheet _output xls exists"sheet _output xls exists for the output fileyou can specify any of the supported formats stream apis for big file set of two liners when you are dealing with big excel filesyou will want pyexcel to use constant memory this section shows you how to get data from your big excel files and how to export data to excel files in two lines at mostwithout eating all your computer memory two liners for get data from big excel files get list of dictionaries suppose you want to process the following coffee datalet' get list of dictionary out from the xls filerecords iget_records(file_name="your_file xls"and let' check what do we havefor in recordsprint( "{ ['serving size']of { ['coffees']has { ['caffeine (mg)']mg"venti( ozof starbucks coffee blonde roast has mg large( oz of dunkindonuts coffee with turbo shot has mg grande( oz of starbucks coffee pike place roast has mg regular( oz of panera coffee light roast has mg please do not forgot the second line to close the opened file handlep free_resources( new tutorial |
6,265 | get two dimensional array insteadwhat if you have to use pyexcel get_array to do the samefor row in iget_array(file_name="your_file xls"start_row= )print( "{row[ ]of {row[ ]has {row[ ]mg"venti( ozof starbucks coffee blonde roast has mg large( oz of dunkindonuts coffee with turbo shot has mg grande( oz of starbucks coffee pike place roast has mg regular( oz of panera coffee light roast has mg againdo not forgot the second linep free_resources(where start_row skips the header row data export in one liners export an array suppose you have the following arraydata [[ ][ ][ ]and here is the code to save it as an excel file isave_as(array=datadest_file_name="example xls"but the following line is not required because the data source are not file sourcesp free_resources(let' verify itp get_sheet(file_name="example xls"pyexcel_sheet +---+---+--- +---+---+--- +---+---+--- +---+---+---and here is the code to save it as csv file isave_as(array=datadest_file_name="example csv"dest_delimiter=':'let' verify itwith open("example csv"as ffor line in readlines()(continues on next page support the project |
6,266 | (continued from previous page : : : : : : print(line rstrip()export list of dictionaries records {"year" "country""germany""speed"" km/ "}{"year" "country""japan""speed"" km/ "}{"year" "country""china""speed"" km/ " isave_as(records=recordsdest_file_name='high_speed_rail xls'export dictionary of single key value pair henley_on_thames_facts "area"" square meters""population"" , ""civial parish""henley-on-thames""latitude"" ""longitude""- isave_as(adict=henley_on_thames_factsdest_file_name='henley xlsx'export dictionary of single dimensonal array ccs_insights "year"[" "" "" "" "" "]"smart phones"[ ]"feature phones"[ isave_as(adict=ccs_insightsdest_file_name='ccs csv' free_resources(export dictionary of two dimensional array as book suppose you want to save the below dictionary to an excel file a_dictionary_of_two_dimensional_arrays 'sheet '[ ][ ][ ]'sheet '(continues on next page new tutorial |
6,267 | (continued from previous page[' '' '' '][ ][ ]'sheet '[' '' '' '][ ][ here is the codep isave_book_asbookdict=a_dictionary_of_two_dimensional_arraysdest_file_name="book xlsif you want to preserve the order of sheets in your dictionaryyou have to pass on an ordered dictionary to the function itself for examplefrom pyexcel _compact import ordereddict data ordereddict(data update({"sheet "a_dictionary_of_two_dimensional_arrays['sheet ']}data update({"sheet "a_dictionary_of_two_dimensional_arrays['sheet ']}data update({"sheet "a_dictionary_of_two_dimensional_arrays['sheet ']} isave_book_as(bookdict=datadest_file_name="book xls" free_resources(let' verify its orderimport json book_dict get_book_dict(file_name="book xls"for keyitem in book_dict items()print(json dumps({keyitem}){"sheet "[[" "" "" "][ ][ ]]{"sheet "[[ ][ ][ ]]{"sheet "[[" "" "" "][ ][ ]]please notice that "sheet is the first item in the book_dictmeaning the order of sheets are preserved file format transcoding on one line noteplease note that the following file transcoding could be with zero line please install pyexcel-cli and you will do the transcode in one command no need to open your editorsave the problemthen python run the following code does simple file format transcoding from xls to csvimport pyexcel save_as(file_name="birth xls"dest_file_name="birth csv"again it is really simple let' verify what we have gotten support the project |
6,268 | sheet get_sheet(file_name="birth csv"sheet birth csv+++name weight birth +++adam +++smith +++noteplease note that csv(comma separate valuefile is pure text file formulachartsimages and formatting in xls file will disappear no matter which transcoding tool you use hencepyexcel is quick alternative for this transcoding job let use previous example and save it as xlsx instead import pyexcel isave_as(file_name="birth xls"dest_file_name="birth xlsx"change the file extension again let' verify what we have gottensheet get_sheet(file_name="birth xlsx"sheet pyexcel_sheet +++name weight birth +++adam +++smith +++for web developer the following libraries are written to facilitate the daily import and export of excel data framework flask django pyramid plugin/middleware/extension flask-excel django-excel pyramid-excel and you may make your own by using pyexcel-webio read any supported excel and respond its content in json you can find real world example in examples/memoryfiledirectorypyexcel_server py here is the example snippet def upload()if request method ='postand 'excelin request files(continues on next page new tutorial |
6,269 | (continued from previous pagehandle file upload filename request files['excel'filename extension filename split(")[- obtain the file extension and content pass tuple instead of file name content request files['excel'read(if sys version_info[ in order to support python have to decode bytes to str content content decode('utf- 'sheet pe get_sheet(file_type=extensionfile_content=contentthen use it as usual sheet name_columns_by_row( respond with json return jsonify({"result"sheet dict}return render_template('upload html' request files['excel'in line holds the file object line finds out the file extension line obtains sheet instance line uses the first row as data header line sends the json representation of the excel file back to client browser write to memory and respond to download data ] @app route('/download'def download()sheet pe sheet(dataoutput make_response(sheet csvoutput headers["content-disposition""attachmentfilename=export csvoutput headers["content-type""text/csvreturn output make_response is flask utility to make memory content as http response noteyou can find the corresponding source code at examples/memoryfile pyexcel data renderers there exist few data renderers for pyexcel data this will walk you through them view pyexcel data in ndjson and other formats with pyexcel-textyou can get pyexcel data in newline delimited jsonnormal json and other formats view the pyexcel data in browser you can use pyexcel-handsontable to render your data support the project |
6,270 | include excel data in your python documentation sphinxcontrib-excel help you present your excel data in various formats inside your sphinx documentation draw charts from your excel data pyexcel-pygal helps you with all charting options and give you charts in svg format pyexcel-echarts draws dgeo charts from pyexcel data and has awesome animations toobut it is under development pyexcel-matplotlib helps you with scientific charts and is under developmement gantt chart visualization for your excel data pyexcel-gantt is specialist renderer for gantt chart sheet the sheet api here is much less powerful than pandas dataframe when the array is of significant size to be honestypandas dataframe is much more powerful and provide rich data manipulation apis when would you consider the sheet api hereif your data manipulation steps are basic and your data volume is not highyou can use them random access to randomly access cell of sheet instancetwo syntax are availablesheet[rowcolumnorsheet[' 'the former syntax is handy when you know the row and column numbers the latter syntax is introduced to help you convert the excel column header such as "axto integer numbers suppose you have the following datayou can get value by reader[ here is the example code showing how you can randomly access cellsheet pyexcel get_sheet(file_name="example xls"sheet content ++---+---+---example ++---+---+--- ++---+---+--- ++---+---+--- ++---+---+---print(sheet[ ] print(sheet[" "](continues on next page new tutorial |
6,271 | (continued from previous page sheet[ print(sheet[ ] notein order to set value to cellplease use sheet[row_indexcolumn_indexnew_value or sheet[' 'new_value random access to rows and columns continue with previous excel fileyou can access row and column separatelysheet row[ [' ' sheet column[ [' ' use custom names instead of index alternativelyit is possible to use the first row to refer to each columnssheet name_columns_by_row( print(sheet[ " "] sheet[ " " print(sheet[ " "] you have noticed the row index has been changed it is because first row is taken as the column nameshence all rows after the first row are shifted now accessing the columns are changed toosheet column[' '[ hence access the same cellthis statement also workssheet column[' '][ further moreit is possible to use first column to refer to each rowssheet name_rows_by_column( to access the same cellwe can use this linesheet row[" "][ for the same reasonthe row index has been reduced by since we have named columns and rowsit is possible to access the same cell like thisprint(sheet[" "" "] sheet[" "" " print(sheet[" "" "] support the project |
6,272 | play with data suppose you have the following data in any of the supported excel formats againsheet pyexcel get_sheet(file_name="example_series xls"name_columns_by_row= you can get headersprint(list(sheet colnames)['column ''column ''column 'you can use utility function to get all in dictionarysheet to_dict(ordereddict([('column '[ ])('column '[ ])('column '[ '- ])]maybe you want to get only the data without the column headers you can call rows(insteadlist(sheet rows()[[ ][ ][ ]attributes attributesimport pyexcel content " , , \ , , sheet pyexcel get_sheet(file_type="csv"file_content=contentsheet tsv ' \ \ \ \ \ \ \ \nprint(sheet simplecsv what' moreyou could as well set value to an attributefor example:import pyexcel content " , , \ , , sheet pyexcel sheet(sheet csv content sheet array [[ ][ ]you can get the direct access to underneath stream object in some situationit is desiredstream sheet stream tsv the returned stream object has tsv formatted content for reading what you could further do is to set memory stream of any supported file format to sheet for exampleanother_sheet pyexcel sheet(another_sheet xls sheet xls another_sheet content (continues on next page new tutorial |
6,273 | (continued from previous page+---+---+--- +---+---+--- +---+---+---yetit is possible assign absolute url to an online excel file to an instance of pyexcel sheet custom attributes you can pass on source specific parameters to getter and setter functions content "\nsheet pyexcel sheet(sheet set_csv(contentdelimiter="-"sheet csv ' , , \ \ , , \ \nsheet get_csv(delimiter="|"' | | \ \ | | \ \ndata manipulation the data in sheet is represented by sheet which maintains the data as list of lists you can regard sheet as two dimensional array with additional iterators random access to individual column and row is exposed by column and row column manipulation suppose have one data file as the followingsheet pyexcel get_sheet(file_name="example xls"name_columns_by_row= sheet pyexcel sheet+++column column column +==========+==========+========== +++ +++ +++and you want to update column with these data[ sheet column["column "[ sheet column[ [ sheet pyexcel sheet+++column column column +==========+==========+========== (continues on next page support the project |
6,274 | (continued from previous page+++ +++ +++remove one column of data file if you want to remove column you can just calldel sheet column["column "sheet column["column "[ the sheet content will becomesheet pyexcel sheet++column column +==========+========== ++ ++ ++append more columns to data file continue from previous example suppose you want add two more columns to the data file column column here is the example code to append two extra columnsextra_data ["column ""column "][ ][ ][ sheet pyexcel sheet(extra_datasheet sheet column sheet sheet column["column "[ sheet column["column "[ new tutorial |
6,275 | please note above column plus statement will not update original sheet instanceas pyexcel user demandedsheet pyexcel sheet++column column +==========+========== ++ ++ ++soto change orginal sheet instanceyou can elect to dosheet column +sheet here is what you will getsheet pyexcel sheet++++column column column column +==========+==========+==========+========== ++++ ++++ ++++cherry pick some columns to be removed suppose you have the following datadata [' '' '' '' '' '' '' '' '][ , , , , , , , ]sheet pyexcel sheet(dataname_columns_by_row= sheet pyexcel sheet+---+---+---+---+---+---+---+--- +===+===+===+===+===+===+===+=== +---+---+---+---+---+---+---+---and you want to remove columns named as' '' ' ''hthis is how you do itdel sheet column[' '' '' '' 'sheet pyexcel sheet+---+---+---+--- (continues on next page support the project |
6,276 | (continued from previous page+===+===+===+=== +---+---+---+---what if the headers are in different row suppose you have the following datasheet pyexcel sheet+++ +++column column column +++ +++the way to name your columns is to use index sheet name_columns_by_row( here is what you getsheet pyexcel sheet+++column column column +==========+==========+========== +++ +++row manipulation suppose you have the following datasheet pyexcel sheet+---+---+---+ row +---+---+---+ row +---+---+---+ row +---+---+---+you can name your rows by column index at sheet name_rows_by_column( sheet pyexcel sheet(continues on next page new tutorial |
6,277 | (continued from previous page++---+---+---row ++---+---+---row ++---+---+---row ++---+---+---then you can access rows by its namesheet row["row "[' '' '' 'formatting previous section has assumed the data is in the format that you want in realityyou have to manipulate the data types bit to suit your needs henceformatters comes into the scene use format(to apply formatter immediately noteintfloat and datetime values are automatically detected in csv files since pyexcel version convert column of numbers to strings suppose you have the following dataimport pyexcel data ["userid","name"][ ,"adam"][ ,"bella"][ ,"cedar"sheet pyexcel sheet(datasheet name_columns_by_row( sheet column["userid"[ as you can seeuserid column is of int type nextlet' convert the column to string formatsheet column format("userid"strsheet column["userid"[' '' '' 'cleanse the cells in spread sheet sometimesthe data in spreadsheet may have unwanted strings in all or some cells let' take an example suppose we have spread sheet that contains all strings but it as random spaces before and after the text values some field had weird characterssuch as " " support the project |
6,278 | data [version"comments"author "][ "release versions", eda"][" v ""useful updates   " freud"sheet pyexcel sheet(datasheet content +++version comments author  +++ release versions eda +++ v useful updates    freud +++now try to create custom cleanse functioncode-block:python def cleanse_func( ) replace(" """ rstrip(strip(return then let' create sheetformatter and apply itcode-block:python sheet map(cleanse_funcso in the endyou get thissheet content +++version comments author +++ release versions eda +++ useful updates freud +++data filtering use filter(function to apply filter immediately the content is modified suppose you have the following data in any of the supported excel formatscolumn new tutorial column column |
6,279 | import pyexcel sheet pyexcel get_sheet(file_name="example_series xls"name_columns_by_row= sheet content +++column column column +==========+==========+========== +++ +++ +++filter out some data you may want to filter odd rows and print them in an array of dictionariessheet filter(row_indices=[ ]sheet content +++column column column +==========+==========+========== +++let' try to further filter out even columnssheet filter(column_indices=[ ]sheet content ++column column +==========+========== ++save the data let' save the previous filtered datasheet save_as("example_series_filter xls"when you open example_series_filter xlsyou will find these data column column how to filter out empty rows in my sheetsuppose you have the following data in sheet and you want to remove those rows with blanks support the project |
6,280 | import pyexcel as pe sheet pe sheet([[ , , ],['','',''],['','',''],[ , , ]]you can use pyexcel filters rowvaluefilterwhich examines each rowreturn true if the row should be filtered out solet' define filter functiondef filter_row(row_indexrow)result [element for element in row if element !''return len(result)== and then apply the filter on the sheetdel sheet row[filter_rowsheet pyexcel sheet+---+---+--- +---+---+--- +---+---+---book you access each cell via this syntaxbook[sheet_index][rowcolumnorbook["sheet_name"][rowcolumnsuppose you have the following sheetsand you can randomly access cell in sheetbook pyexcel get_book(file_name="example xls"print(book["sheet "][ , ] print(book[ ][ , ]the same cell tipwith pyexcelyou can regard single sheet as an two dimensional array and multi-sheet excel book as an ordered dictionary of two dimensional arrays write multiple sheet excel book suppose you have previous data as dictionary and you want to save it as multiple sheet excel filecontent 'sheet '[ ][ ][ (continues on next page new tutorial |
6,281 | (continued from previous page]'sheet '[' '' '' '][ ][ ]'sheet '[' '' '' '][ ][ book pyexcel get_book(bookdict=contentbook save_as("output xls"you shall get xls file read multiple sheet excel file let' read the previous file backbook pyexcel get_book(file_name="output xls"sheets book to_dict(for name in sheets keys()print(namesheet sheet sheet get content book_dict 'sheet '[' '' '' '][ ][ ]'sheet '[' '' '' '][ ][ ]'sheet '[ ][ ][ book pyexcel get_book(bookdict=book_dictbook (continues on next page support the project |
6,282 | (continued from previous pagesheet +++ +++ +++ +++sheet +++ +++ +++ +++sheet +++ +++ +++ +++print(book rstsheet sheet ====== ======sheet ====== ======you can get the direct access to underneath stream object in some situationit is desired stream book stream plain the returned stream object has the content formatted in plain format for further reading set content surelyyou could set content to an instance of pyexcel book new tutorial |
6,283 | other_book pyexcel book(other_book bookdict book_dict print(other_book plainsheet sheet sheet you can set via 'xlsattribute too another_book pyexcel book(another_book xls other_book xls print(another_book mediawikisheet {class="wikitablestyle="text-alignleft;||align="right" |align="right" |align="right" |align="right" |align="right" |align="right" |align="right" |align="right" |align="right" |sheet {class="wikitablestyle="text-alignleft;|| | | | | | | | | |sheet {class="wikitablestyle="text-alignleft;|| | | | | | | | | |access to individual sheets you can access individual sheet of book via attribute support the project |
6,284 | book pyexcel get_book(file_name="book xls"book sheet sheet +---+---+--- +---+---+--- +---+---+--- +---+---+---or via array notationsbook["sheet "there is space in the sheet name sheet +---+---+--- +---+---+--- +---+---+--- +---+---+---merge excel books suppose you have two excel books and each had three sheets you can merge them and get new bookyou also can merge individual sheetsbook pyexcel get_book(file_name="book xls"book pyexcel get_book(file_name="book xlsx"merged_book book book merged_book book ["sheet "book ["sheet "merged_book book ["sheet "book merged_book book book ["sheet "manipulate individual sheets merge sheets into single sheet suppose you want to merge many csv files row by row into new sheet import glob merged pyexcel sheet(for file in glob glob("csv")merged row +pyexcel get_sheet(file_name=filemerged save_as("merged csv"how do read bookprocess it and save to new book yesyou can do that the code looks like this new tutorial |
6,285 | import pyexcel book pyexcel get_book(file_name="yourfile xls"for sheet in bookdo you processing with sheet do filteringpass book save_as("output xls"what would happen if save multi sheet book into "csvfile wellyou will get one csv file per each sheet suppose you have these codecontent 'sheet '[ ][ ][ ]'sheet '[' '' '' '][ ][ ]'sheet '[' '' '' '][ ][ book pyexcel book(contentbook save_as("myfile csv"you will end up with three csv filesimport glob outputfiles glob glob("myfile_csv"for file in sorted(outputfiles)print(filemyfile__sheet __ csv myfile__sheet __ csv myfile__sheet __ csv and their content is the value of the dictionary at the corresponding key alternativelyyou could use save_book_as(function pyexcel save_book_as(bookdict=contentdest_file_name="myfile csv" support the project |
6,286 | after have saved my multiple sheet book in csv formathow do get them back first of allyou can read them back individual as csv file using meth:~pyexcel get_sheet method secondlythe pyexcel can do the magic to load all of them back into book you will just need to provide the common name before the separator "__"book pyexcel get_book(file_name="myfile csv"book sheet +++ +++ +++ +++sheet +++ +++ +++ +++sheet +++ +++ +++ +++working with databases how to import an excel sheet to database using sqlalchemy noteyou can find the complete code of this example in examples folder on github before going aheadlet' import the needed components and initialize sql engine and table baseimport os import pyexcel as from sqlalchemy import create_engine from sqlalchemy ext declarative import declarative_base from sqlalchemy import column integerstringfloatdate from sqlalchemy orm import sessionmaker engine create_engine("sqlite:///birth db"base declarative_base(session sessionmaker(bind=enginelet' suppose we have the following database model new tutorial |
6,287 | class birthregister(base)__tablename__='birthid=column(integerprimary_key=truename=column(stringweight=column(floatbirth=column(datelet' create the tablebase metadata create_all(enginenow here is sample excel file to be saved to the tablehere is the code to import itsession session(obtain sql session save_as(file_name="birth xls"name_columns_by_row= dest_session=session'-dest_table=birthregisterdone it it is that simple let' verify what has been imported to make sure sheet get_sheet(session=sessiontable=birthregistersheet birth++----++birth id name weight ++----++ adam ++----++ smith ++----++ old tutorial work with excel files warningthe pyexcel does not consider fontsstylesformulas and charts at all when you load stylish excel and update ityou definitely will lose all those styles open csv file read csv file is simpleimport pyexcel as sheet get_sheet(file_name="example csv"sheet example csv+---+---+--- +---+---+--- +---+---+---(continues on next page support the project |
6,288 | (continued from previous page +---+---+---the same applies to tsv filesheet get_sheet(file_name="example tsv"sheet example tsv+---+---+--- +---+---+--- +---+---+--- +---+---+---meanwhilea tab separated file can be read as csv too you can specify delimiter parameter with open('tab_example csv'' 'as funused write(' \tam\ttab\tseparated\tcsv\ 'for passing doctest unused write('you\tneed\tdelimiter\tparameter\ 'unused is added sheet get_sheet(file_name="tab_example csv"delimiter='\ 'sheet tab_example csv+++++ am tab separated csv +++++you need delimiter parameter +++++add new row to an existing file suppose you have one data file as the followingand you want to add new row here is the codeimport pyexcel as pe sheet pe get_sheet(file_name="example xls"sheet row +[ sheet save_as("new_example xls"pe get_sheet(file_name="new_example xls"pyexcel_sheet +++column column column +++ +++ +++ +++ +++ old tutorial |
6,289 | update an existing row to an existing file suppose you want to update the last row of the example file as[' / '' / '' / 'here is the sample codecode-block:python import pyexcel as pe sheet pe get_sheet(file_name="example xls"sheet row[ [' / '' / '' / 'sheet save_as("new_example xls"pe get_sheet(file_name="new_example xls"pyexcel_sheet +++column column column +++ +++ +++ / / / +++add new column to an existing file and you want to add column instead["column " here is the codeimport pyexcel as pe sheet pe get_sheet(file_name="example xls"sheet column +["column " sheet save_as("new_example xls"pe get_sheet(file_name="new_example xls"pyexcel_sheet ++++column column column column ++++ ++++ ++++ ++++update an existing column to an existing file again let' update "column with[ here is the sample code support the project |
6,290 | import pyexcel as pe sheet pe get_sheet(file_name="example xls"sheet column[ ["column " sheet save_as("new_example xls"pe get_sheet(file_name="new_example xls"pyexcel_sheet +++column column column +++ +++ +++ +++alternativelyyou could have done like thisimport pyexcel as pe sheet pe get_sheet(file_name="example xls"name_columns_by_row= sheet column["column "[ sheet save_as("new_example xls"pe get_sheet(file_name="new_example xls"pyexcel_sheet +++column column column +++ +++ +++ +++how about the same alternative solution to previous row based examplewellyou' better to have the following kind of dataand then you want to update "row with for example[ these code would do the jobimport pyexcel as pe sheet pe get_sheet(file_name="row_example xls"name_rows_by_column= sheet row["row "[ sheet save_as("new_example xls"pe get_sheet(file_name="new_example xls"pyexcel_sheet ++++row ++++row ++++row ++++ old tutorial |
6,291 | work with excel files in memory excel files in memory can be manipulated directly without saving it to physical disk and vice versa this is useful in excel file handling at file upload or in excel file download for exampleimport pyexcel content " , , \ , , sheet pyexcel get_sheet(file_type="csv"file_content=contentsheet csv ' , , \ \ , , \ \nfile type as its attributes since version each supported file types became an attribute of the sheet and book class what it means is that read the content in memory set the content in memory for exampleafter you have your sheet and book instanceyou could access its content in support file type by using its dot notation the code in previous section could be rewritten asimport pyexcel content " , , \ , , sheet pyexcel sheet(sheet csv content sheet array [[ ][ ]read any supported excel and respond its content in json you can find real world example in examples/memoryfiledirectorypyexcel_server py here is the example snippet def upload()if request method ='postand 'excelin request fileshandle file upload filename request files['excel'filename extension filename split(")[- obtain the file extension and content pass tuple instead of file name content request files['excel'read(if sys version_info[ in order to support python have to decode bytes to str content content decode('utf- 'sheet pe get_sheet(file_type=extensionfile_content=contentthen use it as usual sheet name_columns_by_row( respond with json return jsonify({"result"sheet dict}return render_template('upload html'request files['excel'in line holds the file object line finds out the file extension line obtains sheet instance line uses the first row as data header line sends the json representation of the excel file back to client browser support the project |
6,292 | write to memory and respond to download data ] @app route('/download'def download()sheet pe sheet(dataoutput make_response(sheet csvoutput headers["content-disposition""attachmentfilename=export csvoutput headers["content-type""text/csvreturn output make_response is flask utility to make memory content as http response noteyou can find the corresponding source code at examples/memoryfile relevant packages readily made plugins have been made on top of this example here is list of themframework flask django pyramid plugin/middleware/extension flask-excel django-excel pyramid-excel and you may make your own by using pyexcel-webio sheetdata conversion how to obtain records from an excel sheet suppose you want to process the following excel data here are the example codeimport pyexcel as pe records pe get_records(file_name="your_file xls"for record in recordsprint("% is aged at % (record['name']record['age'])adam is aged at beatrice is aged at ceri is aged at dean is aged at how to save an python array as an excel file suppose you have the following array old tutorial |
6,293 | data [[ ][ ][ ]and here is the code to save it as an excel file import pyexcel pyexcel save_as(array=datadest_file_name="example xls"let' verify itpyexcel get_sheet(file_name="example xls"pyexcel_sheet +---+---+--- +---+---+--- +---+---+--- +---+---+---how to save an python array as csv file with special delimiter suppose you have the following arraydata [[ ][ ][ ]and here is the code to save it as an excel file import pyexcel pyexcel save_as(array=datadest_file_name="example csv"dest_delimiter=':'let' verify itwith open("example csv"as ffor line in readlines()print(line rstrip() : : : : : : how to get dictionary from an excel sheet suppose you have csvxlsxlsx file as the followingthe following code will give you data series in dictionaryimport pyexcel from pyexcel _compact import ordereddict my_dict pyexcel get_dict(file_name="example_series xls"name_columns_by_row= isinstance(my_dictordereddicttrue for keyvalues in my_dict items()(continues on next page support the project |
6,294 | (continued from previous pageprint({str(key)values}{'column '[ ]{'column '[ ]{'column '[ ]please note that my_dict is an ordereddict how to obtain dictionary from multiple sheet book suppose you have multiple sheet book as the followinghere is the code to obtain those sheets as single dictionaryimport pyexcel import json book_dict pyexcel get_book_dict(file_name="book xls"isinstance(book_dictordereddicttrue for keyitem in book_dict items()print(json dumps({keyitem}){"sheet "[[ ][ ][ ]]{"sheet "[[" "" "" "][ ][ ]]{"sheet "[[" "" "" "][ ][ ]]how to save dictionary of two dimensional array as an excel file suppose you want to save the below dictionary to an excel file a_dictionary_of_two_dimensional_arrays 'sheet '[ ][ ][ ]'sheet '[' '' '' '][ ][ ]'sheet '[' '' '' '][ ][ here is the codepyexcel save_book_asbookdict=a_dictionary_of_two_dimensional_arraysdest_file_name="book xls old tutorial |
6,295 | if you want to preserve the order of sheets in your dictionaryyou have to pass on an ordered dictionary to the function itself for exampledata ordereddict(data update({"sheet "a_dictionary_of_two_dimensional_arrays['sheet ']}data update({"sheet "a_dictionary_of_two_dimensional_arrays['sheet ']}data update({"sheet "a_dictionary_of_two_dimensional_arrays['sheet ']}pyexcel save_book_as(bookdict=datadest_file_name="book xls"let' verify its orderbook_dict pyexcel get_book_dict(file_name="book xls"for keyitem in book_dict items()print(json dumps({keyitem}){"sheet "[[" "" "" "][ ][ ]]{"sheet "[[ ][ ][ ]]{"sheet "[[" "" "" "][ ][ ]]please notice that "sheet is the first item in the book_dictmeaning the order of sheets are preserved how to import an excel sheet to database using sqlalchemy noteyou can find the complete code of this example in examples folder on github before going aheadlet' import the needed components and initialize sql engine and table basefrom sqlalchemy import create_engine from sqlalchemy ext declarative import declarative_base from sqlalchemy import column integerstringfloatdate from sqlalchemy orm import sessionmaker engine create_engine("sqlite:///birth db"base declarative_base(session sessionmaker(bind=enginelet' suppose we have the following database modelclass birthregister(base)__tablename__='birthid=column(integerprimary_key=truename=column(stringweight=column(floatbirth=column(datelet' create the tablebase metadata create_all(enginenow here is sample excel file to be saved to the tablehere is the code to import itsession session(obtain sql session pyexcel save_as(file_name="birth xls"name_columns_by_row= dest_ '-session=sessiondest_table=birthregisterdone it it is that simple let' verify what has been imported to make sure support the project |
6,296 | sheet pyexcel get_sheet(session=sessiontable=birthregistersheet birth++----++birth id name weight ++----++ adam ++----++ smith ++----++how to open an xls file and save it as csv suppose we want to save previous used example 'birth xlsas csv file import pyexcel pyexcel save_as(file_name="birth xls"dest_file_name="birth csv"again it is really simple let' verify what we have gottensheet pyexcel get_sheet(file_name="birth csv"sheet birth csv+++name weight birth +++adam +++smith +++noteplease note that csv(comma separate valuefile is pure text file formulachartsimages and formatting in xls file will disappear no matter which transcoding tool you use hencepyexcel is quick alternative for this transcoding job how to open an xls file and save it as xlsx warningformulachartsimages and formatting in xls file will disappear as pyexcel does not support formulachartsimages and formatting let use previous example and save it as ods instead import pyexcel pyexcel save_as(file_name="birth xls"dest_file_name="birth xlsx"change the file extension again let' verify what we have gottensheet pyexcel get_sheet(file_name="birth xlsx"sheet (continues on next page old tutorial |
6,297 | (continued from previous pagepyexcel_sheet +++name weight birth +++adam +++smith +++how to open xls multiple sheet excel book and save it as csv wellyou write similar codes as before but you will need to use save_book_as(function dot notation for data source since version the data source becomes an attribute of the pyexcel native classes all support data format is dot notation away for sheet get content import pyexcel content " , , \ , , sheet pyexcel get_sheet(file_type="csv"file_content=contentsheet tsv ' \ \ \ \ \ \ \ \nprint(sheet simplecsv what' moreyou could as well set value to an attributefor exampleimport pyexcel content " , , \ , , sheet pyexcel sheet(sheet csv content sheet array [[ ][ ]you can get the direct access to underneath stream object in some situationit is desired stream sheet stream tsv the returned stream object has tsv formatted content for reading support the project |
6,298 | set content what you could further do is to set memory stream of any supported file format to sheet for exampleanother_sheet pyexcel sheet(another_sheet xls sheet xls another_sheet content +---+---+--- +---+---+--- +---+---+---yetit is possible assign absolute url to an online excel file to an instance of pyexcel sheet another_sheet url "'-basics/multiple-sheets-example xlsanother_sheet content +---+---+--- +---+---+--- +---+---+--- +---+---+---for book the same dot notation is available to pyexcel book as well get content book_dict 'sheet '[' '' '' '][ ][ ]'sheet '[' '' '' '][ ][ ]'sheet '[ ][ ][ book pyexcel get_book(bookdict=book_dictbook (continues on next page old tutorial |
6,299 | (continued from previous pagesheet +++ +++ +++ +++sheet +++ +++ +++ +++sheet +++ +++ +++ +++print(book rstsheet sheet ====== ======sheet ====== ======you can get the direct access to underneath stream object in some situationit is desired stream sheet stream plain the returned stream object has the content formatted in plain format for further reading set content surelyyou could set content to an instance of pyexcel book support the project |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.