User:Ptomusk: Difference between revisions

From ICO wiki
Jump to navigationJump to search
Line 24: Line 24:
</source>
</source>
Link originaalpostitusele: [[Bash_quests_2013#Teine]]
Link originaalpostitusele: [[Bash_quests_2013#Teine]]
====Quest 30====
<source lang="python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Luua isikukoodi parser ja õigsuse kontroll.
#Sisendiks fail kus igal real on isikukood, mis võib olla õige või vale.
#Väljundiks on fail kus on õiged isikukoodid kus kontrollsumma klapib ning kuupäev on korrektne (aastas 12 kuud ning iga kuu päevade arv sobiv).
#
#NB! Kuupäeva õigsuse kontrollimiseks kasutage datetime.strptime funktsiooni ja uuesti vormindamiseks datetime.strftime funktsiooni
#
#Autor: Peeter Tomusk
#Useful sources
#Isikukoodi spetsifikatsiooni (tasuta) kirjeldus - http://et.wikipedia.org/wiki/Isikukood
##Import modules
import sys
import os
from string import rstrip
import time
#from calendar import isleap
##Some initial variables
helpmessage="Usage: %s [input_file_name] [[--debug]]" % sys.argv[0]
helplongmessage="""
Test the validity of Estonian ID-codes in a file and print properly formatted lines with the birth-date and gender on screen
"""
debug=False
input_file=""
seed={1:(1,2,3,4,5,6,7,8,9,1),2:(3,4,5,6,7,8,9,1,2,3)}
##Parse arguments
#Check that we have arguments
if len(sys.argv)==1:
sys.stderr.write("Invalid number of arguments!\n\n%s\n" % helpmessage)
sys.exit(4)
#Loop trough all arguments except the first one (scripts own name)
while len(sys.argv[1:])>0:
#If the argument is help
if sys.argv[1]=="--help":
print helpmessage+helplongmessage
sys.exit(0)
#If the argument is debug
if sys.argv[1]=="--debug":
debug=True
del sys.argv[1]
#In other cases presume it's a filename
else:
#Test if we already have a filename
if len(input_file)>0:
sys.stderr.write("Input file \"%s\" is already specified and filename \"%s\" is one too many\ncurrently only one file is supported, sorry!\n" % (input_file,sys.argv[1]))
sys.exit(2)
#Test if the file exists
elif os.path.isfile(sys.argv[1]):
input_file=sys.argv[1]
del sys.argv[1]
#If the doesn't exists
else:
sys.stderr.write("Input file \"%s\" doesn't exist!\n" % sys.argv[1])
sys.exit(1)
##Do some actual work
#Test if we can read the file
if os.access(input_file,os.R_OK):
#and read it's contents to a list
f=open(input_file,"r")
input_data=f.readlines()
f.close
#Or give an error
else:
sys.stderr.write("Cannot read file \"%s\"\n" % input_file)
sys.exit(3)
#For each line in the file
for code in input_data:
code=rstrip(code,"\n")
#Find the gender
if int(code[0])%2==0:
gender="naine"
elif int(code[0])%2==1:
gender="mees"
#Find the appropriate number of hundreds for the birthyear
cents=18+(((int(code[0])%2)+int(code[0]))/3)
#Check if the date is a proper value
try:
birthdate=time.strftime("%Y.%m.%d",time.strptime("%s%s.%s.%s" % (cents,code[1:3],code[3:5],code[5:7]),"%Y.%m.%d"))
except ValueError as error:
if debug:
print "%s is wrong, because %s" % (code,error)
continue
#Verify the code against it's checksum
for seed_type in 1,2:
#Initialise a variable for the seed multiplication sums
codesum=0
#For each non-checksum element in the code
for index in range(10):
#Multiply it with the current seed and add the result
codesum=codesum+(seed[seed_type][index]*int(code[index]))
#Calculate the checksum
checksum=codesum%11
#If checksum is 10
if checksum==10:
if seed_type==1:
continue
elif seed_type==2:
checksum=0
#If the checksum is not 10 and matches the original
if checksum!=10 and checksum==int(code[-1]):
print "%s - %s - %s" % (code,birthdate,gender)
break
else:
if debug:
print "%s is wrong, because the checksum is wrong" % code
</source>

Revision as of 13:35, 18 October 2013

Info

Erinevate ainete raames lisatud sisu

Skriptimiskeeled (I387)

Tunnis lahendatud näited

Teine

  1. Teha skript, mis küsib kasutajalt kataloogi nime ja siis väljastab kõik (tavalised) failid/kaustad, mis seal kataloogis asuvad 3p

Ptomusk 14:29, 29 September 2013 (EEST)

#!/bin/bash
_short_help="`basename $0` [DIRECTORY]"
_long_help="Output the files in the specified directory"
if [ "$1" = '--help' ]; then
        echo $_short_help
        echo $_long_help
        exit 0
elif [ -d "$1" ]; then
	find "$1/" -maxdepth 1 -type f
else
	echo "No such directory!"
	echo $_short_help
	exit 1
fi

Link originaalpostitusele: Bash_quests_2013#Teine

Quest 30

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Luua isikukoodi parser ja õigsuse kontroll.
#Sisendiks fail kus igal real on isikukood, mis võib olla õige või vale.
#Väljundiks on fail kus on õiged isikukoodid kus kontrollsumma klapib ning kuupäev on korrektne (aastas 12 kuud ning iga kuu päevade arv sobiv).
#
#NB! Kuupäeva õigsuse kontrollimiseks kasutage datetime.strptime funktsiooni ja uuesti vormindamiseks datetime.strftime funktsiooni
#
#Autor: Peeter Tomusk

#Useful sources
#Isikukoodi spetsifikatsiooni (tasuta) kirjeldus - http://et.wikipedia.org/wiki/Isikukood

##Import modules
import sys
import os
from string import rstrip
import time
#from calendar import isleap

##Some initial variables
helpmessage="Usage: %s [input_file_name] [[--debug]]" % sys.argv[0]
helplongmessage="""

Test the validity of Estonian ID-codes in a file and print properly formatted lines with the birth-date and gender on screen
"""
debug=False
input_file=""
seed={1:(1,2,3,4,5,6,7,8,9,1),2:(3,4,5,6,7,8,9,1,2,3)}

##Parse arguments
#Check that we have arguments
if len(sys.argv)==1:
	sys.stderr.write("Invalid number of arguments!\n\n%s\n" % helpmessage)
	sys.exit(4)
#Loop trough all arguments except the first one (scripts own name)
while len(sys.argv[1:])>0:
	#If the argument is help
	if sys.argv[1]=="--help":
		print helpmessage+helplongmessage
		sys.exit(0)
	#If the argument is debug
	if sys.argv[1]=="--debug":
		debug=True
		del sys.argv[1]
	#In other cases presume it's a filename 
	else:
		#Test if we already have a filename
		if len(input_file)>0:
			sys.stderr.write("Input file \"%s\" is already specified and filename \"%s\" is one too many\ncurrently only one file is supported, sorry!\n" % (input_file,sys.argv[1]))
			sys.exit(2)
		#Test if the file exists
		elif os.path.isfile(sys.argv[1]):
			input_file=sys.argv[1]
			del sys.argv[1]
		#If the doesn't exists
		else:
			sys.stderr.write("Input file \"%s\" doesn't exist!\n" % sys.argv[1])
			sys.exit(1)

##Do some actual work
#Test if we can read the file
if os.access(input_file,os.R_OK):
	#and read it's contents to a list
	f=open(input_file,"r")
	input_data=f.readlines()
	f.close 
#Or give an error
else:
	sys.stderr.write("Cannot read file \"%s\"\n" % input_file)
	sys.exit(3)

#For each line in the file
for code in input_data:
	code=rstrip(code,"\n")
	#Find the gender
	if int(code[0])%2==0:
		gender="naine"
	elif int(code[0])%2==1:
		gender="mees"
	#Find the appropriate number of hundreds for the birthyear
	cents=18+(((int(code[0])%2)+int(code[0]))/3)
	#Check if the date is a proper value
	try:
		birthdate=time.strftime("%Y.%m.%d",time.strptime("%s%s.%s.%s" % (cents,code[1:3],code[3:5],code[5:7]),"%Y.%m.%d"))
	except ValueError as error:
		if debug:
			print "%s is wrong, because %s" % (code,error)
		continue
	#Verify the code against it's checksum
	for seed_type in 1,2:
		#Initialise a variable for the seed multiplication sums
		codesum=0
		#For each non-checksum element in the code
		for index in range(10):
			#Multiply it with the current seed and add the result
			codesum=codesum+(seed[seed_type][index]*int(code[index]))
		#Calculate the checksum
		checksum=codesum%11
		#If checksum is 10
		if checksum==10:
			if seed_type==1:
				continue
			elif seed_type==2:
				checksum=0
		#If the checksum is not 10 and matches the original
		if checksum!=10 and checksum==int(code[-1]):
			print "%s - %s - %s" % (code,birthdate,gender)
			break
	else:
		if debug:
			print "%s is wrong, because the checksum is wrong" % code