In: Computer Science
PYHTON
A company uses codes to represent its products, for example ABC2475A5R-14. Valid codes must have:
At least 10 characters (some codes have more than 10 characters)
Positions 4 through 7 must be digits (and represents the country in which the product will be sold)
The character in the 10th position must be a capital letter and represents the security level of the product.
Write a Python program that will read 10 product codes from a text file (Codes.txt - attached below). Determine if each conforms to the rules listed above:
If it does conform, print a heading: Valid Code(s) are: and list the codes that are valid. If it does not conform, print a heading: Invalid Code(s) are: and list the codes that area invalid. Be sure to test all possible combinations.
Further, if the code is valid, due to new government security laws, products with a security level of R (restricted) are no longer to be sold in countries with a country code of 2000 or higher. Output a heading: Invalid Restricted Code(s) are: and list the codes that are invalid in case you encounter any products that violate these new laws.
.txt file
XYZ2755R-14
RST1234A6A-12
UVW24a6R7R-13
PQR3999F85-11
STI1281J9A-04
FOR2561T4R-54
BID2075U3R-55
AGA1475P1B01
JBT2175E5X-04
KAM1145X2R-05
PYTHON
Code.py
#importing regex library as I have used regex in my code for matching
import re
#three list for storing different types of codes
valid=[]
invalid=[]
restricted=[]
#opening a txt file in read mode
f = open("Codes.txt", "r")
for x in f:
str=x;
s1 = str[3:7] #Cutoff the country code part of string from the given code and take in s1 string for further matching
if (len(str)<10): # first matching that code is of more than or equal to of length 10 or not
invalid.append(str) # if not add it to invalid list
elif (not(re.search("^[0-9]+$", s1))): #if length is ok then check all country codes are numeric or not
invalid.append(str) # if not add it to invalid
elif (not(re.search("^[A-Z]+$", str[9]))): #similary checking 10th character is capital or not
invalid.append(str) # if not add it to invalid
else:
valid.append(str) # else it is a valid code
# if valid then check Security code is R or not if yes add it to restricted list by checking its country code
if (str[9]=="R" and int(s1)>2000):
restricted.append(str)
f.close() # close the file
#print the result
print("\nValid Code(s) are:\n")
for a in valid:
print(a)
print("\nInvalid Code(s) are:\n")
for a in invalid:
print(a)
print("\nInvalid Restricted Code(s) are:\n")
for a in restricted:
print(a)
Codes.txt
XYZ2755R-14
RST1234A6A-12
UVW24a6R7R-13
PQR3999F85-11
STI1281J9A-04
FOR2561T4R-54
BID2075U3R-55
AGA1475P1B01
JBT2175E5X-04
KAM1145X2R-05
Snaps of Code and Output: