Python Code Examples: Data Structures, Algorithms, and Games

Python Code Examples

Data Structures

SNP Data Processing

def get_data(line: str) -> [str, str, set[str]]:
code, illnesses = line.split(':')
rs_code, nucleotid = code.split()
rs_code = rs_code.strip() # SNP
nucleotid = nucleotid.strip()
illnessset = set()
for illness in illnesses.split(','):
illnessset.add(illness.strip().lower())
return rs_code, nucleotid, illnesssetdef add_data(snp:dict,rs_code: str, code_n:str, pats: set)->None:
if rs_code in snp:
if nucleotid in snp[rs_code]:
snp[rs_code][nucleotid] |= ilnesses # |= is union
else:
snp[rs_code][nucleotid] = ilnesses
else:
snp[rs_code] = dict()
snp[rs_code][nucleotid] = ilnessesdef read_snp(filename) -> dict:
snp = dict()
with open(filename) as fln:
for line in fln:
if line[0] != '#':
rs_code, nucleotid, ilnessset = get_data(line)
add_data(snp, rs_code, nucleotid, ilnessset)
return snpdef remove_snp(snp:dict, rs_code: str, code_n:str, pats: set[str])->N:
if rs_code in snp:
if code_n in snp[rs_code]:
snp[rs_code][code_n] -= pats
if snp[rs_code][code_n] == set():
del snp[rs_code][code_n]
if snp[rs_code] == {}:
del snp[rs_code]def write_snp(snp: dict, filename: str) -> None:
with open(filename, 'w') as f:
for rs_code, val in snp.items():
for nucleotid, ilnessset in val.items():
line = f'{rs_code} {nucleotid}: '
first = True
for illness in ilnessset:
if not first:
line += ', '
line += illness
first = False
line += '\n'
f.write(line)def get_snpinfo(snp: dict, pats: set[str]) -> set[str, str]:
info = set()
for rs_code, val in snp.items():
for nucleotid, ilnessset in val.items():
if pats & ilnessset != set(): ## Checks for non-empty intersection
info.add( (rs_code, nucleotid) )
return infodef get_snps(snp: list[dict]) -> dict:
snps = dict()
for rs_code, val in snp.items():
snps[rs_code] = 0
for nucleotid, ilnessset in val.items():
snps[rs_code] += len(ilnessset)
return snpsdef mean_ocurrences(snp: dict) -> float:
mean = 0.0
count = 0
for rs_code, num in get_snps(snp).items():
mean += num
count += 1
return mean/countdef mode_ocurrences(snp: dict) -> int:
modedict = dict()
for rs_code, num in get_snps(snp).items():
if num in modedict:
modedict[num] += 1
else:
modedict[num] = 1
mode = 0
max_occ = 0
for num, occur in modedict.items():
if occur > max_occ:
max_occ = occur
mode = num
return modedef median_ocurrences(snp: dict) -> int:
occlst = []
for rs_code, num in get_snps(snp).items():
occlst.append(num)
sort(occlst)
return occlst[len(occlst)//2]

Encryption and Decryption

def crypt(txt:str,cpgm:str)->str:
res= ""
ind_A= ord("A") # CRYPT
for l in txt:
if l!=" ":
res +=cpgm[ord(l)- ind_A]
return resdef decrypt(txt: str, cpgm: str)-> str:
res=""
for l in txt:
i=0
while i<len(cpgm) and cpgm[i]!=l:
i+=1
res+= chr(ord("A")+i)
return resdef no_rep(word:str)->str:
letras= set() # empty set
res= ""for l in word:
if l not in letras:
letras.add(l)
res+=l
return resdef gen_crytopgram(word: str)->str:
letras= set(word)
res= no_rep(word)
for i in range(26):
l= chr(ord("A")+i)
if l not in letras:
res+=l
return resdef crypt_key( txt: str, clave: str)-> str:
return crypt(txt, gen_crytopgram(clave))def decrypt_key( txt: str, clave: str)-> str:
return decrypt(txt, gen_crytopgram(clave))def cifrado_fichero (fichero:str, clave: str)-> None:
assert fichero[-4:] == ".txt"
with open(fichero, "r") as f:
texto = f.read()
texto_enc= crypt_key(texto, clave)
with open(fichero[-4:] + "_enc.txt", "w") as f:
f.write(texto_enc)def decifrado_fichero (fichero:str, clave: str)-> None:
assert fichero[-8:] == "_enc.txt"
with open(fichero, "r") as f:
texto_enc= f.read()
texto = decrypt_key(texto_enc, clave)
with open(fichero[:-8] + "_clear.txt", "w") as f:
f.write(texto)

Algorithms

Linear Regression

from random import random, uniformN=200def gen_test_file(filename: str) -> None:
with open(filename, "w")as f:
for _ in range(N): # LINEAR REGRESSION
x= uniform(1,100)
y= 2*x +1
f.write(str(x)+ "\t"+ str(y)+'\n')def linear_regression(filename: str) -> tuple[float,float] :
with open(filename,"r") as f:
cont=0
sumx=0
sumy=0
sumxy=0
sumxx=0
l= f.readline() # to read data line by line without saving it to a list
while l!= "" :
cont+=1
xy= l.split()
x= float(xy[0])
y= float(xy[1])
sumx += x
sumy += y
sumxy += x * y
sumxx += x *x
l= f.readline()
mediax= sumx/cont
mediay= sumy/cont
sigmaxx= sumxx- cont*mediax **2
sigmaxy= sumxy- mediax *sumy - mediay*sumx + cont*mediax*mediay
a= sigmaxy/sigmaxx
b= mediay- a*mediax
return a,b

Prime Number Generation

def add_primes(filename: str, nprimes: int) -> None:
primelst = read_primes(filename)
with open(filename, "a") as flp:
for _ in range(nprimes):
next_prime(primelst)
prime = primelst[-1]
flp.write(f"{prime}\n")def merge(fln1: str, fln2: str, res:str) -> None:
with open(fln1) as f1, open(fln2) as f2, open(res, 'w') as fres:
l1 = f1.readline()
l2 = f2.readline() # MERGE
while l1!='' and l2!='':
n1 = int(l1)
n2 = int(l2)
if n1 < n2:
fres.write(f'{n1}\n')
l1 = f1.readline()
else:
fres.write(f'{n2}\n')
l2 = f2.readline()
while l1!='':
n1 = int(l1)
fres.write(f'{n1}\n')
l1 = f1.readline()
while l2!='':
n2 = int(l2)
fres.write(f'{n2}\n')
l2 = f2.readline()def is_prime(num: int, primelst: list[int]) -> bool:
i = 0
while i<len(primelst) and primelst[i]**2 < num and num % primelst[i] != 0:
i += 1
return i == len(primelst) or primelst[i]**2 > numdef next_prime(primelst: list[int]) -> None:
if len(primelst) == 0:
primelst.append(2)
else:
num = primelst[-1] + 1
while not is_prime(num, primelst):
num += 1
primelst.append(num)def read_primes(filename: str) -> list[int]:
primelst: list[int] = []
with open(filename) as fl:
for line in fl:
primelst.append(int(line))
return primelst

Games

Hangman

def picture2str(drw: dict, fails: int) -> str:
row = 0
pict = ""
for row, line in enumerate(drw['picture']):
for col, char in enumerate(line):
if drw['order'][row][col] <= fails:
pict += char
else:
pict += " " # HANGMAN
pict += "\n"
return pictdef game2str(game: dict) -> str:
pict = picture2str(game['drawing'], game['fails'])
aciertos = 0
for letter in game['word']:
if letter in game['given_letters']:
pict += letter
aciertos += 1
else:
pict += "_"
pict += " "
pict += "\n"
if game['fails'] == game['drawing']['max_attemps']:
pict += f"You lost, the word is: {game['word']}\n"
elif right_letters == len(game['word']):
pict += "You won\n"
return pictdef init(words_filename: str, picture_filename: str) -> dict:
with open(words_filename, "r") as f:
palabras = f.readlines()
p_aleatoria = palabras[randint(0, len(palabras)- 1)][:-1]
game = {
"word" : p_aleatoria,
"given_letters" : set(),
"fails" : 0,
"drawing": drawing(picture_filename)
}
return gamedef drawing(filename: str) -> dict:
with open(filename, "r") as f:
n = int(f.readline())
picture = []
for _ in range(n):
picture.append(f.readline()[:-1])
order = []
maximo = 0
for _ in range(n):
l = f.readline()
l = l.split()
for j in range(len(l)):
l[j] = int(l[j])
if l[j] > maximo:
maximo = l[j]
order.append(l)
return {"picture": picture, "order": order, "max_attemps": maximo}def is_ended(game: dict) -> bool:
count = 0
for l in game['word']:
if l in game['given_letters']:
count += 1
return count == len(game['word']) or game['fails'] == game['drawing']['max_attemps']def update(game: dict, letter: str) -> str:
if letter in game['given_letters']:
msg = f"You have already said '{letter}'" elif letter in game['word']:
msg = f"Good, {letter} is in the word"
game['given_letters'].add(letter)
else:
msg = f"Sorry, {letter} is NOT in the word"
game['given_letters'].add(letter)
game['fails'] += 1
return msgdef main(words_filename: str, picture_filename: str) -> None:
game = init(words_filename, picture_filename)
while not is_ended(game):
print(game2str(game))
letter = input("Give a letter: ")
msg = update(game, letter)
print(msg)
print(game2str(game))

2048 Game

import json
from random import choice, random # 2048def add_new_cell(game:dict) -> None:
vacias = []
for i in range(len(game["board"])):
for j in range(len(game["board"])):
if game["board"][i][j] == 0:
vacias.append((i,j))
c_aleatoria = choice(vacias)
if random() < 0.75:
game["board"][c_aleatoria[0]][c_aleatoria[1]] = 2
else:
game["board"][c_aleatoria[0]][c_aleatoria[1]] = 4
if game["max_value"] < game["board"][c_aleatoria[0]][c_aleatoria[1]]:
game["max_value"] = game["board"][c_aleatoria[0]][c_aleatoria[1]]def init(dim: int) -> dict:
f = open("2048.ini", "r")
ini = json.loads(f.read())
if dim == None:
dim = ini["dim"]
juego = {
"board":[],
"score": 0,
"max_value": 0,
"max_score":ini["max_score"] }
for _ in range(dim):
juego["board"].append([0]*dim)
f.close()
for _ in range(2):
add_new_cell(juego)
return juegodef finalize(game: dict) -> None:
estado = {
"dim": len(game["board"]),
"max_score": max(game["score"], game["max_score"])}
f = open("2048.ini", "w")
f.write(str(estado))
f.close()def get_size(game: dict) -> int:
return len(game["board"])def get_value(game: dict, pos: tuple, trasposed: bool = False) -> int:
res = -1
if pos[0] < len(game["board"]) and pos[0] >= -len(game["board"]) and pos[1] < len(game["board"]) and pos[1] >= -len(game["board"]):
if trasposed:
f = pos[1]
c = pos[0]
else:
f = pos[0]
c = pos[1]
res = game["board"][f][c]return resdef put_value(game: dict, pos: tuple, value: int, trasposed: bool = False):
if trasposed:
f = pos[1]
c = pos[0]
else:
f = pos[0]
c = pos[1]
game["board"][f][c] = valuedef is_blocked(game: dict) -> bool:
blocked = True
i = 0
while i < get_size(game) and blocked:
j = 0
while j < get_size(game) and blocked:
if get_value(game, (i, j)) == 0:
blocked = False
elif j < get_size(game)-1 and get_value(game, (i, j)) == get_value(game, (i, j+1)):
blocked = False
elif i < get_size(game)-1 and get_value(game, (i, j)) == get_value(game, (i+1, j)):
blocked = False
j += 1
i += 1
return blockeddef move(game: dict, start_end: bool, move_cols: bool) -> bool:
cambiado = False
if start_end:
ini = 0
fin = get_size(game)
act = 1
else:
ini = -1
fin = -get_size(game)-1
act = -1
score = 0
i = ini
while abs(i) < abs(fin):
j = ini
while abs(j) < abs(fin):
k = j+act
while abs(k)<abs(fin) and get_value(game, (i, j), move_cols) == 0:
if get_value(game, (i, k), move_cols) != 0:
put_value(game, (i, j), get_value(game, (i, k), move_cols), move_cols)
put_value(game, (i, k), 0, move_cols)
cambiado = True
k+=act
while abs(k)<abs(fin) and get_value(game, (i, k), move_cols) == 0:
k += act if get_value(game, (i, j), move_cols) == get_value(game, (i, k), move_cols):
put_value(game, (i, j), get_value(game, (i, k), move_cols)*2 , move_cols)
put_value(game, (i, k), 0, move_cols)
score += get_value(game, (i, j), move_cols)
cambiado = True
j += act
i += actupdate(game, score)
return cambiadodef update(game: dict, score: int) -> None:
game["score"] += score for f in game["board"]:
for casilla in f:
if casilla > game["max_value"]:
game["max_value"] = casilla# reverse indices def right(game: dict) -> bool:
return move(game, False, False)def left(game: dict) -> bool:
return move(game, True, False)# Transposed matrix def up(game: dict) -> bool:
return move(game, True, True)# Reverse indices on transposed matrix def down(game: dict) -> bool:
return move(game, False, True)def game2str(game: dict) -> str:
dim = get_size(game)
line = '-' * (6*dim + 1) + '\n'
res = line
size = get_size(game)
for row in range(size):
scol = '|'
for col in range(size):
val = get_value(game, (row, col))
if val == 0:
val = ''
scol += f'{val:5}|'
res += scol + '\n' + line
score = game['score']
mval = game['max_value']
res += f'{mval:6}-{score:6}'
return res

File Processing

def mean_file(filename):
with open(filename,"r") as fln:
acc = 0.0
i = 0
line = fln.readline()
while line != "":
for num in split_line(line):
acc += num
i += 1
line = fln.readline()
mean = acc / i
return meandef read_lines(filename):
with open(filename,"r") as fll:
line = fll.readline()
while line != "":
line = line.strip()
print(f"{line}:{len(line)}")
line = fll.readline()