Best Python code snippet using molecule_python
results.py
Source:results.py
1class PyLSpmHTML(object):23 def __init__(self, plsobject):4 self.path_matrix = plsobject.path_matrix.T5 self.scheme = plsobject.scheme6 self.regression = plsobject.regression78 if self.regression == 'fuzzy':9 self.path_matrix_low = plsobject.path_matrix_low10 self.path_matrix_high = plsobject.path_matrix_high11 self.path_matrix_range = plsobject.path_matrix_range1213 self.corLVs = plsobject.corLVs()14 self.AVE = plsobject.AVE()15 self.fscores = plsobject.fscores16 self.comunalidades = plsobject.comunalidades()17 self.outer_loadings = plsobject.outer_loadings18 self.xloads = plsobject.xloads()19 self.outer_weights = plsobject.outer_weights20 self.fscores = plsobject.fscores21 self.rhoA = plsobject.rhoA()22 self.alpha = plsobject.alpha()23 self.r2 = plsobject.r224 self.r2adjusted = plsobject.r2adjusted()25 self.htmt = plsobject.htmt()26 self.cr = plsobject.cr()27 self.total_effects = plsobject.total_effects28 self.indirect_effects = plsobject.indirect_effects29 self.empirical = plsobject.empirical()30 self.implied = plsobject.implied()3132 self.srmr = plsobject.srmr()33 self.gof = plsobject.gof()34 self.frequency = plsobject.frequency()35 self.mean, self.sd, self.skew, self.kurtosis, self.shapiro = plsobject.dataInfo()3637 self.plsc = plsobject.disattenuate3839 def geraInfo(self):4041 print_matrix = """42 <div id=info>43 <h3>Model Info</h3>44 <table class="table table-striped table-condensed">45 <thead>46 <tr>"""4748 linhas = ['Scheme', 'Regression', 'Latent Variables',49 'Manifests', 'Observations', 'SRMR', 'GoF', 'disattenuation']50 conteudo = [(self.scheme), self.regression, len(self.path_matrix), len(51 self.outer_loadings), len(self.fscores), round(self.srmr, 3), round(self.gof, 3), self.plsc]5253 print_matrix += """</tr></thead><tbody>"""5455 for i in range(len(linhas)):56 print_matrix += "<tr>"57 print_matrix += "<td>" + str(linhas[i]) + "</td>"58 print_matrix += "<td>" + str(conteudo[i]) + "</td>"59 print_matrix += "</tr>"6061 print_matrix += """</tbody>62 </table></div>"""6364 return print_matrix6566 def geraTable(self, matrix, titulo, link):6768 print_matrix = """69 <div id=""" + link + """>70 <h3>""" + titulo + """</h3>71 <table class="table table-striped table-condensed">72 <thead>73 <tr>"""7475 colunas = matrix.columns.values76 linhas = matrix.index.values77 conteudo = matrix.values7879 print_matrix += "<th></th>"80 for i in range(len(colunas)):81 print_matrix += "<th>" + str(colunas[i]) + "</th>"8283 print_matrix += """</tr></thead><tbody>"""8485 for i in range(len(linhas)):86 print_matrix += "<tr>"87 print_matrix += "<td>" + str(linhas[i]) + "</td>"88 for j in range(len(colunas)):89 if (str(conteudo[i][j]) == '0.0'):90 print_matrix += "<td></td>"91 else:92 print_matrix += "<td>" + \93 str(round(conteudo[i][j], 3)) + "</td>"94 print_matrix += "</tr>"9596 print_matrix += """</tbody>97 </table></div>"""9899 return print_matrix100101 def geraTableStr(self, matrix, titulo, link):102103 print_matrix = """104 <div id=""" + link + """>105 <h3>""" + titulo + """</h3>106 <table class="table table-striped table-condensed">107 <thead>108 <tr>"""109110 colunas = matrix.columns.values111 linhas = matrix.index.values112 conteudo = matrix.values113114 print_matrix += "<th></th>"115 for i in range(len(colunas)):116 print_matrix += "<th>" + str(colunas[i]) + "</th>"117118 print_matrix += """</tr></thead><tbody>"""119120 for i in range(len(linhas)):121 print_matrix += "<tr>"122 print_matrix += "<td>" + str(linhas[i]) + "</td>"123 for j in range(len(colunas)):124 if (str(conteudo[i][j]) == '0.0 0.0'):125 print_matrix += "<td></td>"126 else:127 print_matrix += "<td>" + str(conteudo[i][j]) + "</td>"128 print_matrix += "</tr>"129130 print_matrix += """</tbody>131 </table></div>"""132133 return print_matrix134135 def geraReliabilityTable(self, matrix, matrix2, matrix3):136137 print_matrix = """138 <div id="reliability">139 <h3>Construct Reliability</h3>140 <table class="table table-striped table-condensed">141 <thead>142 <tr>"""143144 linhas = matrix.index.values145 conteudo = matrix.values146 conteudo2 = matrix2.values147 conteudo3 = matrix3.values148149 print_matrix += "<th></th>"150 print_matrix += "<th>Cronbach Alpha</th>"151 print_matrix += "<th>Composite Reliability</th>"152 print_matrix += "<th>ρA</th>"153154 print_matrix += """</tr></thead><tbody>"""155156 for i in range(len(linhas)):157 print_matrix += "<tr>"158 print_matrix += "<td>" + str(linhas[i]) + "</td>"159 print_matrix += "<td>" + \160 str(round(float(conteudo[i]), 3)) + "</td>"161 print_matrix += "<td>" + \162 str(round(float(conteudo2[i]), 3)) + "</td>"163 print_matrix += "<td>" + \164 str(round(float(conteudo3[i]), 3)) + "</td>"165 print_matrix += "</tr>"166167 print_matrix += """</tbody>168 </table></div>"""169170 return print_matrix171172 def geraDataInfoTable(self, matrix, matrix2, matrix3, matrix4, matrix5):173174 print_matrix = """175 <div id="datainfo">176 <h3>Population Info</h3>177 <table class="table table-striped table-condensed">178 <thead>179 <tr>"""180181 linhas = matrix.index.values182 conteudo = matrix.values183 conteudo2 = matrix2.values184 conteudo3 = matrix3185 conteudo4 = matrix4186 conteudo5 = matrix5187188 print_matrix += "<th></th>"189 print_matrix += "<th>Mean</th>"190 print_matrix += "<th>Standard Deviation</th>"191 print_matrix += "<th>Skewness</th>"192 print_matrix += "<th>Kurtosis</th>"193 print_matrix += "<th>Shapiro</th>"194195 print_matrix += """</tr></thead><tbody>"""196197 for i in range(len(linhas)):198 print_matrix += "<tr>"199 print_matrix += "<td>" + str(linhas[i]) + "</td>"200 print_matrix += "<td>" + \201 str(round(float(conteudo[i]), 3)) + "</td>"202 print_matrix += "<td>" + \203 str(round(float(conteudo2[i]), 3)) + "</td>"204 print_matrix += "<td>" + \205 str(round(float(conteudo3[i]), 3)) + "</td>"206 print_matrix += "<td>" + \207 str(round(float(conteudo4[i]), 3)) + "</td>"208 print_matrix += "<td>" + \209 str(round(float(conteudo5[i]), 3)) + "</td>"210 print_matrix += "</tr>"211212 print_matrix += """</tbody>213 </table></div>"""214215 return print_matrix216217 def gerasingleTable(self, matrix, titulo, link):218219 print_matrix = """220 <div id=""" + link + """>221 <h3>""" + titulo + """</h3>222 <table class="table table-striped table-condensed">223 <thead>224 <tr>"""225226 linhas = matrix.index.values227 conteudo = matrix.values228229 print_matrix += "<th></th>"230 print_matrix += "<th>" + titulo + "</th>"231232 print_matrix += """</tr></thead><tbody>"""233234 for i in range(len(linhas)):235 print_matrix += "<tr>"236 print_matrix += "<td>" + str(linhas[i]) + "</td>"237 print_matrix += "<td>" + \238 str(round(float(conteudo[i]), 3)) + "</td>"239 print_matrix += "</tr>"240241 print_matrix += """</tbody>242 </table></div>"""243244 return print_matrix245246 def generate(self):247248 message = """<!DOCTYPE html>249 <html lang="en">250 <head>251 <meta charset="utf-8">252 <title>PyLS-PM - Partial Least Squares Path Modeling in Python</title>253254 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">255256 <script257 src="https://code.jquery.com/jquery-2.2.4.min.js"258 integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="259 crossorigin="anonymous"></script>260 <!-- Optional theme -->261 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">262263 <!-- Latest compiled and minified JavaScript -->264 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>265266 <style>267 body {268 position: relative;269 }270 ul.nav-pills {271 top: 20px;272 margin-left: -22px;273 margin-right: -22px;274 }275 .nav-pills>li>a {276 padding: 5px 15px !important;277 }278 .sidebar {279 position: fixed;280 top: 41px;281 bottom: 0;282 left: 0;283 z-index: 1000;284 display: block;285 padding: 20px;286 overflow-x: hidden;287 overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */288 background-color: #f5f5f5;289 border-right: 1px solid #eee;290 }291 .results {292 padding-top: 51px;293 padding-left: 50px;294 padding-right: 50px;295 }296297 </style>298299 <script>300 var offsetHeight = 51;301 $(document).ready(function(){302303 $('a').click(function (event) {304 var tamanho = $('.results').find($(this).attr('href'))305306 $('body,html').animate({307 scrollTop: tamanho[0].offsetTop-60308 }, 500);309 return false;310 });311 });312 </script>313314 </head>"""315316 info = self.geraInfo()317318 path_matrix = self.geraTable(319 self.path_matrix, 'Path Coefficients', 'path_matrix')320321 if(self.regression == 'fuzzy'):322 path_matrix_low = self.geraTable(323 self.path_matrix_low, 'Low Path Coefficients', 'path_matrix_low')324 path_matrix_high = self.geraTable(325 self.path_matrix_high, 'High Path Coefficients', 'path_matrix_high')326 path_matrix_range = self.geraTableStr(327 self.path_matrix_range, 'Path Coefficients Range', 'path_matrix_range')328329 indirect_effects = self.geraTable(330 self.indirect_effects, 'Indirect Effects', 'indirect_effects')331 total_effects = self.geraTable(332 self.total_effects, 'Total Effects', 'total_effects')333334 r2 = self.gerasingleTable(self.r2, 'R-Squared', 'r2')335 r2adjusted = self.gerasingleTable(336 self.r2adjusted, 'R-Squared Adjusted', 'r2adjusted')337 AVE = self.gerasingleTable(338 self.AVE, 'Average Variance Extracted', 'AVE')339340 corLVs = self.geraTable(341 self.corLVs, 'Latent Variables Correlations', 'corLVs')342 htmt = self.geraTable(343 self.htmt, 'Heterotrait-Monotrait Ratio of Correlations (HTMT)', 'htmt')344 outer_loadings = self.geraTable(345 self.outer_loadings, 'Loadings', 'outer_loadings')346 comunalidades = self.geraTable(347 self.comunalidades, 'Communalities', 'comunalidades')348 xloads = self.geraTable(self.xloads, 'Crossloadings', 'xloads')349 fscores = self.geraTable(self.fscores, 'Scores', 'fscores')350 outer_weights = self.geraTable(351 self.outer_weights, 'Weigths', 'outer_weights')352353 empirical = self.geraTable(354 self.empirical, 'Empirical Correlation Matrix', 'empirical')355 implied = self.geraTable(356 self.implied, 'Model Implied Correlation Matrix', 'implied')357358 frequency = self.geraTable(359 self.frequency, 'Frequency Table', 'frequency')360361 reliability = self.geraReliabilityTable(self.alpha, self.cr, self.rhoA)362363 datainfo = self.geraDataInfoTable(364 self.mean, self.sd, self.skew, self.kurtosis, self.shapiro)365366 body = """<body data-spy="scroll" data-target="#myScrollspy" data-offset="60">367 <nav class="navbar navbar-inverse navbar-fixed-top"><div class="container-fluid"><div class="navbar-header"><div class="navbar-brand">PyLS-PM</div></div></div></nav>368 <div class="container-fluid">369 <div class="row">370 <div class="col-sm-3 col-md-2 sidebar" id="myScrollspy">371 <ul class="nav nav-pills nav-stacked">372 <div align="center">373 <img src="logo.png"></div>374 <li class=""><a align="center" href="#overall"><b>Overall</b></a></li>375 <li class=""><a href="#reliability">Construct Reliability</a></li>376 <li class=""><a href="#htmt">HTMT</a></li>377378 <li class=""><a align="center" href="#inner"><b>Inner Model</b></a></li>379 <li class=""><a href="#path_matrix">Path Coefficients</a></li>"""380381 if(self.regression == 'fuzzy'):382 body += """383 <li class=""><a href="#path_matrix_low">Low Path Coefficients</a></li>384 <li class=""><a href="#path_matrix_high">High Path Coefficients</a></li>385 <li class=""><a href="#path_matrix_range">Path Coefficients Range</a></li>"""386 else:387 body += """<li class=""><a href="#r2">R-Squared</a></li>388 <li class=""><a href="#r2adjusted">R-Squared Adjusted</a></li>"""389390 body += """<li class=""><a href="#indirect_effects">Indirect Effects</a></li>391 <li class=""><a href="#total_effects">Total Effects</a></li>392 <li class=""><a href="#AVE">Average Variance Extracted</a></li>393 <li class=""><a href="#corLVs">Latent Variables Correlations</a></li>394395 <li class=""><a align="center" href="#outer"><b>Outer Model</b></a></li>396 <li class=""><a href="#outer_loadings">Loadings</a></li>397 <li class=""><a href="#comunalidades">Communalities</a></li>398 <li class=""><a href="#xloads">Crossloadings</a></li>399 <li class=""><a href="#outer_weights">Weigths</a></li>400401 <li class=""><a align="center" href="#others"><b>Others</b></a></li> 402 <li class=""><a href="#fscores">Scores</a></li>403 <li class=""><a href="#empirical">Empirical Correlation Matrix</a></li>404 <li class=""><a href="#implied">Model Implied Correlation Matrix</a></li>405 <li class=""><a align="center" href="#datainfo"><b>Data Info</b></a></li> 406 </ul>407 </div>408 <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 results">"""409410 rodape = """</div></div></div>411 </body>412 </html>"""413414 f = open('results.html', 'w', encoding='utf-8')415 f.write(message)416 f.write(body)417418 f.write('<h1 id="overall">Overall</h1><hr>')419 f.write(info)420 f.write(reliability)421 f.write(htmt)422423 f.write('<h1 id="inner">Inner Model</h1><hr>')424 f.write(path_matrix)425426 if(self.regression == 'fuzzy'):427 f.write(path_matrix_low)428 f.write(path_matrix_high)429 f.write(path_matrix_range)430 else:431 f.write(r2)432 f.write(r2adjusted)433 f.write(indirect_effects)434 f.write(total_effects)435 f.write(AVE)436 f.write(corLVs)437438 f.write('<h1 id="outer">Outer Model</h1><hr>')439440 f.write(outer_loadings)441 f.write(comunalidades)442 f.write(xloads)443 f.write(outer_weights)444445 f.write('<h1 id="others">Others</h1><hr>')446 f.write(fscores)447 f.write(empirical)448 f.write(implied)449 f.write('<h1 id="datainfo">Data Info</h1><hr>')450 f.write(frequency)451 f.write(datainfo)452 f.write(rodape)
...
efficient_plotting.py
Source:efficient_plotting.py
1import argparse2from colorama import Fore, Style3PARSER = argparse.ArgumentParser()4PARSER.add_argument("-basic", help="produces basic dotplot without changess", action="store_true")5PARSER.add_argument("-colour", help="produces dotplot where letters not on diagnonals are blacked out", action="store_true")6PARSER.add_argument("-compliment", help="produces mapped compliment base pairing dotplot", action="store_true")7PARSER.add_argument('-file1', help="first sequence that will be used as x axis in the dotplot", dest='seq1', action='store')8PARSER.add_argument('-file2', help="second sequence that will be used as the y axis in the dotplot", dest='seq2', action='store')9PARSER.add_argument("-filter", help="produces dotplot where diagonals are capitalised and other letters arent", action="store_true")10PARSER.add_argument("-palindrome", help="produces dotplot where letters are repalced with ascii characters and palindromes are checked in both diagonal directions", action="store_true")11ARGS = PARSER.parse_args()12def prepare_filtering(matrix, seq1, seq2):13 '''14 Determines which type of filtering should occur15 depending on arguments passed on command line.16 Iterates through matrix to access each value17 in the matrix18 '''19 print_matrix = [[" " for x in range(len(seq1))] for y in range(len(seq2))]20 column_limit = len(seq1) - 121 row_limit = len(seq2) - 122 for row in range(len(seq2)):23 for column in range(len(seq1)):24 if ARGS.compliment:25 seq1_col = seq1[column]26 seq2_row = seq2[row]27 print_matrix = compliment_filtering(seq1_col, seq2_row, row, column, print_matrix)28 else:29 value = matrix[row][column]30 if value != " ":31 if ARGS.palindrome:32 print_matrix = palindrome_filtering(value, row, row_limit, column, column_limit, matrix, print_matrix)33 else:34 print_matrix = filtering(value, row, row_limit, column, column_limit, matrix, print_matrix)35 return print_matrix36def filtering(value, row, row_lim, column, column_lim, matrix, print_matrix):37 '''38 compares the next diagonal positions in the matrix,39 forwards 1 and backwards 1 to calculate diagnoals40 '''41 if row == 0 and column != column_lim:42 next = matrix[row + 1][column + 1]43 print_matrix = single_choice(next, value, row, column, print_matrix)44 elif row == row_lim and column != 0:45 prev = matrix[row - 1][column - 1]46 print_matrix = single_choice(prev, value, row, column, print_matrix)47 elif row == 0 and column == column_lim or row == row_lim and column == 0:48 print_matrix = edit_matrix_no_match(value, row, column, print_matrix)49 elif column == 0 and row != 0 or column == 0 and row != row_lim:50 next = matrix[row + 1][column + 1]51 print_matrix = single_choice(next, value, row, column, print_matrix)52 elif column == column_lim and row != 0 or column == column_lim and row != row_lim:53 prev = matrix[row - 1][column - 1]54 print_matrix = single_choice(prev, value, row, column, print_matrix)55 elif column != 0 or column != column_lim and row != 0 and row != row_lim:56 next = matrix[row + 1][column + 1]57 previous = matrix[row - 1][column - 1]58 print_matrix = double_choice(next, previous, value, row, column, print_matrix)59 return print_matrix60def palindrome_filtering(value, row, row_limit, column, column_limit, matrix, print_matrix):61 '''62 compares forwards and backwards one63 along both diagonals in order to64 calculate palindromes65 '''66 if row == 0 and column == 0:67 next_f = matrix[row + 1][column + 1]68 print_matrix = single_choice(next_f, value, row, column, print_matrix)69 elif row == 0 and column == column_limit:70 n_p = matrix[row + 1][column - 1]71 print_matrix = single_choice_pal(n_p, value, row, column, print_matrix)72 elif row == row_limit and column == column_limit:73 prev_f = matrix[row - 1][column - 1]74 print_matrix = single_choice(prev_f, value, row, column, print_matrix)75 elif row == row_limit and column == 0:76 previous_p = matrix[row - 1][column + 1]77 print_matrix = single_choice_pal(previous_p, value, row, column, print_matrix)78 elif row != 0 and column == 0 or row != row_limit and column == 0:79 next_f = matrix[row + 1][column + 1]80 previous_p = matrix[row - 1][column + 1]81 print_matrix = double_choice_pal(next_f, previous_p, value, row, column, print_matrix)82 elif row == 0 and column != 0 or row == 0 and column != column_limit:83 next_f = matrix[row + 1][column + 1]84 next_p = matrix[row + 1][column - 1]85 print_matrix = double_choice_pal(next_f, next_p, value, row, column, print_matrix)86 elif row != 0 and column == column_limit or row != row_limit and column == column_limit:87 previous_f = matrix[row - 1][column - 1]88 next_p = matrix[row + 1][column - 1]89 print_matrix = double_choice_pal(previous_f, next_p, value, row, column, print_matrix)90 elif row == row_limit and column != 0 or row == row_limit and column != column_limit:91 prev_f = matrix[row - 1][column - 1]92 prev_p = matrix[row - 1][column + 1]93 print_matrix = double_choice_pal(prev_f, prev_p, value, row, column, print_matrix)94 elif row != 0 and row != row_limit and column != 0 and column != column_limit:95 next_f = matrix[row + 1][column + 1]96 next_p = matrix[row + 1][column - 1]97 prev_f = matrix[row - 1][column - 1]98 prev_p = matrix[row - 1][column + 1]99 print_matrix = quad_choice(next_f, next_p, prev_f, prev_p, value, row, column, print_matrix)100 return print_matrix101def compliment_filtering(seq1_c, seq2_r, row, col, print_matrix):102 '''103 matches complimentary base pairs104 in sequence provided and indicates105 these matches106 '''107 if seq2_r == 'A' and seq1_c == 'T' or seq2_r == 'A' and seq1_c == 'U':108 print_matrix[row][col] = chr(92)109 elif seq2_r == 'T' and seq1_c == 'A' or seq2_r == 'U' and seq1_c == 'A':110 print_matrix[row][col] = chr(92)111 elif seq2_r == 'C' and seq1_c == 'G':112 print_matrix[row][col] = chr(92)113 elif seq2_r == 'G' and seq1_c == 'C':114 print_matrix[row][col] = chr(92)115 return print_matrix116def edit_matrix_match(val, row, col, print_matrix):117 '''118 filters what to edit in the matrix119 if there is a match depending120 on arguments passed. Default is ascii121 '''122 if ARGS.filter or ARGS.colour:123 print_matrix[row][col] = val124 elif ARGS.basic:125 print_matrix[row][col] = val126 else:127 print_matrix[row][col] = chr(92)128 return print_matrix129def edit_matrix_no_match(val, row, col, print_matrix):130 '''131 Filters what to edit in the matrix132 if there is no match, depending133 on arguments passed. Default is ascii134 '''135 if ARGS.filter or ARGS.colour:136 val = val.lower()137 if ARGS.colour:138 print_matrix[row][col] = Fore.BLACK + val + Style.RESET_ALL139 elif ARGS.filter:140 print_matrix[row][col] = val141 elif ARGS.basic:142 print_matrix[row][col] = val143 else:144 print_matrix[row][col] = chr(46)145 return print_matrix146def edit_matrix_match_pal(row, col, print_matrix):147 '''148 edits matrix if palindrome found149 on opposite diagonal150 '''151 print_matrix[row][col] = chr(47)152 return print_matrix153def single_choice(direction, val, row, col, print_matrix):154 '''155 calculates if there is a match156 diagnoally in one direction157 '''158 if direction != ' ':159 print_matrix = edit_matrix_match(val, row, col, print_matrix)160 else:161 print_matrix = edit_matrix_no_match(val, row, col, print_matrix)162 return print_matrix163def single_choice_pal(direction, val, row, col, print_matrix):164 '''165 calculates if there is match166 on reverse diagonal in one167 direction168 '''169 if direction != ' ':170 print_matrix = edit_matrix_match_pal(row, col, print_matrix)171 else:172 print_matrix = edit_matrix_no_match(val, row, col, print_matrix)173 return print_matrix174def double_choice(direction, direction_opposite, val, row, col, print_matrix):175 '''176 calculates if there is a match177 in 2 directions diagonally178 '''179 if direction != ' ' or direction_opposite != ' ':180 print_matrix = edit_matrix_match(val, row, col, print_matrix)181 elif direction == ' ' and direction_opposite == ' ':182 print_matrix = edit_matrix_no_match(val, row, col, print_matrix)183 return print_matrix184def double_choice_pal(direction, direction2, val, row, col, print_matrix):185 '''186 calculates if there is a match187 in 2 directions for palindrome188 indetification189 '''190 if direction != " " and direction2 == " ":191 print_matrix = edit_matrix_match(val, row, col, print_matrix)192 elif direction == " " and direction2 != " ":193 print_matrix = edit_matrix_match_pal(row, col, print_matrix)194 else:195 print_matrix = edit_matrix_no_match(val, row, col, print_matrix)196 return print_matrix197def quad_choice(next_f, next_p, prev_f, prev_p, val, row, col, print_matrix):198 '''199 calculates if there is a match200 in 4 directions201 '''202 if next_f == " " and next_p == " " and prev_f == " " and prev_p == " ":203 print_matrix = edit_matrix_no_match(val, row, col, print_matrix)204 elif next_f != " " or prev_f != " " and next_p == " " and prev_p == " ":205 print_matrix = edit_matrix_match(val, row, col, print_matrix)206 elif next_f == " " and prev_f == " " and next_p != " " or prev_p != " ":207 print_matrix = edit_matrix_match_pal(row, col, print_matrix)...
2048Game4X4.py
Source:2048Game4X4.py
1from random import randint2matrix = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]3print_matrix = [['','','',''],['','','',''],['','','',''],['','','','']]4num_list = [2,2,4,2,2,2,2]5def newnum():6 while True:7 row = randint(0,3)8 clm = randint(0,3)9 num = num_list[randint(0,3)]10 if matrix[row][clm]==0:11 matrix[row][clm] = num12 break13def result():14 for i in range(4):15 for j in range(4):16 if matrix[i][j]==0:17 print_matrix[i][j] = ' '18 else:19 l = str(matrix[i][j])20 if len(l)==1:21 print_matrix[i][j] = l+' '22 elif len(l)==2:23 print_matrix[i][j] = l+' '24 elif len(l)==3:25 print_matrix[i][j] = l+' '26 else:27 print_matrix[i][j] = l28 print(f'[{print_matrix[0][0]}|{print_matrix[0][1]}|{print_matrix[0][2]}|{print_matrix[0][3]}]')29 print(f'[{print_matrix[1][0]}|{print_matrix[1][1]}|{print_matrix[1][2]}|{print_matrix[1][3]}]')30 print(f'[{print_matrix[2][0]}|{print_matrix[2][1]}|{print_matrix[2][2]}|{print_matrix[2][3]}]')31 print(f'[{print_matrix[3][0]}|{print_matrix[3][1]}|{print_matrix[3][2]}|{print_matrix[3][3]}]\n')32def checkwin():33 for i in range(4):34 for j in range(4):35 if matrix[i][j]==2048:36 print('----------You Win----------')37 exit()38 return True39def notloose():40 for i in range(4):41 for j in range(4):42 if matrix[i][j]==0:43 return True44 for i in range(4):45 for j in range(3):46 if matrix[i][j]==matrix[i][j+1]:47 return True48 for i in range(3):49 for j in range(4):50 if matrix[i][j]==matrix[i+1][j]:51 return True52 print('----------Game Over----------')53 exit()54def addindentleft():55 for i in range(4):56 for j in range(3):57 if matrix[i][j]==matrix[i][j+1] and matrix[i][j]!=0:58 matrix[i][j]*=259 matrix[i][j+1] = 060 for i in range(3,-1,-1):61 for j in range(3,0,-1):62 if matrix[i][j-1]==0:63 matrix[i][j-1] = matrix[i][j]64 matrix[i][j] = 065def addindentright():66 for i in range(4):67 for j in range(3):68 if matrix[i][j+1]==matrix[i][j] and matrix[i][j+1]!=0:69 matrix[i][j+1]*=270 matrix[i][j] = 071 for i in range(4):72 for j in range(3):73 if matrix[i][j+1]==0:74 matrix[i][j+1] = matrix[i][j]75 matrix[i][j] = 076def moveleft():77 addindentleft()78 addindentleft()79 addindentleft()80 addindentleft()81def moveright():82 addindentright()83 addindentright()84 addindentright()85 addindentright()86def transposeleftup():87 for i in range(4):88 for j in range(4):89 temp_matrix[i][j] = matrix[j][i]90def transposerightup():91 temp_matrix[0][0] = matrix[3][3]92 temp_matrix[0][1] = matrix[2][3]93 temp_matrix[0][2] = matrix[1][3]94 temp_matrix[0][3] = matrix[0][3]95 temp_matrix[1][0] = matrix[3][2]96 temp_matrix[1][1] = matrix[2][2]97 temp_matrix[1][2] = matrix[1][2]98 temp_matrix[1][3] = matrix[0][2]99 temp_matrix[2][0] = matrix[3][1]100 temp_matrix[2][1] = matrix[2][1]101 temp_matrix[2][2] = matrix[1][1]102 temp_matrix[2][3] = matrix[0][1]103 temp_matrix[3][0] = matrix[3][0]104 temp_matrix[3][1] = matrix[2][0]105 temp_matrix[3][2] = matrix[1][0]106 temp_matrix[3][3] = matrix[0][0]107 108print('************Welcome to 2048 Game************')109print("----------Press (u or ') for slide up or (d or ;) for slide down or (r or /) for slide right or (l or .) for slide left.----------")110newnum()111newnum()112result()113while checkwin():114 if notloose():115 choice = input('Enter move : ')116 ask = randint(1,50)117 if choice in ('u',"'"):118 temp_matrix = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]119 transposeleftup()120 matrix = list(temp_matrix)121 moveleft()122 temp_matrix = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]123 transposeleftup()124 matrix = list(temp_matrix)125 if ask not in (1,10,20,40,45,50):126 newnum()127 result()128 elif choice in ('r','/'):129 moveright()130 if ask not in (1,10,20,40,45,50):131 newnum()132 result()133 elif choice in ('l','.'):134 moveleft()135 if ask not in (1,10,20,40,45,50):136 newnum()137 result()138 elif choice in ('d',';'):139 temp_matrix = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]140 transposerightup()141 matrix = list(temp_matrix)142 moveleft()143 temp_matrix = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]144 transposerightup()145 matrix = list(temp_matrix)146 if ask not in (1,10,20,40,45,50):147 newnum()148 result()149 else:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!