-
Notifications
You must be signed in to change notification settings - Fork 5
Homeworks expired
Read it and send me it to my email `[email protected]` or `[email protected]`
Task: From input or from random function print the big digits. Help is the shape of bigdigits.
`Zero = [" *** ",`
`" * * ",`
`"* *",`
`"* *",`
`"* *",`
`" * * ",`
`" *** "]`
`One = [" * ", "** ", " * ", " * ", " * ", " * ", "***"]`
`Two = [" *** ", "* *", "* * ", " * ", " * ", "* ", "*****"]`
`Three = [" *** ", "* *", " *", " ** ", " *", "* *", " *** "]`
`Four = [" * ", " ** ", " * * ", "* * ", "******", " * ",`
`" * "]`
`Five = ["*****", "* ", "* ", " *** ", " *", "* *", " *** "]`
`Six = [" *** ", "* ", "* ", "**** ", "* *", "* *", " *** "]`
`Seven = ["*****", " *", " * ", " * ", " * ", "* ", "* "]`
`Eight = [" *** ", "* *", "* *", " *** ", "* *", "* *", " *** "]`
`Nine = [" ****", "* *", "* *", " ****", " *", " *", " *"]`
`Digits = [Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine]`
Example
`import random`
`def get_int(msg, minimum, default):`
`while True:`
`try:`
`line = input(msg)`
`if not line and default is not None:`
`return default`
`i = int(line)`
`if i < minimum:`
`print("must be >=", minimum)`
`else:`
`return i`
`except ValueError as err:`
`print(err)`
`rows = get_int("rows: ", 1, None)`
`columns = get_int("columns: ", 1, None)`
`minimum = get_int("minimum (or Enter for 0): ", -1000000, 0)`
`default = 1000`
`if default < minimum:`
`default = 2 * minimum`
`maximum = get_int("maximum (or Enter for " + str(default) + "): ",`
`minimum, default)`
`row = 0`
`while row < rows:`
`line = ""`
`column = 0`
`while column < columns:`
`i = random.randint(minimum, maximum)`
`s = str(i)`
`while len(s) < 10:`
`s = " " + s`
`line += s`
`column += 1`
`print(line)`
`row += 1`
Based on this generate grid - all random - also no. of rows and no. of collumns
Try this **[The string](https://github.com/MartaVohnoutovaBukovec/IOS-655-Python-a-Bash/blob/master/string-input.txt)** *”0100100100100000011000010110110100100000011010000110111101101110011011110111001001100101011001000010000001110100011011110010000001110111011001010110110001100011011011110110110101100101001000000111100101101111011101010010000001100001011011000110110000100000011010010110111000100000011101000110100001100101001000000101000001111001011101000110100001101111011011100010000001100011011011110111010101110010011100110110010100111010”
or *”010101100110000101101100011000010111001000100000010011010110111101110010011001110110100001110101011011000110100101110011001000000101011001100001011011000110000101110010001000000100010001101111011010000110000101100101011100100110100101110011”
Every letter has 8 digits and represents one letter in binary.
[[https://github.com/MartaVohnoutovaBukovec/IOS-655-Python-a-Bash/blob/master/IOS%20655%20Python%20a%20Bash/diveintopython3-master/examples/Vigenere_table.jpg]
[Vigenere table]]
# Module mCipher
# Vigerere cipher function
def vigenere(s,k,en):
s,k=s.replace(" ","").upper(),k.replace(" ","").upper() # remove all spaces and chenge to all capitals - for string and key
out_s = ""
if len(s) > len(k):
k = (k * len(s))[0:len(s)] # add key to the length of string
else:
k = k[:len(s)]
if en:
for i in range(len(s)):
if ord(s[i]) in range(65,91): # outside alphabets let it be as it is
number_ord = ord(s[i]) + ord(k[i]) - 65
if number_ord > 90: # adjust alphabet boundary
number_ord -= 26
else:
number_ord = ord(s[i])
out_s = out_s + chr(number_ord)
else:
for i in range(len(s)):
if ord(s[i]) in range(65,91): # outside alphabets let it be as it is
number_ord = ord(s[i]) - ord(k[i]) + 65
if number_ord < 65: # adjust alphabet boundary
number_ord += 26
else:
number_ord = ord(s[i])
out_s = out_s + chr(number_ord)
return out_s
#print(vigenere("kleinehaarschnittkoch","brinellrockwellvickers",1))
#print(vigenere("LCMVRPSROTCYLYTOBMYGY","brinellrockwellvickers",0))
#print(vigenere("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz","brinellrockwellvickers",1))
#print(vigenere("AQHMDKKQNBJVDKKUHBJDQRAQHMDKKQNB","brinellrockwellvickers",0))
We have a programm **mCipher** with one definition **vigenere** and it is saved in **python library**. We can import it as a module and have three ways.
->>> import mCipher
->>> mCipher.vigenere("I have a cat her name is Tit","Titan",1)
'BPTVRTKTTUXZGAZXQLTVM'
->>> from mCipher import vigenere
->>> vigenere("I have a cat her name is Tit","Titan",1)
''BPTVRTKTTUXZGAZXQLTVM''
->>> from mCipher import vigenere as v
->>> v("BPTVRTKTTUXZGAZXQLTVM","Titan",0)
'IHAVEACATHERNAMEISTIT'
any number base to 10-base
->>> int("cangaroo",36)
963555890856
10-base to 2 (b) (bin), 8 (o) (oct) , 16 (x) (hex) base
->>> format(12456897,"b")
'101111100001001111000001'
or
->>> oct(12456897)
'0o57411701'
Example program
# any base to any base function example
# Function definition is here
def base_to_base(s_in,b_in,b_out):
return str_base(int(str(s_in),b_in),"0123456789abcdefghijklmnopqrstuvwxyz"[:b_out])
def str_base(number, base):
(d,m) = divmod(number, len(base))
if d > 0:
return str_base(d,base)+base[m]
return base[m]
- >>> from base_to_base import *
->>> base_to_base("martavohnoutova",36,19)
'15ie5de50cag2f229bi'
->>> base_to_base("2568",10,16)
'a08'
->>>
With the help of brute force decrypt this message - who will send me the keyword - it is a bonus :-)
ne Ocpn uo idamihtngdea ry wr,ie hl onIpeeddr ea,w ndkawar e,veyO anrm
qyaantuiad nuiocrsvou ue lmffoo gttronloe e Wr—ie hl odIne, dderlna
apynig,pnsdd uny elhretecme aata pngpi s ,Afsoo eonm enegl rtypinap,
rag pngpia m t haycbr meor.doTs ioe smiitvsr Io,mtt urd,eetpp an aig y
tmhmbcardoe r Oo—l tnyi ahsdnon hngtimre o .
for inspiration from Marta it is trans_cipher with key, it is not the brute force
def getKey(item):
return item[1]
def trans_cipher(string,keyword,en):
k = list(enumerate(keyword.upper()))
k = sorted(k, key=itemgetter(1))
keys = [(i,k[i][0]) for i in range(len(k))]
string_en=""
if en:
for i in range(0,len(string),len(keys)):
for j in keys:
try:
string_en += string[i+j[1]]
except IndexError:
pass
else:
keys = sorted(keys,key=getKey)
for i in range(0,len(string),len(keys)):
for j in keys:
try:
string_en += string[i+j[0]]
except IndexError:
pass
return string_en
Look at csv2html.py in the Summerfiled`s book on a page 97 and try to understand it. See csv2html.py
d3= [(“x”,3, “y”,3),(“x”,2, “y”,-1),(“x”,2, “y”,3),(“x”,-1, “y”,0),(“x”,2, “y”,2),(“x”,3, “y”,-1),(“x”,1, “y”,2),(“x”,0, “y”,2),(“x”,1, “y”,0),(“x”,0, “y”,-1),(“x”,0, “y”,1),(“x”,-1, “y”,0),(“x”,1, “y”,-1),(“x”,-1, “y”,1),(“x”,2, “y”,0),(“x”,1, “y”,2),(“x”,-1, “y”,0),(“x”,1, “y”,2),(“x”,-1, “y”,3),(“x”,-1, “y”,2),(“x”,0, “y”,0),(“x”,1, “y”,3),(“x”,2, “y”,0),(“x”,0, “y”,2),(“x”,-1, “y”,-1),(“x”,0, “y”,2),(“x”,2, “y”,3),(“x”,2, “y”,-1),(“x”,2, “y”,0),(“x”,3, “y”,3),(“x”,-1, “y”,0),(“x”,2, “y”,-1),(“x”,0, “y”,-1),(“x”,2, “y”,2),(“x”,-1, “y”,0),(“x”,2, “y”,-1),(“x”,0, “y”,1),(“x”,0, “y”,3),(“x”,3, “y”,1),(“x”,0, “y”,2),(“x”,2, “y”,0),(“x”,0, “y”,2),(“x”,1, “y”,2),(“x”,0, “y”,3),(“x”,1, “y”,0),(“x”,-1, “y”,0),(“x”,-1, “y”,3),(“x”,1, “y”,-1),(“x”,0, “y”,2),(“x”,2, “y”,3),(“x”,-1, “y”,1),(“x”,1, “y”,0),(“x”,2, “y”,3),(“x”,2, “y”,2),(“x”,1, “y”,2),(“x”,0, “y”,-1),(“x”,-1, “y”,1),(“x”,1, “y”,0),(“x”,0, “y”,2),(“x”,3, “y”,3),(“x”,2, “y”,-1),(“x”,1, “y”,3),(“x”,2, “y”,3),(“x”,1, “y”,2),(“x”,3, “y”,0),(“x”,0, “y”,2),(“x”,3, “y”,0),(“x”,0, “y”,-1),(“x”,3, “y”,3),(“x”,1, “y”,3),(“x”,-1, “y”,-1),(“x”,1, “y”,1),(“x”,0, “y”,3),(“x”,3, “y”,-1),(“x”,1, “y”,2),(“x”,1, “y”,0),(“x”,-1, “y”,0),(“x”,2, “y”,3),(“x”,1, “y”,-1),(“x”,0, “y”,0),(“x”,0, “y”,1),(“x”,1, “y”,1),(“x”,-1, “y”,1),(“x”,-1, “y”,0),(“x”,2, “y”,-1),(“x”,1, “y”,-1),(“x”,3, “y”,-1),(“x”,2, “y”,1),(“x”,0, “y”,1),(“x”,1, “y”,1),(“x”,3, “y”,1),(“x”,2, “y”,3),(“x”,1, “y”,3),(“x”,1, “y”,3),(“x”,1, “y”,-1),(“x”,2, “y”,1),(“x”,0, “y”,1),(“x”,3, “y”,0),(“x”,1, “y”,-1),(“x”,3, “y”,-1)]
Here is a program - look at it, or even edit and try and send me the description what the Python program is doing
# image Klara jpeg watermark
# Marta Vohnoutova
from PIL import Image, ImageEnhance
import os
import sys
def reduce_opacity(im, opacity):
"""Returns an image with reduced opacity."""
assert opacity >= 0 and opacity <= 1
if im.mode != 'RGBA':
im = im.convert('RGBA')
else:
im = im.copy()
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alpha)
return im
def watermark(im, mark, position, opacity=1):
"""Adds a watermark to an image."""
if opacity < 1:
mark = reduce_opacity(mark, opacity)
if im.mode != 'RGBA':
im = im.convert('RGBA')
# create a transparent layer the size of the image and draw the
# watermark in that layer.
layer = Image.new('RGBA', im.size, (0,0,0,0))
if position == 'tile':
for y in range(0, im.size[1], mark.size[1]):
for x in range(0, im.size[0], mark.size[0]):
layer.paste(mark, (x, y))
elif position == 'scale':
# scale, but preserve the aspect ratio
ratio = min(
float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
w = int(mark.size[0] * ratio)
h = int(mark.size[1] * ratio)
mark = mark.resize((w, h))
layer.paste(mark, (im.size[0] - w, im.size[1] - h))
else:
layer.paste(mark, position)
# composite the watermark with the layer
return Image.composite(layer, im, layer)
if __name__ == '__main__':
kam="/home/marta/photostruk/klara"
vodoznak = "/home/marta/photostruk/logo/logo_ju.jpeg"
position = "tile"
for root, dirs, files in os.walk(kam):
for file in os.listdir(root):
if file.endswith(".jpg"):
im = Image.open(os.path.join(root, file))
mark = Image.open(vodoznak)
im_watermarked = watermark(im, mark,position, 0.15)
im_watermarked.save(kam+"/" + file + "_watermarked_" + position + ".jpeg")
It means that e.g. "RDBDTQA" has pattern "0,1,2,1,3,4,5" Try to find out in the dictionary the words which corresponds with the pattern.
*** Homework - bonus1 voluntary - Brute force - no key needed
'FCAFLC ORA LWJC WV MLIUU RAEUCU URAELX VAZ ZRPAO UZAVCU. CVMLWUR FPAJCPN.'
*** Homework - bonus2 voluntary - Brute force - key is math.pi without dot -
'gYQ\x11RKSEF\x13\\K\x19VUDSJK\x14Q@SQ]VJ\x13]Y\x19AXW\x18W@Y\\E\x11EPW\\\x19\\Q\x15EXP\x18ZYU[\x1a\x19qZRU[@X\x17HCYBUDP'
*** Homework 11 - intermediate - understand and describe the program with exception handling
```diff
#!/usr/bin/env python3
# Copyright (c) 2008-11 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. It is provided for educational
# purposes and is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
import string
import sys
class InvalidEntityError(Exception): pass
class InvalidNumericEntityError(InvalidEntityError): pass
class InvalidAlphaEntityError(InvalidEntityError): pass
class InvalidTagContentError(Exception): pass
def parse(filename, skip_on_first_error=False):
HEXDIGITS = frozenset("0123456789ABCDEFabcdef")
NORMAL, PARSING_TAG, PARSING_ENTITY = range(3)
state = NORMAL
entity = ""
fh = None
try:
fh = open(filename, encoding="utf8")
errors = False
for lino, line in enumerate(fh, start=1):
for column, c in enumerate(line, start=1):
try:
if state == NORMAL:
if c == "<":
state = PARSING_TAG
elif c == "&":
entity = ""
state = PARSING_ENTITY
elif state == PARSING_TAG:
if c == ">":
state = NORMAL
elif c == "<":
raise InvalidTagContentError()
elif state == PARSING_ENTITY:
if c == ";":
if entity.startswith("#"):
if frozenset(entity[1:]) - HEXDIGITS:
raise InvalidNumericEntityError()
elif not entity.isalpha():
raise InvalidAlphaEntityError()
entity = ""
state = NORMAL
else:
if entity.startswith("#"):
if c not in HEXDIGITS:
raise InvalidNumericEntityError()
elif (entity and
c not in string.ascii_letters):
raise InvalidAlphaEntityError()
entity += c
except (InvalidEntityError,
InvalidTagContentError) as err:
if isinstance(err, InvalidNumericEntityError):
error = "invalid numeric entity"
elif isinstance(err, InvalidAlphaEntityError):
error = "invalid alphabetic entity"
elif isinstance(err, InvalidTagContentError):
error = "invalid tag"
print("ERROR {0} in {1} on line {2} column {3}"
.format(error, filename, lino, column))
if skip_on_first_error:
raise
entity = ""
state = NORMAL
errors = True
if state == PARSING_TAG:
raise EOFError("missing '>' at end of " + filename)
elif state == PARSING_ENTITY:
raise EOFError("missing ';' at end of " + filename)
if not errors:
print("OK", filename)
except (InvalidEntityError, InvalidTagContentError):
pass # Already handled
except EOFError as err:
print("ERROR unexpected EOF:", err)
except EnvironmentError as err:
print(err)
finally:
if fh is not None:
fh.close()
if len(sys.argv) < 2:
print("usage: checktags.py infile1 [infile2 [... infileN]]")
sys.exit()
for filename in sys.argv[1:]:
parse(filename)
Find and count the occurrence of all words in given text , sort them and print them to a file. Send me the file and the program. Get rid the words of colons, quotas, semicolons etc. The text file is here
From The dictionary txt file is here. make patterns and sorted it into a text file in a shape:
Pattern “list of candidates from dictionary separated by ‘,’ ” e.g. ‘0.0.1.2.3’ [‘AARON’, ‘LLOYD’, ‘OOZED’]
Send me a program and the file.
Link to Python documentation and basics tutorial - https://docs.python.org/3.10/tutorial/index.html