« Prev 1 2 3 4 5 6 7 8 9 10 Next »

Matrix Script

Create Date: March 31, 2019 at 11:25 AM         Tag: PYTHON         Author Name: Sun, Charles

Neo has a complex matrix script. The matrix script is a  X  grid of strings. It consists of alphanumeric characters, spaces and symbols (!,@,#,$,%,&).

To decode the script, Neo needs to read each column and select only the alphanumeric characters and connect them. Neo reads the column from top to bottom and starts reading from the leftmost column.

If there are symbols or spaces between two alphanumeric characters of the decoded script, then Neo replaces them with a single space '' for better readability.

Neo feels that there is no need to use 'if' conditions for decoding.

Alphanumeric characters consist of: [A-Z, a-z, and 0-9].

Input Format

The first line contains space-separated integers  (rows) and  (columns) respectively. 
The next  lines contain the row elements of the matrix script.

Constraints

Note: A  score will be awarded for using 'if' conditions in your code.

Output Format

Print the decoded matrix script.

Sample Input 0

7 3
Tsi
h%x
i #
sM 
$a 
#t%
ir!

Sample Output 0

This is Matrix#  %!

Explanation 0

The decoded script is:

This$#is% Matrix#  %!

Neo replaces the symbols or spaces between two alphanumeric characters with a single space   ' ' for better readability.

So, the final decoded script is:

This is Matrix#  %!

Method 1: doesn't pass the test, but the result looks OK. Note that,

They use if themselves in main definition:

if __name__ == '__main__':

Romove it and it will work.

#!/bin/python3

import math
import os
import random
import re
import sys



if __name__ == '__main__':
    nm = input().split()

    n = int(nm[0])

    m = int(nm[1])

    matrix = []

    for _ in range(n):
        matrix_item = input()
        matrix.append(matrix_item)
    print(re.sub(r"(\w)(\W)+(\w)",
          r"\1 \3",
          "".join([u for t in zip(*matrix) for u in t])))

Method 2:

#!/bin/python3

import math
import os
import random
import re
import sys




nm = input().split()

n = int(nm[0])

m = int(nm[1])

matrix = []

for _ in range(n):
    matrix_item = input()
    matrix.append(matrix_item)
res = ""
for z in zip(*matrix):
    res += "".join(z)

print(re.sub(r"(?<=\w)([^\w]+)(?=\w)", " ", res))

method 3:

#!/bin/python3

import math
import os
import random
import re
import sys


n, m = map(int, input().split())
arr = ''.join([''.join(t) for t in zip(*[input() for _ in range(n)])])
print(re.sub(r'\b[^a-zA-Z0-9]+\b', r' ', arr))

method 4:

#!/bin/python3

import math
import os
import random
import re
import sys

count = 0
decode = ''
val = list(map(int, input().split()))
input_val = [input() for x in range(val[0])]
while count != val[1]:
    for y in input_val:
        decode += y[count]
    count += 1
print(re.sub(r'(?<=([a-zA-Z0-9]))[\s$#%&]+(?=[a-zA-Z0-9])',' ', decode))

method 5:

#!/bin/python3

import math
import os
import random
import re
import sys

print(re.sub(r'\b[^\w\d]+\b',' ', ''.join([''.join(t) for t in zip(*[input().replace('\r','') for x in range(int(input().split()[0]))])])))

regex   = re.compile(r'(?<=\w)(\W+)(?=\w)')
N, M    = (int(num) for num in input().split())
encoded = [input().rstrip('\r') for __ in range(N)]
decoded = ''.join(row[letter] for letter in range(M) 
                              for row in encoded)
print(regex.sub(' ', decoded))

method 6:

#!/bin/python3

import math
import os
import random
import re
import sys

n,m=map(int,input().split())
new=[(input()+' '*m)[:m] for i in range(n)]
string=''.join(list(map(lambda *x:''.join(x),*new)))
print(re.sub(r'\b\W+\b',' ',string))

 

New Comment

Validating Postal Codes

Create Date: March 31, 2019 at 10:58 AM         Tag: PYTHON         Author Name: Sun, Charles

A valid postal code  have to fullfil both below requirements:

  1.  must be a number in the range from  to  inclusive.
  2.  must not contain more than one alternating repetitive digit pair.

Alternating repetitive digits are digits which repeat immediately after the next digit. In other words, an alternating repetitive digit pair is formed by two equal digits that have just a single digit between them.

For example:

121426 # Here, 1 is an alternating repetitive digit.
523563 # Here, NO digit is an alternating repetitive digit.
552523 # Here, both 2 and 5 are alternating repetitive digits.

Your task is to provide two regular expressions regex_integer_in_range and regex_alternating_repetitive_digit_pair. Where:

regex_integer_in_range should match only integers range from  to  inclusive

regex_alternating_repetitive_digit_pair should find alternating repetitive digits pairs in a given string.

Both these regular expressions will be used by the provided code template to check if the input string  is a valid postal code using the following expression:

(bool(re.match(regex_integer_in_range, P)) 
and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)

Input Format

Locked stub code in the editor reads a single string denoting  from stdin and uses provided expression and your regular expressions to validate if  is a valid postal code.

Output Format

You are not responsible for printing anything to stdout. Locked stub code in the editor does that.

Sample Input 0

110000

Sample Output 0

False

Explanation 0

1 1 0000 : (0, 0) and (0, 0) are two alternating digit pairs. Hence, it is an invalid postal code.

Note: 
A score of  will be awarded for using 'if' conditions in your code. 
You have to pass all the testcases to get a positive score.

regex_integer_in_range = r"^[1-9][\d]{5}$"	# Do not delete 'r'.
regex_alternating_repetitive_digit_pair = r"(\d)(?=\d\1)"	# Do not delete 'r'.


import re
P = input()

print (bool(re.match(regex_integer_in_range, P)) 
and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)

the first parentheses-delimited expression inside of the regex. It will return the number of alternate matching pattern which should be at max 1. SO the condition is of <2. re.findall function will take a pattern and a string. So we matches the digit \d. (?=...) Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

Findall Return all non-overlapping matches of pattern in string, as a list of strings.

This non-overlapping is what is called string consuming. Once a match is found, the three characters are not longer used to continue the search, in that way the string was consumed. With the look ahead groupin (?=...) you do not consume the string.

An example with: r'(\d)\d\1', '111100'

finds 111 which matches, saves it, and continue to the rest of the string which will be '100', because it consumed the initial match. Another good way to check this is with: '111111', it will match twice '1'.

On the other hand, with looking ahead: r'(\d)(?=\d\1)', '111100'

it matches the first '111' but doesnt consume the match, so it continues the search to '11100'.

New Comment

Validating Credit Card Numbers

Create Date: March 31, 2019 at 10:29 AM         Tag: PYTHON         Author Name: Sun, Charles

You and Fredrick are good friends. Yesterday, Fredrick received  credit cards from ABCD Bank. He wants to verify whether his credit card numbers are valid or not. You happen to be great at regex so he is asking for your help!

A valid credit card from ABCD Bank has the following characteristics: 

â–º It must start with a ,  or . 
â–º It must contain exactly  digits. 
â–º It must only consist of digits (-). 
â–º It may have digits in groups of , separated by one hyphen "-". 
â–º It must NOT use any other separator like ' ' , '_', etc. 
â–º It must NOT have  or more consecutive repeated digits.

Examples:

Valid Credit Card Numbers

4253625879615786
4424424424442444
5122-2368-7954-3214

Invalid Credit Card Numbers

42536258796157867       #17 digits in card number → Invalid 
4424444424442444        #Consecutive digits are repeating 4 or more times → Invalid
5122-2368-7954 - 3214   #Separators other than '-' are used → Invalid
44244x4424442444        #Contains non digit characters → Invalid
0525362587961578        #Doesn't start with 4, 5 or 6 → Invalid

Input Format

The first line of input contains an integer . 
The next  lines contain credit card numbers.

Constraints

Output Format

Print 'Valid' if the credit card number is valid. Otherwise, print 'Invalid'. Do not print the quotes.

Sample Input

6
4123456789123456
5123-4567-8912-3456
61234-567-8912-3456
4123356789123456
5133-3367-8912-3456
5123 - 3567 - 8912 - 3456

Sample Output

Valid
Valid
Invalid
Valid
Invalid
Invalid

Explanation

4123456789123456 : Valid 
5123-4567-8912-3456 : Valid 
61234--8912-3456 : Invalid, because the card number is not divided into equal groups of . 
4123356789123456 : Valid 
51-67-8912-3456 : Invalid, consecutive digits  is repeating  times. 
5123456789123456 : Invalid, because space '  ' and - are used as separators.

method 1:

import re
pattern = re.compile(r"^(?!.*(\d)(-?\1){3})[456]\d{3}(?:-?\d{4}){3}$")
for _ in range(int(input())):
    print("Valid" if pattern.search(input().strip()) else "Invalid")

method 2:

import re
TESTER = re.compile(
    r"^"
    r"(?!.*(\d)(-?\1){3})"
    r"[456]"
    r"\d{3}"
    r"(?:-?\d{4}){3}"
    r"$")
[print("Valid" if TESTER.search(s) else "Invalid") for s in [input().strip() for _ in range(int(input().strip()))]]

 

New Comment
« Prev 1 2 3 4 5 6 7 8 9 10 Next »