Final changes and commit

This commit is contained in:
Kristofers Solo 2022-08-02 20:34:11 +03:00
parent db328c4350
commit 253802ac88
38 changed files with 1917 additions and 1708 deletions

1
.gitignore vendored
View File

@ -6,3 +6,4 @@
/december/task_081221/*.log
**.pkl
**test.py
pygame/snake/source/score.csv

View File

@ -8,56 +8,56 @@ HEADERS = {
class IKEA:
def __init__(self, url):
self.url = 'https://www.ikea.lv/en/products/' + url + '?&&page=1&order=PRICEASC'
def __init__(self, url):
self.url = 'https://www.ikea.lv/en/products/' + url + '?&&page=1&order=PRICEASC'
def _get_paige_amount(self):
page_amount = 1
page = requests.get(self.url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
def _get_paige_amount(self):
page_amount = 1
page = requests.get(self.url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
# getting max page amount
for el in soup.find_all(class_='page-link'):
cropped_name = el.get_text().strip()
if cropped_name.isnumeric():
cropped_name = int(cropped_name)
if cropped_name > page_amount:
page_amount = cropped_name
# getting max page amount
for el in soup.find_all(class_='page-link'):
cropped_name = el.get_text().strip()
if cropped_name.isnumeric():
cropped_name = int(cropped_name)
if cropped_name > page_amount:
page_amount = cropped_name
return page_amount
return page_amount
def get_data(self):
prices = []
names = []
prices.clear()
names.clear()
# combined_list.clear()
position = self.url.find('page=') + 5
for i in range(1, self._get_paige_amount() + 1):
url = self.url[:position] + str(i) + self.url[position + 1:]
def get_data(self):
prices = []
names = []
prices.clear()
names.clear()
# combined_list.clear()
position = self.url.find('page=') + 5
for i in range(1, self._get_paige_amount() + 1):
url = self.url[:position] + str(i) + self.url[position + 1:]
page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
# getting product name
for el in soup.find_all(class_='display-7 mr-2'):
cropped_name = el.get_text().strip()
names.append(cropped_name)
# getting product name
for el in soup.find_all(class_='display-7 mr-2'):
cropped_name = el.get_text().strip()
names.append(cropped_name)
# getting product price
for el in soup.find_all(class_='display-6'):
cropped_price = el.get_text().strip()
prices.append(cropped_price[:cropped_price.find("") + 1])
# getting product price
for el in soup.find_all(class_='display-6'):
cropped_price = el.get_text().strip()
prices.append(cropped_price[:cropped_price.find("") + 1])
combined_list = [i + " - " + j for i, j in zip(names, prices)]
if __name__ == '__main__':
SEPARATOR = "\n"
else:
SEPARATOR = "<br>"
combined_list = [i + " - " + j for i, j in zip(names, prices)]
if __name__ == '__main__':
SEPARATOR = "\n"
else:
SEPARATOR = "<br>"
output = SEPARATOR.join(str(elem) for elem in combined_list)
print(len(names))
return output
output = SEPARATOR.join(str(elem) for elem in combined_list)
print(len(names))
return output
arm_chairs = IKEA('ikea-for-business/office/armchairs')
@ -67,29 +67,36 @@ bed_frames = IKEA('bedroom/beds-and-sofa-beds/bed-frames')
bookcases = IKEA('living-room/bookcases/bookcases')
boxes_and_baskets = IKEA('bedroom/sorting-solutions/boxes-and-baskets')
candles = IKEA('kitchen/kitchen-decoration/candles')
ceiling_lamps_and_spotlights = IKEA('decoration/lighting/ceiling-lamps-and-spotlights')
ceiling_lamps_and_spotlights = IKEA(
'decoration/lighting/ceiling-lamps-and-spotlights')
chairs_and_benches = IKEA('dining-room/dining-seating/chairs-and-benches')
chest_of_drawers = IKEA('bedroom/chest-of-drawers-other-furniture/chest-of-drawers')
children_storage_furniture = IKEA('children-s-room/children-3-7/children-s-storage-furniture')
chest_of_drawers = IKEA(
'bedroom/chest-of-drawers-other-furniture/chest-of-drawers')
children_storage_furniture = IKEA(
'children-s-room/children-3-7/children-s-storage-furniture')
curtains = IKEA('kitchen/curtains-blinds-and-fabrics/curtains')
day_beds = IKEA('bedroom/beds-and-sofa-beds/day-beds')
dining_tables = IKEA('dining-room/dining-tables/dining-tables')
dinnerware_and_serving = IKEA('kitchen/cookware-and-dinnerware/dinnerware-and-serving')
dinnerware_and_serving = IKEA(
'kitchen/cookware-and-dinnerware/dinnerware-and-serving')
glasses = IKEA('kitchen/cookware-and-dinnerware/glasses')
home_desks = IKEA('home-office/desks/home-desks')
interior_organisers = IKEA('home-office/wardrobes/interior-organisers')
kitchen_interior_organisers = IKEA('kitchen/kitchen-interior-organisers/kitchen-interior-organisers')
kitchen_interior_organisers = IKEA(
'kitchen/kitchen-interior-organisers/kitchen-interior-organisers')
light_bulbs = IKEA('bedroom/bedroom-lighting/light-bulbs')
mattresses = IKEA('bedroom/mattresses/mattresses')
mirrors = IKEA('kitchen/kitchen-decoration/mirrors')
office_chairs = IKEA('home-office/work-seating-range/office-chairs')
office_desks_and_tables = IKEA('home-office/desks/office-desks-and-tables')
open_shelving_units = IKEA('living-room/shelving-units-systems/open-shelving-units')
open_shelving_units = IKEA(
'living-room/shelving-units-systems/open-shelving-units')
pax_wardrobes = IKEA('ikea-for-business/retail/system-wardrobes')
pendant_lamps = IKEA('ikea-for-business/retail/pendant-lamps')
pillows = IKEA('bedroom/bedding/pillows')
pots = IKEA('kitchen/cookware-and-dinnerware/pots')
quilt_covers_and_pillow_cases = IKEA('bedroom/bedding/quilt-covers-and-pillow-cases')
quilt_covers_and_pillow_cases = IKEA(
'bedroom/bedding/quilt-covers-and-pillow-cases')
quilts = IKEA('bedroom/bedding/quilts')
rugs = IKEA('living-room/home-furnishing-rugs/rugs')
sheets_and_pillow_cases = IKEA('bedroom/bedding/sheets-and-pillow-cases')
@ -100,22 +107,23 @@ solitaire_wardrobes = IKEA('bedroom/wardrobes/solitaire-wardrobes')
system_cabinets = IKEA('living-room/solitaire-cabinets/system-cabinets')
table_lamps = IKEA('bedroom/bedroom-lighting/table-lamps')
towels = IKEA('bathroom/towels/towels')
toys_for_small_children = IKEA('children-s-room/children-3-7/toys-for-small-children')
toys_for_small_children = IKEA(
'children-s-room/children-3-7/toys-for-small-children')
tv_benches = IKEA('living-room/tv-stands-media-units/tv-benches')
def main():
# import cProfile
# import pstats
# with cProfile.Profile() as pr:
# tv_benches.get_data()
# import cProfile
# import pstats
# with cProfile.Profile() as pr:
# tv_benches.get_data()
# stats = pstats.Stats(pr)
# stats.sort_stats(pstats.SortKey.TIME)
# # stats.print_stats()
# stats.dump_stats(filename='stats.prof')
print(tv_benches.get_data())
# stats = pstats.Stats(pr)
# stats.sort_stats(pstats.SortKey.TIME)
# # stats.print_stats()
# stats.dump_stats(filename='stats.prof')
print(tv_benches.get_data())
if __name__ == '__main__':
main()
main()

View File

@ -1,72 +1,80 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="IKEA_logo.svg" type="image/svg" />
<title>IKEA scraper</title>
<link rel="stylesheet" href="style.css" />
<script src="eel.js"></script>
</head>
<body>
<select name="dropdown" id="product">
<option value="Armchairs">Armchairs</option>
<option value="Bathroom furniture">Bathroom furniture</option>
<option value="Bathroom lightning">Bathroom lightning</option>
<option value="Bed frames">Bed frames</option>
<option value="Bookcases">Bookcases</option>
<option value="Boxes and baskets">Boxes and baskets</option>
<option value="Ceiling lamps and spotlight">Ceiling lamps and spotlight</option>
<option value="Chest of drawers">Chest of drawers</option>
<option value="Children's storage furniture">Children's storage furniture</option>
<option value="curtains">Curtains</option>
<option value="day beds">Day beds</option>
<option value="dining tables">Dining tables</option>
<option value="dinnerware and serving">Dinnerware and serving</option>
<option value="glasses">Glasses</option>
<option value="home desks">Home desks</option>
<option value="interior organisers">Interior organisers</option>
<option value="kitchen interior organisers">Kitchen interior organisers</option>
<option value="light bulbs">Light bulbs</option>
<option value="mattresses">Mattresses</option>
<option value="mirrors">Mirrors</option>
<option value="office chairs">Office chairs</option>
<option value="office desks and tables">Office desks and tables</option>
<option value="open shelving units">Open shelving units</option>
<option value="pax wardrobes">PAX wardrobes</option>
<option value="pendant lamps">Pendant lamps</option>
<option value="pillows">Pillows</option>
<option value="pots">Pots</option>
<option value="quilt covers and pillow cases">Quilt covers and pillow cases</option>
<option value="quilts">Quilts</option>
<option value="rugs">Rugs</option>
<option value="sheets and pillow cases">Sheets and pillow cases</option>
<option value="sofa beds and chair beds">Sofa beds and chair beds</option>
<option value="sofa tables">Sofa tables</option>
<option value="solitaire cabinets">Solitaire cabinets</option>
<option value="solitaire wardrobes">Solitaire wardrobes</option>
<option value="system cabinets">System cabinets</option>
<option value="table lamps">Table lamps</option>
<option value="towels">Towels</option>
<option value="toys for small children">Toys for small children</option>
<option value="tv benches">TV benches</option>
</select>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="IKEA_logo.svg" type="image/svg" />
<title>IKEA scraper</title>
<link rel="stylesheet" href="style.css" />
<script src="eel.js"></script>
</head>
<body>
<select name="dropdown" id="product">
<option value="Armchairs">Armchairs</option>
<option value="Bathroom furniture">Bathroom furniture</option>
<option value="Bathroom lightning">Bathroom lightning</option>
<option value="Bed frames">Bed frames</option>
<option value="Bookcases">Bookcases</option>
<option value="Boxes and baskets">Boxes and baskets</option>
<option value="Ceiling lamps and spotlight">
Ceiling lamps and spotlight
</option>
<option value="Chest of drawers">Chest of drawers</option>
<option value="Children's storage furniture">
Children's storage furniture
</option>
<option value="curtains">Curtains</option>
<option value="day beds">Day beds</option>
<option value="dining tables">Dining tables</option>
<option value="dinnerware and serving">Dinnerware and serving</option>
<option value="glasses">Glasses</option>
<option value="home desks">Home desks</option>
<option value="interior organisers">Interior organisers</option>
<option value="kitchen interior organisers">
Kitchen interior organisers
</option>
<option value="light bulbs">Light bulbs</option>
<option value="mattresses">Mattresses</option>
<option value="mirrors">Mirrors</option>
<option value="office chairs">Office chairs</option>
<option value="office desks and tables">Office desks and tables</option>
<option value="open shelving units">Open shelving units</option>
<option value="pax wardrobes">PAX wardrobes</option>
<option value="pendant lamps">Pendant lamps</option>
<option value="pillows">Pillows</option>
<option value="pots">Pots</option>
<option value="quilt covers and pillow cases">
Quilt covers and pillow cases
</option>
<option value="quilts">Quilts</option>
<option value="rugs">Rugs</option>
<option value="sheets and pillow cases">Sheets and pillow cases</option>
<option value="sofa beds and chair beds">Sofa beds and chair beds</option>
<option value="sofa tables">Sofa tables</option>
<option value="solitaire cabinets">Solitaire cabinets</option>
<option value="solitaire wardrobes">Solitaire wardrobes</option>
<option value="system cabinets">System cabinets</option>
<option value="table lamps">Table lamps</option>
<option value="towels">Towels</option>
<option value="toys for small children">Toys for small children</option>
<option value="tv benches">TV benches</option>
</select>
<button id="show">Find products</button>
<button id="show">Find products</button>
<div id="info"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
async function call() {
let product = document.getElementById("product").value;
<div id="info"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
async function call() {
let product = document.getElementById('product').value
let res = await eel.call_in_js(product)();
document.getElementById("info").innerHTML = res;
}
jQuery("#show").on("click", function () {
call();
});
</script>
</body>
let res = await eel.call_in_js(product)()
document.getElementById('info').innerHTML = res
}
jQuery('#show').on('click', function () {
call()
})
</script>
</body>
</html>

View File

@ -1,55 +1,55 @@
html,
body {
font-family: "Roboto", sans-serif;
background: #f2f2f2;
margin: 0;
padding: 0;
font-family: 'Roboto', sans-serif;
background: #f2f2f2;
margin: 0;
padding: 0;
}
#product {
display: flex;
margin-top: 10px;
height: 30px;
margin-left: auto;
margin-right: auto;
background-color: #333333;
width: 95%;
min-width: 100px;
border-radius: 5px;
cursor: pointer;
color: #cccccc;
display: flex;
margin-top: 10px;
height: 30px;
margin-left: auto;
margin-right: auto;
background-color: #333333;
width: 95%;
min-width: 100px;
border-radius: 5px;
cursor: pointer;
color: #cccccc;
}
#show {
display: block;
border: none;
margin: auto;
margin-top: 10px;
margin-bottom: 10px;
min-width: 200px;
display: block;
border: none;
margin: auto;
margin-top: 10px;
margin-bottom: 10px;
min-width: 200px;
background: #666666;
background: #666666;
border-radius: 5px;
padding: 10px;
color: #f2f2f2;
outline: none;
width: 95%;
font-size: 18px;
text-transform: uppercase;
cursor: pointer;
transition: transform 0.7s ease;
border-radius: 5px;
padding: 10px;
color: #f2f2f2;
outline: none;
width: 95%;
font-size: 18px;
text-transform: uppercase;
cursor: pointer;
transition: transform 0.7s ease;
}
#show:hover {
opacity: 0.9;
transform: scale(1.01);
opacity: 0.9;
transform: scale(1.01);
}
#info {
color: #666666;
display: block;
text-align: center;
font-size: 16px;
font-weight: bold;
color: #666666;
display: block;
text-align: center;
font-size: 16px;
font-weight: bold;
}

View File

@ -8,37 +8,37 @@ url = "https://www.ikea.lv/"
all_page = requests.get(url)
if all_page.status_code == 200:
page = BeautifulSoup(all_page.content, 'html.parser')
found = page.find_all(class_="itemBlock")
page = BeautifulSoup(all_page.content, 'html.parser')
found = page.find_all(class_="itemBlock")
info = []
item_array = []
for item in found:
item = item.findChild("div").findChild(class_="card-body")
info = []
item_array = []
for item in found:
item = item.findChild("div").findChild(class_="card-body")
item_name = item.findChild(class_="itemName")
item_name = item_name.findChild("div").findChild("h6")
item_name = item.findChild(class_="itemName")
item_name = item_name.findChild("div").findChild("h6")
item_array.append(item_name.string)
item_array.append(item_name.string)
price = item.findChild(class_="itemPrice-wrapper")
price = price.findChild("p").findChild("span")
price = item.findChild(class_="itemPrice-wrapper")
price = price.findChild("p").findChild("span")
try:
item_array.append(price.attrs["data-price"])
except:
item_array.append(price.attrs["data-pricefamily"])
try:
item_array.append(price.attrs["data-price"])
except:
item_array.append(price.attrs["data-pricefamily"])
all_facts = []
for facts in all_facts:
if len(facts) == 1:
all_facts.append(facts.string)
else:
atrasts = facts.findChildren("span")
for i in atrasts:
all_facts.append(i.string)
all_facts = []
for facts in all_facts:
if len(facts) == 1:
all_facts.append(facts.string)
else:
atrasts = facts.findChildren("span")
for i in atrasts:
all_facts.append(i.string)
item_array.append(all_facts)
info.append(item_array)
for ieraksts in info:
print(ieraksts)
item_array.append(all_facts)
info.append(item_array)
for ieraksts in info:
print(ieraksts)

View File

@ -10,98 +10,111 @@ from io import BytesIO
from openpyxl.styles import Font, Alignment
import openpyxl
HEADERS = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.97 Safari/537.36 Vivaldi/4.1.2369.21'}
HEADERS = {
"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.97 Safari/537.36 Vivaldi/4.1.2369.21'}
class SS:
def __init__(self, url):
self.url = url
def __init__(self, url):
self.url = url
def _get_page_amount(self):
page = requests.get(self.url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
def _get_page_amount(self):
page = requests.get(self.url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
last_url = soup.find(class_='td2').findChild('a')['href']
page_amount = last_url[last_url.find("page") + 4:last_url.find(".html")]
print(f"Page amount = {page_amount}")
last_url = soup.find(class_='td2').findChild('a')['href']
page_amount = last_url[last_url.find(
"page") + 4:last_url.find(".html")]
print(f"Page amount = {page_amount}")
return int(page_amount)
return int(page_amount)
def get_data(self):
items = []
images = []
item_no = 1
for page_number in range(1, self._get_page_amount() + 1):
url = self.url + f"/page{page_number}.html"
def get_data(self):
items = []
images = []
item_no = 1
for page_number in range(1, self._get_page_amount() + 1):
url = self.url + f"/page{page_number}.html"
page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
# item ids
ids = [tag['id'] for tag in soup.select('tr[id]')] # creates list with ids
ids = [x for x in ids if "tr_bnr" not in x] # removes "tr_bnr" elements from list
ids.remove("head_line") # removes first "head_line" id
print(f"Page {page_number}")
# item ids
ids = [tag['id']
for tag in soup.select('tr[id]')] # creates list with ids
# removes "tr_bnr" elements from list
ids = [x for x in ids if "tr_bnr" not in x]
ids.remove("head_line") # removes first "head_line" id
print(f"Page {page_number}")
# getting item data
for el in soup.find_all(id=ids):
print(f"Item {item_no}")
item_no += 1
# getting item data
for el in soup.find_all(id=ids):
print(f"Item {item_no}")
item_no += 1
# image
image_url = el.find(class_='msga2').find_next_sibling().findChild('a').findChild('img')['src'] # gets image url
response = requests.get(image_url)
img = Image.open(BytesIO(response.content))
images.append(img)
print(img)
for elem in el.find_all(class_='msga2-o pp6'):
items.append(elem.get_text())
# image
image_url = el.find(class_='msga2').find_next_sibling().findChild(
'a').findChild('img')['src'] # gets image url
response = requests.get(image_url)
img = Image.open(BytesIO(response.content))
images.append(img)
print(img)
for elem in el.find_all(class_='msga2-o pp6'):
items.append(elem.get_text())
# adverts url
item_url = el.findChild(class_='msg2').findChild('div').findChild('a')['href'] # gets url
item_url = "https://www.ss.com" + item_url
item_page = requests.get(item_url, headers=HEADERS)
item_soup = BeautifulSoup(item_page.content, 'html.parser')
# adverts url
item_url = el.findChild(class_='msg2').findChild(
'div').findChild('a')['href'] # gets url
item_url = "https://www.ss.com" + item_url
item_page = requests.get(item_url, headers=HEADERS)
item_soup = BeautifulSoup(item_page.content, 'html.parser')
# adverts full text
item_text = item_soup.find(id='msg_div_msg').get_text() # gets full text
item_text = item_text[:item_text.find("Pilsēta:")] # removes text last part (table)
items.append(item_text)
# adverts full text
item_text = item_soup.find(
id='msg_div_msg').get_text() # gets full text
# removes text last part (table)
item_text = item_text[:item_text.find("Pilsēta:")]
items.append(item_text)
# adverts publication date
item_date = item_soup.find_all('td', class_='msg_footer') # gets all 'msg_footer' class'
item_date = item_date[2].get_text() # extracts 3rd element
items.append(item_date[8:18]) # crops date
# adverts publication date
# gets all 'msg_footer' class'
item_date = item_soup.find_all('td', class_='msg_footer')
item_date = item_date[2].get_text() # extracts 3rd element
items.append(item_date[8:18]) # crops date
chunk_size = 8
chunked_items_list = [items[i:i + chunk_size] for i in range(0, len(items), chunk_size)] # combines each 'chunk_size' elements into array
columns = ["Atrašanās vieta", "Istabu skaits", "Kvadratūra", "Stāvs", "Sērija", "Cena", "Pilns sludinājuma teksts", "Izvietošanas datums"]
df = pd.DataFrame(chunked_items_list, columns=columns)
df.to_excel(excel_writer='output.xlsx', index=False)
chunk_size = 8
# combines each 'chunk_size' elements into array
chunked_items_list = [items[i:i + chunk_size]
for i in range(0, len(items), chunk_size)]
columns = ["Atrašanās vieta", "Istabu skaits", "Kvadratūra", "Stāvs",
"Sērija", "Cena", "Pilns sludinājuma teksts", "Izvietošanas datums"]
df = pd.DataFrame(chunked_items_list, columns=columns)
df.to_excel(excel_writer='output.xlsx', index=False)
wb = openpyxl.load_workbook("output.xlsx")
ws = wb.worksheets[0]
sheet = wb.active
wb = openpyxl.load_workbook("output.xlsx")
ws = wb.worksheets[0]
sheet = wb.active
# 'I1' cell setup
ws['I1'] = "Attēli"
ws['I1'].font = Font(bold=True)
ws["I1"].alignment = Alignment(horizontal='center', vertical='top')
# 'I1' cell setup
ws['I1'] = "Attēli"
ws['I1'].font = Font(bold=True)
ws["I1"].alignment = Alignment(horizontal='center', vertical='top')
# sets cell width
sheet.column_dimensions['A'].width = 20
sheet.column_dimensions['G'].width = 50
sheet.column_dimensions['H'].width = 20
sheet.column_dimensions['I'].width = 13
# sets cell width
sheet.column_dimensions['A'].width = 20
sheet.column_dimensions['G'].width = 50
sheet.column_dimensions['H'].width = 20
sheet.column_dimensions['I'].width = 13
for i in range(len(images)):
sheet.row_dimensions[i + 2].height = 51 # sets cell height
ws[f'G{i + 2}'].alignment = Alignment(wrap_text=True) # enables word wrap
for i in range(len(images)):
sheet.row_dimensions[i + 2].height = 51 # sets cell height
# enables word wrap
ws[f'G{i + 2}'].alignment = Alignment(wrap_text=True)
img = openpyxl.drawing.image.Image(images[i])
ws.add_image(img, f"I{i + 2}") # adds images
wb.save("output.xlsx")
print("Done")
img = openpyxl.drawing.image.Image(images[i])
ws.add_image(img, f"I{i + 2}") # adds images
wb.save("output.xlsx")
print("Done")
flats = SS("https://www.ss.com/lv/real-estate/flats/riga/all/sell/")
@ -109,8 +122,8 @@ flats2 = SS("https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/")
def main():
flats.get_data()
flats.get_data()
if __name__ == '__main__':
main()
main()

View File

@ -11,9 +11,9 @@ from selenium.webdriver.common.by import By
use_firefox = True
if use_firefox:
browser = webdriver.Firefox()
browser = webdriver.Firefox()
else:
browser = webdriver.Chrome("chromedriver")
browser = webdriver.Chrome("chromedriver")
address = "https://www.riga.lv/lv"
browser.get(address)
@ -25,7 +25,8 @@ search = browser.find_element_by_class_name('search-link')
search.click()
delay = 2
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.ID, 'edit-search')))
WebDriverWait(browser, delay).until(
EC.presence_of_all_elements_located((By.ID, 'edit-search')))
search = browser.find_element_by_id('edit-search')
search.send_keys("dokum") # writes in search line
@ -33,9 +34,11 @@ search = browser.find_element_by_id('search-header-button')
search.click()
browser.maximize_window()
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'filter-content')))
WebDriverWait(browser, delay).until(
EC.presence_of_all_elements_located((By.CLASS_NAME, 'filter-content')))
delay = 3
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.ID, 'filter_type_file')))
WebDriverWait(browser, delay).until(
EC.presence_of_all_elements_located((By.ID, 'filter_type_file')))
filter = browser.find_element_by_css_selector('label[for="filter_type_file"]')
filter.click()

View File

@ -16,108 +16,116 @@ firefox = ["2", "firefox"]
def get_data():
user_browser, user_pages, search_word = get_user_input()
user_browser, user_pages, search_word = get_user_input()
for page in user_pages:
if user_browser in chromium:
if os.name in ('nt', 'dos'):
browser = webdriver.Chrome("chromedriver.exe") # windows
else:
browser = webdriver.Chrome("chromedriver") # gnu/linux
elif user_browser in firefox:
browser = webdriver.Firefox()
for page in user_pages:
if user_browser in chromium:
if os.name in ('nt', 'dos'):
browser = webdriver.Chrome("chromedriver.exe") # windows
else:
browser = webdriver.Chrome("chromedriver") # gnu/linux
elif user_browser in firefox:
browser = webdriver.Firefox()
url = f"https://www.riga.lv/lv/search?q={search_word}&types=file&page={page - 1}"
browser.get(url)
browser.find_element(By.CLASS_NAME, 'cookie-accept-all').click()
url = f"https://www.riga.lv/lv/search?q={search_word}&types=file&page={page - 1}"
browser.get(url)
browser.find_element(By.CLASS_NAME, 'cookie-accept-all').click()
files = browser.find_elements(By.CLASS_NAME, 'file')
for file in files:
file_name = file.text
file_url = file.get_attribute('href')
file_download(file_name, file_url)
browser.quit()
files = browser.find_elements(By.CLASS_NAME, 'file')
for file in files:
file_name = file.text
file_url = file.get_attribute('href')
file_download(file_name, file_url)
browser.quit()
def get_user_input():
if debug == True:
search_word = "dokum"
else:
search_word = input("Choose keyword to search: ")
if debug == True:
search_word = "dokum"
else:
search_word = input("Choose keyword to search: ")
last_page = get_max_page_amount(search_word)
print("\nChoose which browser to use:")
print("1 - chromium (chrome)")
print("2 - firefox")
last_page = get_max_page_amount(search_word)
print("\nChoose which browser to use:")
print("1 - chromium (chrome)")
print("2 - firefox")
if debug == True:
browser = "firefox"
else:
browser = input("").lower()
if debug == True:
browser = "firefox"
else:
browser = input("").lower()
print(f"\nChoose from which pages you want to download files (1 4 7; 2-5; all). Maximum is {last_page} pages.")
try:
if debug == True:
user_input = "1"
else:
user_input = input("").lower()
print(
f"\nChoose from which pages you want to download files (1 4 7; 2-5; all). Maximum is {last_page} pages.")
try:
if debug == True:
user_input = "1"
else:
user_input = input("").lower()
if user_input == "all":
pages = list(map(int, range(1, last_page + 1))) # creates list with all pages
else:
user_page_list = user_input.split(" ")
for page_range in user_page_list:
if "-" in page_range:
if user_input == "all":
# creates list with all pages
pages = list(map(int, range(1, last_page + 1)))
else:
user_page_list = user_input.split(" ")
for page_range in user_page_list:
if "-" in page_range:
first_num = int(page_range[:page_range.find("-")]) # gets first number
second_num = int(page_range[page_range.find("-") + 1:]) + 1 # gets second number
# gets first number
first_num = int(page_range[:page_range.find("-")])
# gets second number
second_num = int(page_range[page_range.find("-") + 1:]) + 1
if second_num > last_page: # reduces user input to max page amount
second_num = last_page
if second_num > last_page: # reduces user input to max page amount
second_num = last_page
user_page_list = user_page_list + list(map(str, range(first_num, second_num))) # creates list with str range
pages = [elem for elem in user_page_list if not "-" in elem] # removes all elements containing "-"
pages = list(map(int, pages)) # convers str to int
pages.sort() # sorts list
pages = list(set(pages)) # removes duplicates from list
except:
print("Enered incorrect number/s. Try again.")
return browser, pages, search_word
user_page_list = user_page_list + \
list(map(str, range(first_num, second_num))
) # creates list with str range
# removes all elements containing "-"
pages = [elem for elem in user_page_list if not "-" in elem]
pages = list(map(int, pages)) # convers str to int
pages.sort() # sorts list
pages = list(set(pages)) # removes duplicates from list
except:
print("Enered incorrect number/s. Try again.")
return browser, pages, search_word
def get_max_page_amount(keyword: str):
url = f"https://www.riga.lv/lv/search?q={keyword}&types=file"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
try:
last_page = soup.find(class_='pager__item--last').get_text().strip()
except:
try:
last_page = soup.find_all(class_='pager__item page-item')
last_page = last_page[-1].get_text().strip()[-1] # gets last number from navigation bar
except:
print("Something went wrong. Please try again or try another keyword.")
return int(last_page)
url = f"https://www.riga.lv/lv/search?q={keyword}&types=file"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
try:
last_page = soup.find(class_='pager__item--last').get_text().strip()
except:
try:
last_page = soup.find_all(class_='pager__item page-item')
# gets last number from navigation bar
last_page = last_page[-1].get_text().strip()[-1]
except:
print("Something went wrong. Please try again or try another keyword.")
return int(last_page)
def file_download(file_name, file_url):
print(f"\nNAME: {file_name}")
print(f"URL: {file_url}")
print(f"\nNAME: {file_name}")
print(f"URL: {file_url}")
path = "files"
if not exists(path):
os.mkdir(path)
path = "files"
if not exists(path):
os.mkdir(path)
response = requests.get(file_url)
if ".pdf" in file_name:
open(f"{path}/{file_name}", "wb").write(response.content)
else:
open(f"{path}/{file_name}.pdf", "wb").write(response.content)
response = requests.get(file_url)
if ".pdf" in file_name:
open(f"{path}/{file_name}", "wb").write(response.content)
else:
open(f"{path}/{file_name}.pdf", "wb").write(response.content)
def main():
get_data()
get_data()
if __name__ == '__main__':
main()
main()

View File

@ -21,126 +21,138 @@ firefox = ["2", "firefox"]
def get_data():
user_browser, user_pages, search_word, last_page = get_user_input()
user_browser, user_pages, search_word, last_page = get_user_input()
if user_browser in chromium:
if os.name in ('nt', 'dos'):
browser = webdriver.Chrome("chromedriver.exe") # windows
else:
browser = webdriver.Chrome("chromedriver") # gnu/linux
elif user_browser in firefox:
browser = webdriver.Firefox()
url = "https://www.riga.lv/lv/"
browser.get(url)
browser.find_element(By.CLASS_NAME, 'cookie-accept-all').click()
if user_browser in chromium:
if os.name in ('nt', 'dos'):
browser = webdriver.Chrome("chromedriver.exe") # windows
else:
browser = webdriver.Chrome("chromedriver") # gnu/linux
elif user_browser in firefox:
browser = webdriver.Firefox()
url = "https://www.riga.lv/lv/"
browser.get(url)
browser.find_element(By.CLASS_NAME, 'cookie-accept-all').click()
browser.find_element(By.CLASS_NAME, 'search-link').click()
browser.find_element(By.CLASS_NAME, 'search-link').click()
delay = 2
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.ID, 'edit-search')))
search = browser.find_element(By.ID, 'edit-search')
search.send_keys(search_word) # writes in search line
delay = 2
WebDriverWait(browser, delay).until(
EC.presence_of_all_elements_located((By.ID, 'edit-search')))
search = browser.find_element(By.ID, 'edit-search')
search.send_keys(search_word) # writes in search line
browser.find_element(By.ID, 'search-header-button').click()
browser.find_element(By.ID, 'search-header-button').click()
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'filter-content')))
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.ID, 'filter_type_file')))
WebDriverWait(browser, delay).until(
EC.presence_of_all_elements_located((By.CLASS_NAME, 'filter-content')))
WebDriverWait(browser, delay).until(
EC.presence_of_all_elements_located((By.ID, 'filter_type_file')))
browser.find_element(By.CSS_SELECTOR, 'label[for="filter_type_file"]').click()
browser.find_element(
By.CSS_SELECTOR, 'label[for="filter_type_file"]').click()
browser.find_element(By.ID, 'search-view-button').click()
for current_page in range(1, last_page + 1):
if current_page in user_pages:
files = browser.find_elements(By.CLASS_NAME, 'file')
for file in files:
file_name = file.text
file_url = file.get_attribute('href')
file_download(file_name, file_url)
if current_page != last_page:
browser.find_element(By.CLASS_NAME, 'pager__item--next').click()
if current_page == user_pages[-1]:
break
browser.quit()
browser.find_element(By.ID, 'search-view-button').click()
for current_page in range(1, last_page + 1):
if current_page in user_pages:
files = browser.find_elements(By.CLASS_NAME, 'file')
for file in files:
file_name = file.text
file_url = file.get_attribute('href')
file_download(file_name, file_url)
if current_page != last_page:
browser.find_element(By.CLASS_NAME, 'pager__item--next').click()
if current_page == user_pages[-1]:
break
browser.quit()
def get_user_input():
if debug == True:
search_word = "dokum"
else:
search_word = input("Choose keyword to search: ")
if debug == True:
search_word = "dokum"
else:
search_word = input("Choose keyword to search: ")
last_page = get_max_page_amount(search_word)
print("\nChoose which browser to use:")
print("1 - chromium (chrome)")
print("2 - firefox")
last_page = get_max_page_amount(search_word)
print("\nChoose which browser to use:")
print("1 - chromium (chrome)")
print("2 - firefox")
if debug == True:
browser = "firefox"
else:
browser = input("").lower()
if debug == True:
browser = "firefox"
else:
browser = input("").lower()
print(f"\nChoose from which pages you want to download files (1 4 7; 2-5; all). Maximum is {last_page} pages.")
try:
if debug == True:
user_input = "16-17"
else:
user_input = input("").lower()
print(
f"\nChoose from which pages you want to download files (1 4 7; 2-5; all). Maximum is {last_page} pages.")
try:
if debug == True:
user_input = "16-17"
else:
user_input = input("").lower()
if user_input == "all":
pages = list(map(int, range(1, last_page + 1))) # creates list with all pages
else:
user_page_list = user_input.split(" ")
for page_range in user_page_list:
if "-" in page_range:
if user_input == "all":
# creates list with all pages
pages = list(map(int, range(1, last_page + 1)))
else:
user_page_list = user_input.split(" ")
for page_range in user_page_list:
if "-" in page_range:
first_num = int(page_range[:page_range.find("-")]) # gets first number
second_num = int(page_range[page_range.find("-") + 1:]) + 1 # gets second number
# gets first number
first_num = int(page_range[:page_range.find("-")])
# gets second number
second_num = int(page_range[page_range.find("-") + 1:]) + 1
if second_num > last_page: # reduces user input to max page amount
second_num = last_page
user_page_list = user_page_list + list(map(str, range(first_num, second_num + 1))) # creates list with str range
pages = [elem for elem in user_page_list if not "-" in elem] # removes all elements containing "-"
pages = list(map(int, pages)) # convers str to int
pages.sort() # sorts list
pages = list(set(pages)) # removes duplicates from list
except:
print("Enered incorrect number/s. Try again.")
return browser, pages, search_word, last_page
if second_num > last_page: # reduces user input to max page amount
second_num = last_page
user_page_list = user_page_list + \
list(map(str, range(first_num, second_num + 1))
) # creates list with str range
# removes all elements containing "-"
pages = [elem for elem in user_page_list if not "-" in elem]
pages = list(map(int, pages)) # convers str to int
pages.sort() # sorts list
pages = list(set(pages)) # removes duplicates from list
except:
print("Enered incorrect number/s. Try again.")
return browser, pages, search_word, last_page
def get_max_page_amount(keyword: str):
url = f"https://www.riga.lv/lv/search?q={keyword}&types=file"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
try:
last_page = soup.find(class_='pager__item--last').get_text().strip()
except:
try:
last_page = soup.find_all(class_='pager__item page-item')
last_page = last_page[-1].get_text().strip()[-1] # gets last number from navigation bar
except:
print("Something went wrong. Please try again or try another keyword.")
return int(last_page)
url = f"https://www.riga.lv/lv/search?q={keyword}&types=file"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
try:
last_page = soup.find(class_='pager__item--last').get_text().strip()
except:
try:
last_page = soup.find_all(class_='pager__item page-item')
# gets last number from navigation bar
last_page = last_page[-1].get_text().strip()[-1]
except:
print("Something went wrong. Please try again or try another keyword.")
return int(last_page)
def file_download(file_name, file_url):
print(f"\nNAME: {file_name}")
print(f"URL: {file_url}")
print(f"\nNAME: {file_name}")
print(f"URL: {file_url}")
path = "files"
if not exists(path):
os.mkdir(path)
path = "files"
if not exists(path):
os.mkdir(path)
response = requests.get(file_url)
if ".pdf" in file_name:
open(f"{path}/{file_name}", "wb").write(response.content)
else:
open(f"{path}/{file_name}.pdf", "wb").write(response.content)
response = requests.get(file_url)
if ".pdf" in file_name:
open(f"{path}/{file_name}", "wb").write(response.content)
else:
open(f"{path}/{file_name}.pdf", "wb").write(response.content)
def main():
get_data()
get_data()
if __name__ == '__main__':
main()
main()

View File

@ -1,26 +1,31 @@
def main():
try:
user_input = input("Input: ")
user_input_array = user_input.split(" ")
if user_input == "all":
pages = list(map(int, range(1, 17 + 1)))
else:
for page_range in user_input_array:
if "-" in page_range:
first_num = int(page_range[:page_range.find("-")]) # gets first number
second_num = int(page_range[page_range.find("-") + 1:]) + 1 # gets second number
user_input_array = user_input_array + list(map(str, range(first_num, second_num))) # creates list with str range
pages = [elem for elem in user_input_array if not "-" in elem] # removes all elements containing "-"
pages = list(map(int, pages)) # convers str to int
pages.sort() # sorts list
pages = list(set(pages)) # removes duplicates from list
print(pages)
try:
user_input = input("Input: ")
user_input_array = user_input.split(" ")
if user_input == "all":
pages = list(map(int, range(1, 17 + 1)))
else:
for page_range in user_input_array:
if "-" in page_range:
# gets first number
first_num = int(page_range[:page_range.find("-")])
# gets second number
second_num = int(page_range[page_range.find("-") + 1:]) + 1
user_input_array = user_input_array + \
list(map(str, range(first_num, second_num))
) # creates list with str range
# removes all elements containing "-"
pages = [elem for elem in user_input_array if not "-" in elem]
pages = list(map(int, pages)) # convers str to int
pages.sort() # sorts list
pages = list(set(pages)) # removes duplicates from list
print(pages)
except:
print("Something went wrong. Try again.")
except:
print("Something went wrong. Try again.")
if __name__ == '__main__':
main()
main()
# 3 1 5 2 7-11 3-30
# 3 1 5 2 7-11 3-30

View File

@ -9,7 +9,7 @@ file = pd.ExcelFile("dati_masiviem.xlsx")
data = []
for sheet_name in file.sheet_names:
data.append(file.parse(sheet_name))
data.append(file.parse(sheet_name))
# print(data[0]["Nosaukums"])
data[0]["Cena"] = round((data[0]["Pašizmaksa"] + .4) * 1.21, 2)
@ -42,6 +42,6 @@ found = data[2]["Datums2"] == "2020-09-09"
page_num = 1
with pd.ExcelWriter("new_file2.xlsx") as file:
for page in data:
page.to_excel(file, sheet_name=str(page_num), index=False)
page_num += 1
for page in data:
page.to_excel(file, sheet_name=str(page_num), index=False)
page_num += 1

View File

@ -9,7 +9,7 @@ file = pd.ExcelFile("dzivnieki.xls")
data = []
for sheet_name in file.sheet_names:
data.append(file.parse(sheet_name))
data.append(file.parse(sheet_name))
# print(data)
# print(data[0])
@ -22,6 +22,7 @@ for sheet_name in file.sheet_names:
new_data = pd.concat([data[0], data[1]]) # concatenates data
# print(new_data)
print(new_data.sort_values("Vecums", ascending=False)) # sorts table by age, inverted
# sorts table by age, inverted
print(new_data.sort_values("Vecums", ascending=False))
new_data.to_excel("new_file.xls", index=False)
new_data.to_excel("new_file.xls", index=False)

View File

@ -15,62 +15,63 @@ import matplotlib.pyplot as plt
def get_data():
data = pd.read_csv("auto_imports_mainits.csv")
data = pd.read_csv("auto_imports_mainits.csv")
data_copy = data.copy()
data_copy = data.copy()
del data_copy["normalized-losses"]
del data_copy["normalized-losses"]
dislike = ["N/A", "NA", "--"]
data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
dislike = ["N/A", "NA", "--"]
data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
# Replaces word written numbers to intigers
columns = ["num-of-doors", "num-of-cylinders"]
for column in columns:
for value in data_copy3[column]:
try:
data_copy3 = data_copy3.replace(to_replace=value, value=w2n.word_to_num(value))
except:
pass
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
# Replaces word written numbers to intigers
columns = ["num-of-doors", "num-of-cylinders"]
for column in columns:
for value in data_copy3[column]:
try:
data_copy3 = data_copy3.replace(
to_replace=value, value=w2n.word_to_num(value))
except:
pass
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
# Leaves only columns that contain numbers
data_copy4 = data_copy3.copy()
for column in data_copy4:
if isinstance(data_copy4[column][0], str):
del data_copy4[column]
print(data_copy4)
return data_copy4
# Leaves only columns that contain numbers
data_copy4 = data_copy3.copy()
for column in data_copy4:
if isinstance(data_copy4[column][0], str):
del data_copy4[column]
print(data_copy4)
return data_copy4
def graph_plot():
data = get_data()
data = get_data()
sns.set_style("whitegrid")
plt.figure(figsize=(15, 10))
sns.heatmap(data.corr())
plt.savefig("plot1.png")
# plt.show()
sns.set_style("whitegrid")
plt.figure(figsize=(15, 10))
sns.heatmap(data.corr())
plt.savefig("plot1.png")
# plt.show()
# korealācija novērojama starp kolonnām [length,width,wheel-base] un [engine-size,price,horsepower]
# noderīga ir otrā korelācija, jo tā atklāj to savstarpējo ietekmi
# korealācija novērojama starp kolonnām [length,width,wheel-base] un [engine-size,price,horsepower]
# noderīga ir otrā korelācija, jo tā atklāj to savstarpējo ietekmi
# matplotlib heatmap veido korealāciju starp datiem savstarpēji salīdzinot to vērtības un norādot iegūtos koeficientus
# seaborn heatmap veido korealāciju starp datu vērtībām pēc pašnoteiktas korealācijas skalas
# matplotlib heatmap veido korealāciju starp datiem savstarpēji salīdzinot to vērtības un norādot iegūtos koeficientus
# seaborn heatmap veido korealāciju starp datu vērtībām pēc pašnoteiktas korealācijas skalas
sns.displot(data["price"])
plt.savefig("plot2.png")
# plt.show()
sns.displot(data["price"])
plt.savefig("plot2.png")
# plt.show()
plt.scatter(data["price"], data["engine-size"])
plt.savefig("plot3.png")
# plt.show()
plt.scatter(data["price"], data["engine-size"])
plt.savefig("plot3.png")
# plt.show()
sns.scatterplot(data["price"], data["engine-size"])
plt.savefig("plot4.png")
# plt.show()
sns.scatterplot(data["price"], data["engine-size"])
plt.savefig("plot4.png")
# plt.show()
if __name__ == '__main__':
# get_data()
graph_plot()
# get_data()
graph_plot()

View File

@ -2,75 +2,76 @@
# Date - 04.02.2022
# Title - Classwork
import matplotlib.pyplot as plt
import pandas as pd
from word2number import w2n
import seaborn as sns
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
# mathplotlib ir bibliotēka statisku, animētu un interaktīvu vizualizāciju izveidei
# seaborn padara matplotlib sarežģītākos momentus par vienkāršākiem
def get_data():
data = pd.read_csv("auto_imports_mainits.csv")
data = pd.read_csv("auto_imports_mainits.csv")
data_copy = data.copy()
data_copy = data.copy()
del data_copy["normalized-losses"]
del data_copy["normalized-losses"]
dislike = ["N/A", "NA", "--"]
data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
dislike = ["N/A", "NA", "--"]
data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
# Replaces word written numbers to intigers
columns = ["num-of-doors", "num-of-cylinders"]
for column in columns:
for value in data_copy3[column]:
try:
data_copy3 = data_copy3.replace(to_replace=value, value=w2n.word_to_num(value))
except:
pass
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
# Replaces word written numbers to intigers
columns = ["num-of-doors", "num-of-cylinders"]
for column in columns:
for value in data_copy3[column]:
try:
data_copy3 = data_copy3.replace(
to_replace=value, value=w2n.word_to_num(value))
except:
pass
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
# Leaves only columns that contain numbers
data_copy4 = data_copy3.copy()
for column in data_copy4:
if isinstance(data_copy4[column][0], str):
del data_copy4[column]
print(data_copy4)
return data_copy4
# Leaves only columns that contain numbers
data_copy4 = data_copy3.copy()
for column in data_copy4:
if isinstance(data_copy4[column][0], str):
del data_copy4[column]
print(data_copy4)
return data_copy4
def graph_plot():
data = get_data()
data = get_data()
sns.set_style("whitegrid")
plt.figure(figsize=(15, 10))
sns.heatmap(data.corr())
plt.savefig("plot1.png")
plt.show()
sns.set_style("whitegrid")
plt.figure(figsize=(15, 10))
sns.heatmap(data.corr())
plt.savefig("plot1.png")
plt.show()
# korealācija novērojama starp kolonnām [length,width,wheel-base] un [engine-size,price,horsepower]
# noderīga ir otrā korelācija, jo tā atklāj to savstarpējo ietekmi
# korealācija novērojama starp kolonnām [length,width,wheel-base] un [engine-size,price,horsepower]
# noderīga ir otrā korelācija, jo tā atklāj to savstarpējo ietekmi
# matplotlib heatmap veido korealāciju starp datiem savstarpēji salīdzinot to vērtības un norādot iegūtos koeficientus
# seaborn heatmap veido korealāciju starp datu vērtībām pēc pašnoteiktas korealācijas skalas
# matplotlib heatmap veido korealāciju starp datiem savstarpēji salīdzinot to vērtības un norādot iegūtos koeficientus
# seaborn heatmap veido korealāciju starp datu vērtībām pēc pašnoteiktas korealācijas skalas
sns.displot(data["price"])
plt.savefig("plot2.png")
plt.show()
sns.displot(data["price"])
plt.savefig("plot2.png")
plt.show()
plt.scatter(data["price"], data["engine-size"])
plt.savefig("plot3.png")
plt.show()
plt.scatter(data["price"], data["engine-size"])
plt.savefig("plot3.png")
plt.show()
sns.scatterplot(data["price"], data["engine-size"])
plt.savefig("plot4.png")
plt.show()
sns.scatterplot(data["price"], data["engine-size"])
plt.savefig("plot4.png")
plt.show()
if __name__ == '__main__':
# get_data()
graph_plot()
# get_data()
graph_plot()

View File

@ -18,17 +18,20 @@ data = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
del data["normalized-losses"]
select_data = data[["make", "engine-size", "num-of-doors"]]
select_data = select_data.sort_values(by=["make", "engine-size", "num-of-doors"])
select_data = select_data.sort_values(
by=["make", "engine-size", "num-of-doors"])
select_data = select_data.drop_duplicates()
col_width = usable_w / 3
height = pdf.font_size * 2
for i in range(select_data.shape[0]):
pdf.cell(col_width, height, str(select_data["make"].iloc[i]), border=1)
pdf.cell(col_width, height, str(select_data["engine-size"].iloc[i]), border=1)
pdf.cell(col_width, height, str(select_data["num-of-doors"].iloc[i]), border=1)
pdf.ln(height)
pdf.cell(col_width, height, str(select_data["make"].iloc[i]), border=1)
pdf.cell(col_width, height, str(
select_data["engine-size"].iloc[i]), border=1)
pdf.cell(col_width, height, str(
select_data["num-of-doors"].iloc[i]), border=1)
pdf.ln(height)
# pdf.image("output.png", x=None, y=None, w=usable_w, h=0)
pdf.output("output.pdf")
pdf.output("output.pdf")

View File

@ -49,190 +49,206 @@ series_photos = {
class priceGraph:
def __init__(self, data, pos, title, x_value, xlabel, xticks=None, y_value=PRICE, ylabel="Price"):
self.pos = pos
self.x_value = data[x_value]
self.y_value = data[y_value]
self.title = title
self.xlabel = xlabel
self.ylabel = ylabel
self.xticks = xticks
def __init__(self, data, pos, title, x_value, xlabel, xticks=None, y_value=PRICE, ylabel="Price"):
self.pos = pos
self.x_value = data[x_value]
self.y_value = data[y_value]
self.title = title
self.xlabel = xlabel
self.ylabel = ylabel
self.xticks = xticks
def _graph_price(self):
plot = plt.subplot2grid((3, 2), self.pos)
plot.scatter(self.x_value, self.y_value)
plot.set_title(self.title)
plot.set_xlabel(self.xlabel)
plot.set_ylabel(self.ylabel)
if self.xticks != None:
plot.set_xticks(self.xticks)
def _graph_price(self):
plot = plt.subplot2grid((3, 2), self.pos)
plot.scatter(self.x_value, self.y_value)
plot.set_title(self.title)
plot.set_xlabel(self.xlabel)
plot.set_ylabel(self.ylabel)
if self.xticks != None:
plot.set_xticks(self.xticks)
def read():
files = list(Path(Path(__file__).parent.absolute()).glob("**/*.xlsx"))
files = list(Path(Path(__file__).parent.absolute()).glob("**/*.xlsx"))
for file_path in files:
all_df.append(pd.read_excel(file_path))
df_combined = pd.concat(all_df).reset_index(drop=True) # combine DataFrames
df_combined.sort_values(by=[PRICE, PUB_DATE], inplace=True) # sort DataFrame
df_combined.drop_duplicates(keep="first", inplace=True) # drop duplicates
# replaces floor value to intiger
for value in df_combined[FLOOR]:
df_combined = df_combined.replace(value, int(float(value[:value.find("/")])))
for file_path in files:
all_df.append(pd.read_excel(file_path))
df_combined = pd.concat(all_df).reset_index(
drop=True) # combine DataFrames
df_combined.sort_values(by=[PRICE, PUB_DATE],
inplace=True) # sort DataFrame
df_combined.drop_duplicates(keep="first", inplace=True) # drop duplicates
# replaces floor value to intiger
for value in df_combined[FLOOR]:
df_combined = df_combined.replace(
value, int(float(value[:value.find("/")])))
# replaces price value to intiger
for value in df_combined[PRICE]:
df_combined = df_combined.replace(value, replace_value(value, " ", ",", ""))
# replaces price value to intiger
for value in df_combined[PRICE]:
df_combined = df_combined.replace(
value, replace_value(value, " ", ",", ""))
# replaces "Citi" to 7
for _ in df_combined[ROOM_AMOUNT]:
df_combined = df_combined.replace(["citi", "Citi"], "7")
# replaces "Citi" to 7
for _ in df_combined[ROOM_AMOUNT]:
df_combined = df_combined.replace(["citi", "Citi"], "7")
# converts room amount to intiger
for value in df_combined[ROOM_AMOUNT]:
df_combined = df_combined.replace(value, int(value))
# converts room amount to intiger
for value in df_combined[ROOM_AMOUNT]:
df_combined = df_combined.replace(value, int(value))
# converts to datetime
df_combined[PUB_DATE] = pd.to_datetime(df_combined[PUB_DATE], format="%d.%m.%Y").dt.date
# converts to datetime
df_combined[PUB_DATE] = pd.to_datetime(
df_combined[PUB_DATE], format="%d.%m.%Y").dt.date
df_combined.to_excel("output/excel/combined.xlsx", index=False)
return df_combined.sort_values(by=PUB_DATE)
df_combined.to_excel("output/excel/combined.xlsx", index=False)
return df_combined.sort_values(by=PUB_DATE)
# replace value
replace_value = lambda value, find, replace, replace_to: int(value[:value.find(find)].replace(replace, replace_to))
def replace_value(value, find, replace, replace_to): return int(
value[:value.find(find)].replace(replace, replace_to))
def graph_corr(data):
data_corr = data.copy()
plt.rc("font", size=8)
# gets all series
series = []
for i in data_corr[SERIES]:
if i not in series:
series.append(i)
# change series names to numbers
data_corr[SERIES] = data_corr[SERIES].replace(series, range(len(series)))
data_corr = data.copy()
plt.rc("font", size=8)
# gets all series
series = []
for i in data_corr[SERIES]:
if i not in series:
series.append(i)
# change series names to numbers
data_corr[SERIES] = data_corr[SERIES].replace(series, range(len(series)))
sns.heatmap(data_corr.corr())
plt.savefig(f"{output_path}/korelacija.png")
sns.heatmap(data_corr.corr())
plt.savefig(f"{output_path}/korelacija.png")
def graph_price(data):
plt.figure(figsize=(50, 30))
plt.rc("font", size=15)
plt.figure(figsize=(50, 30))
plt.rc("font", size=15)
plot1 = priceGraph(data, (0, 0), "Price to floor", FLOOR, "Floor", range(1, max(data[FLOOR]) + 1))
plot2 = priceGraph(data, (0, 1), "Price to room amount", ROOM_AMOUNT, "Room amount")
plot3 = priceGraph(data, (1, 0), "Price to quadrature", QUADRATURE, "Quadrature")
plot4 = priceGraph(data, (1, 1), "Price to series", SERIES, "Series")
plot5 = priceGraph(data, (2, 0), "Price to date", PUB_DATE, "Date")
plot1 = priceGraph(data, (0, 0), "Price to floor", FLOOR,
"Floor", range(1, max(data[FLOOR]) + 1))
plot2 = priceGraph(data, (0, 1), "Price to room amount",
ROOM_AMOUNT, "Room amount")
plot3 = priceGraph(data, (1, 0), "Price to quadrature",
QUADRATURE, "Quadrature")
plot4 = priceGraph(data, (1, 1), "Price to series", SERIES, "Series")
plot5 = priceGraph(data, (2, 0), "Price to date", PUB_DATE, "Date")
plot1._graph_price()
plot2._graph_price()
plot3._graph_price()
plot4._graph_price()
plot5._graph_price()
plot1._graph_price()
plot2._graph_price()
plot3._graph_price()
plot4._graph_price()
plot5._graph_price()
plt.savefig(f"{output_path}/cenu_grafiki.png")
plt.savefig(f"{output_path}/cenu_grafiki.png")
def create_pdf(data):
pdf = FPDF("P", "mm", "A4")
pdf.add_page()
pdf.add_font("Roboto", fname="fonts/Roboto-Regular.ttf", uni=True)
pdf.set_font("Roboto", size=12)
pdf = FPDF("P", "mm", "A4")
pdf.add_page()
pdf.add_font("Roboto", fname="fonts/Roboto-Regular.ttf", uni=True)
pdf.set_font("Roboto", size=12)
usable_w = pdf.w - 2 * pdf.l_margin
width = usable_w / 7
height = pdf.font_size * 2
LINE_HEIGHT = 5
usable_w = pdf.w - 2 * pdf.l_margin
width = usable_w / 7
height = pdf.font_size * 2
LINE_HEIGHT = 5
# table head
for column in COLUMNS:
if column == PUB_DATE:
col_width = width * 2
else:
col_width = width
pdf.cell(col_width, height, column, border=1)
# table head
for column in COLUMNS:
if column == PUB_DATE:
col_width = width * 2
else:
col_width = width
pdf.cell(col_width, height, column, border=1)
pdf.ln(height)
# table contents
for _ in range(5):
rand_num = randint(2, len(data))
for column in COLUMNS:
if column == PUB_DATE:
col_width = width * 2
else:
col_width = width
pdf.cell(col_width, height, str(data[column].iloc[rand_num]), border=1)
pdf.ln(height)
pdf.ln(height)
# table contents
for _ in range(5):
rand_num = randint(2, len(data))
for column in COLUMNS:
if column == PUB_DATE:
col_width = width * 2
else:
col_width = width
pdf.cell(col_width, height, str(
data[column].iloc[rand_num]), border=1)
pdf.ln(height)
pdf.ln(height)
pdf.image(f"{output_path}/korelacija.png", w=usable_w) # corr graph
pdf.write(LINE_HEIGHT, "Starp istabu skaitu un cenu, kvadratūru un cenu ir liela korelācija.")
pdf.ln(height)
pdf.image(f"{output_path}/cenu_grafiki.png", w=usable_w) # price graph
pdf.ln(height)
pdf.image(f"{output_path}/korelacija.png", w=usable_w) # corr graph
pdf.write(
LINE_HEIGHT, "Starp istabu skaitu un cenu, kvadratūru un cenu ir liela korelācija.")
pdf.ln(height)
pdf.image(f"{output_path}/cenu_grafiki.png", w=usable_w) # price graph
# price graph conclusions
text = """
# price graph conclusions
text = """
"Price to floor" grafiks - lielākā daļa pārdodamo dzīvokļu ir līdz 6. stāvam.
"Price to room amount" grafiks - veido normālo sadalījumu (Gausa sadalījumu).
"Price to quadrature" grafiks - jo lielāka dzīvokļa platība, jo dārgāks dzīvoklis.
"Price to series" grafiks - jaunie, renovētie un pēc kara dzīvokļi ir dārgāki.
"Price to date" grafiks - nav nekādas sakarības.
"""
for txt in text.split("\n"):
pdf.write(LINE_HEIGHT, txt.strip())
pdf.ln(LINE_HEIGHT)
for txt in text.split("\n"):
pdf.write(LINE_HEIGHT, txt.strip())
pdf.ln(LINE_HEIGHT)
# mean/mode values
text = [
"Vidējā cena: ", "Vidējā cena attiecībā pret kvadratūru: ", "Sērijas moda: ", "Vidējā cena attiecībā pret istabu skaitu: ",
"Vidējā cena attiecībā pret stāvu: "
]
values = [
round(mean(data[PRICE]), 2),
round(mean(data[PRICE]) / mean(data[QUADRATURE])),
mode(data[SERIES]),
round(mean(data[PRICE]) / mean(data[ROOM_AMOUNT])),
round(mean(data[PRICE]) / mean(data[FLOOR]))
]
for txt, value in zip(text, values):
pdf.write(LINE_HEIGHT, f"{txt}{value}")
pdf.ln(LINE_HEIGHT)
# mean/mode values
text = [
"Vidējā cena: ", "Vidējā cena attiecībā pret kvadratūru: ", "Sērijas moda: ", "Vidējā cena attiecībā pret istabu skaitu: ",
"Vidējā cena attiecībā pret stāvu: "
]
values = [
round(mean(data[PRICE]), 2),
round(mean(data[PRICE]) / mean(data[QUADRATURE])),
mode(data[SERIES]),
round(mean(data[PRICE]) / mean(data[ROOM_AMOUNT])),
round(mean(data[PRICE]) / mean(data[FLOOR]))
]
for txt, value in zip(text, values):
pdf.write(LINE_HEIGHT, f"{txt}{value}")
pdf.ln(LINE_HEIGHT)
# adds photo of most frequent series
response = requests.get(series_photos[mode(data[SERIES])])
img = Image.open(BytesIO(response.content))
pdf.image(img)
# adds photo of most frequent series
response = requests.get(series_photos[mode(data[SERIES])])
img = Image.open(BytesIO(response.content))
pdf.image(img)
pdf.output("output/pdf/secinajumi.pdf")
pdf.output("output/pdf/secinajumi.pdf")
def make_dir():
if "output" not in listdir():
mkdir("output")
if "excel" not in listdir("output"):
mkdir("output/excel")
if "graphs" not in listdir("output"):
mkdir("output/graphs")
if "pdf" not in listdir("output"):
mkdir("output/pdf")
if "output" not in listdir():
mkdir("output")
if "excel" not in listdir("output"):
mkdir("output/excel")
if "graphs" not in listdir("output"):
mkdir("output/graphs")
if "pdf" not in listdir("output"):
mkdir("output/pdf")
def graph_plot():
data = read()
graph_corr(data)
graph_price(data)
create_pdf(data)
data = read()
graph_corr(data)
graph_price(data)
create_pdf(data)
flats_riga = SS("https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga")
flats_rigareg = SS("https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg")
flats_aizkraukle = SS("https://www.ss.com/lv/real-estate/flats/aizkraukle-and-reg/sell/", "aizkraukle")
flats_tukums = SS("https://www.ss.com/lv/real-estate/flats/tukums-and-reg/sell/", "tukums")
flats_ogre = SS("https://www.ss.com/lv/real-estate/flats/ogre-and-reg/sell/", "ogre")
flats_riga = SS(
"https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga")
flats_rigareg = SS(
"https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg")
flats_aizkraukle = SS(
"https://www.ss.com/lv/real-estate/flats/aizkraukle-and-reg/sell/", "aizkraukle")
flats_tukums = SS(
"https://www.ss.com/lv/real-estate/flats/tukums-and-reg/sell/", "tukums")
flats_ogre = SS(
"https://www.ss.com/lv/real-estate/flats/ogre-and-reg/sell/", "ogre")
OPERATIONS = """
python pd_pandas_k_f_cagulis.py
@ -245,15 +261,15 @@ Operations:
def main(argv):
for arg in argv:
if arg in ["-h", "--help"]:
print(OPERATIONS)
exit()
elif arg in ["-n", "--new"]:
flats_riga.get_data()
make_dir()
graph_plot()
for arg in argv:
if arg in ["-h", "--help"]:
print(OPERATIONS)
exit()
elif arg in ["-n", "--new"]:
flats_riga.get_data()
make_dir()
graph_plot()
if __name__ == "__main__":
main(sys.argv[1:])
main(sys.argv[1:])

View File

@ -17,94 +17,110 @@ HEADERS = {
class SS:
def __init__(self, url, name):
self.url = url
self.name = name
def __init__(self, url, name):
self.url = url
self.name = name
def _get_page_amount(self):
page = requests.get(self.url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
def _get_page_amount(self):
page = requests.get(self.url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
try:
last_url = soup.find(class_='td2').findChild('a')['href']
page_amount = last_url[last_url.find("page") + 4:last_url.find(".html")]
except:
page_amount = 1
# print(f"Page amount = {page_amount}")
try:
last_url = soup.find(class_='td2').findChild('a')['href']
page_amount = last_url[last_url.find(
"page") + 4:last_url.find(".html")]
except:
page_amount = 1
# print(f"Page amount = {page_amount}")
return int(page_amount)
return int(page_amount)
def get_data(self):
items = []
item_no = 1
page_amount = self._get_page_amount()
# widgets = ["Getting data...", pbar.Bar("*")]
# bar = pbar.ProgressBar(max_value=page_amount, widgets=widgets).start()
bar = LoadBar(max=page_amount * 30, head="#", body="#")
bar.start()
def get_data(self):
items = []
item_no = 1
page_amount = self._get_page_amount()
# widgets = ["Getting data...", pbar.Bar("*")]
# bar = pbar.ProgressBar(max_value=page_amount, widgets=widgets).start()
bar = LoadBar(max=page_amount * 30, head="#", body="#")
bar.start()
for page_number in range(1, page_amount + 1):
for page_number in range(1, page_amount + 1):
url = self.url + f"/page{page_number}.html"
page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
url = self.url + f"/page{page_number}.html"
page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser')
# item ids
ids = [tag['id'] for tag in soup.select('tr[id]')] # creates list with ids
ids = [x for x in ids if "tr_bnr" not in x] # removes "tr_bnr" elements from list
ids.remove("head_line") # removes first "head_line" id
# print(f"Page {page_number}")
# item ids
ids = [tag['id']
for tag in soup.select('tr[id]')] # creates list with ids
# removes "tr_bnr" elements from list
ids = [x for x in ids if "tr_bnr" not in x]
ids.remove("head_line") # removes first "head_line" id
# print(f"Page {page_number}")
# getting item data
for id in soup.find_all(id=ids):
# print(f"Item {item_no}")
bar.update(step=item_no)
# getting item data
for id in soup.find_all(id=ids):
# print(f"Item {item_no}")
bar.update(step=item_no)
item_no += 1
item_no += 1
for elem in id.find_all(class_='msga2-o pp6'):
items.append(elem.get_text())
for elem in id.find_all(class_='msga2-o pp6'):
items.append(elem.get_text())
if len(id.find_all(class_='msga2-o pp6')) == 7:
del items[-2]
if len(id.find_all(class_='msga2-o pp6')) == 7:
del items[-2]
# adverts url
item_url = id.findChild(class_='msg2').findChild('div').findChild('a')['href'] # gets url
item_url = "https://www.ss.com" + item_url
item_page = requests.get(item_url, headers=HEADERS)
item_soup = BeautifulSoup(item_page.content, 'html.parser')
# adverts url
item_url = id.findChild(class_='msg2').findChild(
'div').findChild('a')['href'] # gets url
item_url = "https://www.ss.com" + item_url
item_page = requests.get(item_url, headers=HEADERS)
item_soup = BeautifulSoup(item_page.content, 'html.parser')
# adverts full text
item_text = item_soup.find(id='msg_div_msg').get_text() # gets full text
item_text = item_text[:item_text.find("Pilsēta:")] # removes text last part (table)
items.append(item_text)
# adverts full text
item_text = item_soup.find(
id='msg_div_msg').get_text() # gets full text
# removes text last part (table)
item_text = item_text[:item_text.find("Pilsēta:")]
items.append(item_text)
# adverts publication date
item_date = item_soup.find_all('td', class_='msg_footer') # gets all 'msg_footer' class'
item_date = item_date[2].get_text() # extracts 3rd element
items.append(item_date[8:18]) # crops date
bar.end()
chunk_size = 8
chunked_items_list = [items[i:i + chunk_size] for i in range(0, len(items), chunk_size)] # combines each 'chunk_size' elements into array
columns = ["Atrašanās vieta", "Istabu skaits", "Kvadratūra", "Stāvs", "Sērija", "Cena", "Pilns sludinājuma teksts", "Izvietošanas datums"]
df = pd.DataFrame(chunked_items_list, columns=columns)
time = datetime.now().strftime("%d%m%y%H%M%S") # current time
if "excel" not in listdir("output"):
mkdir("output/excel")
df.to_excel(excel_writer=f"output/excel/ss_{self.name}_{time}.xlsx", index=False)
# adverts publication date
# gets all 'msg_footer' class'
item_date = item_soup.find_all('td', class_='msg_footer')
item_date = item_date[2].get_text() # extracts 3rd element
items.append(item_date[8:18]) # crops date
bar.end()
chunk_size = 8
# combines each 'chunk_size' elements into array
chunked_items_list = [items[i:i + chunk_size]
for i in range(0, len(items), chunk_size)]
columns = ["Atrašanās vieta", "Istabu skaits", "Kvadratūra", "Stāvs",
"Sērija", "Cena", "Pilns sludinājuma teksts", "Izvietošanas datums"]
df = pd.DataFrame(chunked_items_list, columns=columns)
time = datetime.now().strftime("%d%m%y%H%M%S") # current time
if "excel" not in listdir("output"):
mkdir("output/excel")
df.to_excel(
excel_writer=f"output/excel/ss_{self.name}_{time}.xlsx", index=False)
flats_riga = SS("https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga")
flats_rigareg = SS("https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg")
flats_aizkraukle = SS("https://www.ss.com/lv/real-estate/flats/aizkraukle-and-reg/sell/", "aizkraukle")
flats_tukums = SS("https://www.ss.com/lv/real-estate/flats/tukums-and-reg/sell/", "tukums")
flats_ogre = SS("https://www.ss.com/lv/real-estate/flats/ogre-and-reg/sell/", "ogre")
flats_riga = SS(
"https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga")
flats_rigareg = SS(
"https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg")
flats_aizkraukle = SS(
"https://www.ss.com/lv/real-estate/flats/aizkraukle-and-reg/sell/", "aizkraukle")
flats_tukums = SS(
"https://www.ss.com/lv/real-estate/flats/tukums-and-reg/sell/", "tukums")
flats_ogre = SS(
"https://www.ss.com/lv/real-estate/flats/ogre-and-reg/sell/", "ogre")
def main():
flats_riga.get_data()
# flats_rigareg.get_data()
flats_riga.get_data()
# flats_rigareg.get_data()
if __name__ == '__main__':
main()
main()

View File

@ -7,24 +7,24 @@ import pandas as pd
def main():
print(consuption(6.7, 2500))
print(consuption(6.7, 2500))
def try_except():
try:
# print(error) # "Name Error"
data = pd.read_csv("auto_imports_mainits.csx") # "Error 2"
try:
# print(error) # "Name Error"
data = pd.read_csv("auto_imports_mainits.csx") # "Error 2"
except NameError:
print("Name Error")
except NameError:
print("Name Error")
except Exception as error:
print(error)
except Exception as error:
print(error)
except:
print("Error 2")
except:
print("Error 2")
if __name__ == '__main__':
# main()
try_except()
# main()
try_except()

View File

@ -6,13 +6,13 @@ import pandas as pd
def main():
data = pd.read_csv("auto_imports_mainits.csv")
blank = data.isnull().any().sum()
print(f"There are empty spaces in {blank} columns")
data = pd.read_csv("auto_imports_mainits.csv")
blank = data.isnull().any().sum()
print(f"There are empty spaces in {blank} columns")
print(data.isnull().sum())
print(data.columns[data.isnull().any()])
print(data.isnull().sum())
print(data.columns[data.isnull().any()])
if __name__ == '__main__':
main()
main()

View File

@ -3,4 +3,6 @@ import pandas
dati = pandas.read_csv('auto_imports_mainits.csv')
for index, element in enumerate(dati.isnull().sum()):
if element != 0: print(f"| {dati.columns[index]}" + " " * (25 - len(str(dati.columns[index]))) + f"{element}")
if element != 0:
print(f"| {dati.columns[index]}" + " " * (25 -
len(str(dati.columns[index]))) + f"{element}")

View File

@ -1,11 +1,11 @@
def consuption(consuption: float, distance: int, price: float = 1.34):
result = distance / 100 * consuption * price
return round(result, 3)
result = distance / 100 * consuption * price
return round(result, 3)
def main():
print(consuption(7.2, 7200))
print(consuption(7.2, 7200))
if __name__ == '__main__':
main()
main()

View File

@ -6,17 +6,18 @@ import pandas as pd
def main():
data = pd.read_csv("auto_imports_mainits.csv")
# 1st method
for column in data.columns:
if data[column].isnull().sum() > 0:
print(f"{column} {data[column].isnull().sum()}")
data = pd.read_csv("auto_imports_mainits.csv")
# 1st method
for column in data.columns:
if data[column].isnull().sum() > 0:
print(f"{column} {data[column].isnull().sum()}")
print("-" * 22)
print("-" * 22)
# 2nd method
print(pd.DataFrame(data.isnull().sum(), data.columns[data.isnull().any()]).to_string(header=None))
# 2nd method
print(pd.DataFrame(data.isnull().sum(),
data.columns[data.isnull().any()]).to_string(header=None))
if __name__ == '__main__':
main()
main()

View File

@ -7,75 +7,76 @@ from word2number import w2n
def main():
data = pd.read_csv("auto_imports_mainits.csv")
data = pd.read_csv("auto_imports_mainits.csv")
# summary = data["normalized-losses"].notnull() # returns boolean
# print(data[summary], "\n") # "normalized-losses" is not empty
# print(data[~summary]) # inverts all the bits
# print(len(data[~summary]))
# summary = data["normalized-losses"].notnull() # returns boolean
# print(data[summary], "\n") # "normalized-losses" is not empty
# print(data[~summary]) # inverts all the bits
# print(len(data[~summary]))
data_copy = data.copy()
data_copy = data.copy()
# Delete rows with empty spots
# print(f"Before erasing: {data_copy.shape}")
# print(f"After erasing: {data_copy.dropna().shape}")
# Delete rows with empty spots
# print(f"Before erasing: {data_copy.shape}")
# print(f"After erasing: {data_copy.dropna().shape}")
# Delete column
# print(f"Before erasing: {data_copy.shape}")
del data_copy["normalized-losses"]
# print(f"After erasing: {data_copy.shape}")
# print(f"Blank spots: {data_copy.isnull().any().sum()}")
# Delete column
# print(f"Before erasing: {data_copy.shape}")
del data_copy["normalized-losses"]
# print(f"After erasing: {data_copy.shape}")
# print(f"Blank spots: {data_copy.isnull().any().sum()}")
# data_copy2 = data_copy.copy()
# print(data_copy2.head())
# data_copy2.drop(data_copy2.columns[[0, 1]], axis=1, inplace=True)
# print(data_copy2.head())
# data_copy2 = data_copy.copy()
# print(data_copy2.head())
# data_copy2.drop(data_copy2.columns[[0, 1]], axis=1, inplace=True)
# print(data_copy2.head())
dislike = ["N/A", "NA", "--"]
data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
dislike = ["N/A", "NA", "--"]
data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
# Mean
# print(data_copy3.iloc[52], "\n")
# mean = data_copy3["bore"].mean()
# data_copy3["bore"].fillna(mean, inplace=True)
# print(data_copy3.iloc[52])
# Mean
# print(data_copy3.iloc[52], "\n")
# mean = data_copy3["bore"].mean()
# data_copy3["bore"].fillna(mean, inplace=True)
# print(data_copy3.iloc[52])
# Median
# print(data_copy3.iloc[53], "\n")
# median = data_copy3["bore"].median()
# data_copy3["bore"].fillna(median, inplace=True)
# print(data_copy3.iloc[53])
# Median
# print(data_copy3.iloc[53], "\n")
# median = data_copy3["bore"].median()
# data_copy3["bore"].fillna(median, inplace=True)
# print(data_copy3.iloc[53])
# Mode
# print(data_copy3.iloc[60], "\n")
# mode = data_copy3["bore"].mode()
# data_copy3["bore"].fillna(mode, inplace=True)
# print(data_copy3.iloc[60])
# Mode
# print(data_copy3.iloc[60], "\n")
# mode = data_copy3["bore"].mode()
# data_copy3["bore"].fillna(mode, inplace=True)
# print(data_copy3.iloc[60])
# print(data_copy3.dtypes)
# print(data_copy3.dtypes)
# data_copy3["curb-weight"] = pd.to_numeric(data_copy3["curb-weight"], errors='coerce')
# data_copy3["curb-weight"] = data_copy3["curb-weight"].astype("float64")
# print(data_copy3.dtypes)
# data_copy3["curb-weight"] = pd.to_numeric(data_copy3["curb-weight"], errors='coerce')
# data_copy3["curb-weight"] = data_copy3["curb-weight"].astype("float64")
# print(data_copy3.dtypes)
# Replaces word written numbers to intigers
columns = ["num-of-doors", "num-of-cylinders"]
for column in columns:
for value in data_copy3[column]:
try:
data_copy3 = data_copy3.replace(to_replace=value, value=w2n.word_to_num(value))
print(type(w2n.word_to_num(value)))
except:
pass
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
# Replaces word written numbers to intigers
columns = ["num-of-doors", "num-of-cylinders"]
for column in columns:
for value in data_copy3[column]:
try:
data_copy3 = data_copy3.replace(
to_replace=value, value=w2n.word_to_num(value))
print(type(w2n.word_to_num(value)))
except:
pass
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
# Leaves only columns that contain numbers
data_copy4 = data_copy3.copy()
for column in data_copy4:
if isinstance(data_copy4[column][0], str):
del data_copy4[column]
print(data_copy4)
# Leaves only columns that contain numbers
data_copy4 = data_copy3.copy()
for column in data_copy4:
if isinstance(data_copy4[column][0], str):
del data_copy4[column]
print(data_copy4)
if __name__ == '__main__':
main()
main()

View File

@ -7,38 +7,42 @@ CHAPTERS = 61
# creates file with chapters and row numbers
def read_array(document):
with open(document, "r", encoding='utf-8') as book:
lines = [line.strip('\n') for line in book] # removes 'enter' characters
with open('array_output.txt', 'w') as output:
for i in range(1, CHAPTERS + 1):
line = lines.index(f"Chapter {i}") + 1 # finds all chapter indexes/lines
output.write(f"Line {line} - Chapter {i}\n") # writes line in file
with open(document, "r", encoding='utf-8') as book:
lines = [line.strip('\n')
for line in book] # removes 'enter' characters
with open('array_output.txt', 'w') as output:
for i in range(1, CHAPTERS + 1):
# finds all chapter indexes/lines
line = lines.index(f"Chapter {i}") + 1
output.write(f"Line {line} - Chapter {i}\n") # writes line in file
# creates file with chapter positions
def read_string(document):
with open(document, "r", encoding='utf-8') as book:
lines = book.read()
with open('str_output.txt', 'w') as output:
for i in range(1, CHAPTERS + 1):
_, position = re.finditer(rf"\bChapter {i}\b", lines) # finds all chapter positions
output.write(f"Position {position.start()} - Chapter {i}\n") # writes position in file
with open(document, "r", encoding='utf-8') as book:
lines = book.read()
with open('str_output.txt', 'w') as output:
for i in range(1, CHAPTERS + 1):
# finds all chapter positions
_, position = re.finditer(rf"\bChapter {i}\b", lines)
# writes position in file
output.write(f"Position {position.start()} - Chapter {i}\n")
def read_book(document):
read_array(document)
read_string(document)
read_array(document)
read_string(document)
def main():
try:
read_book("book.txt")
except:
try:
read_book("1342-0.txt")
except:
read_book(input("Ievadiet faila nosaukumu: "))
try:
read_book("book.txt")
except:
try:
read_book("1342-0.txt")
except:
read_book(input("Ievadiet faila nosaukumu: "))
if __name__ == '__main__':
main()
main()

View File

@ -8,91 +8,95 @@ data = pd.read_csv("company_sales_data.csv")
def task_1():
plt.figure(figsize=(10, 6)) # (x, y)
x = range(len(data["month_number"])) # gets range of months
plt.plot(x, data["total_profit"]) # sets up the plot
plt.xticks(x, data["month_number"], fontsize=15) # sets x value step
plt.yticks(fontsize=15)
plt.ylim(ymin=100000) # sets minimal y value
plt.figure(figsize=(10, 6)) # (x, y)
x = range(len(data["month_number"])) # gets range of months
plt.plot(x, data["total_profit"]) # sets up the plot
plt.xticks(x, data["month_number"], fontsize=15) # sets x value step
plt.yticks(fontsize=15)
plt.ylim(ymin=100000) # sets minimal y value
set_labels("Company profit per month", "Month number", "Total profit")
set_labels("Company profit per month", "Month number", "Total profit")
plt.show()
plt.show()
def task_2():
plt.figure(figsize=(10, 6)) # (x, y)
plt.figure(figsize=(10, 6)) # (x, y)
x = range(len(data["month_number"])) # gets range of months
x = range(len(data["month_number"])) # gets range of months
data_list = list(data.columns)[1:-2] # gets and trims column names
data_list = list(data.columns)[1:-2] # gets and trims column names
for column in data_list:
plt.plot(x, data[column], lw=4, marker='o', ms=10) # ms = marker size
for column in data_list:
plt.plot(x, data[column], lw=4, marker='o', ms=10) # ms = marker size
plt.xticks(x, data["month_number"], fontsize=15) # sets x value step
plt.yticks(fontsize=15)
plt.xticks(x, data["month_number"], fontsize=15) # sets x value step
plt.yticks(fontsize=15)
set_labels("Sales data", "Month number", "Sales units in number")
set_labels("Sales data", "Month number", "Sales units in number")
new_data_list = list(map(lambda x: x.capitalize() + " Sales Data", data_list)) # capitalizes each word in list
plt.legend(new_data_list, loc='upper left', fontsize=15)
plt.show()
# capitalizes each word in list
new_data_list = list(
map(lambda x: x.capitalize() + " Sales Data", data_list))
plt.legend(new_data_list, loc='upper left', fontsize=15)
plt.show()
def task_3():
plt.figure(figsize=(10, 6)) # (x, y)
x = range(len(data["month_number"])) # gets range of months
plt.figure(figsize=(10, 6)) # (x, y)
x = range(len(data["month_number"])) # gets range of months
plt.scatter(x, data["toothpaste"], s=75) # sets up the plot
plt.grid(ls='dashed', lw=1.5) # sets grid line type and width
plt.xticks(x, data["month_number"], fontsize=15) # sets x value step
plt.yticks(fontsize=15)
plt.scatter(x, data["toothpaste"], s=75) # sets up the plot
plt.grid(ls='dashed', lw=1.5) # sets grid line type and width
plt.xticks(x, data["month_number"], fontsize=15) # sets x value step
plt.yticks(fontsize=15)
set_labels("Toothpaste Sales data", "Month number", "Number of units Sold")
plt.legend(["Toothpaste Sales data"], loc='upper left', fontsize=15)
plt.show()
set_labels("Toothpaste Sales data", "Month number", "Number of units Sold")
plt.legend(["Toothpaste Sales data"], loc='upper left', fontsize=15)
plt.show()
def task_4():
items = ["facecream", "facewash"]
items = ["facecream", "facewash"]
data.plot(x="month_number", y=["facecream", "facewash"], kind='bar', figsize=(10, 6), fontsize=15)
data.plot(x="month_number", y=[
"facecream", "facewash"], kind='bar', figsize=(10, 6), fontsize=15)
plt.xticks(rotation=0) # rotates x lables to 0
plt.grid(ls='dashed', lw=1.5) # sets grid line type and width
plt.xticks(rotation=0) # rotates x lables to 0
plt.grid(ls='dashed', lw=1.5) # sets grid line type and width
set_labels("Facewash and Facecream Sales data", "Month number", "Sales units in number")
new_items_list = list(map(lambda x: x.capitalize() + " Sales Data", items))
plt.legend(new_items_list, loc='upper left', fontsize=15)
plt.show()
set_labels("Facewash and Facecream Sales data",
"Month number", "Sales units in number")
new_items_list = list(map(lambda x: x.capitalize() + " Sales Data", items))
plt.legend(new_items_list, loc='upper left', fontsize=15)
plt.show()
def set_labels(title: str, xlabel: str, ylabel: str):
plt.title(title, fontsize=15)
plt.xlabel(xlabel, fontsize=15)
plt.ylabel(ylabel, fontsize=15)
plt.title(title, fontsize=15)
plt.xlabel(xlabel, fontsize=15)
plt.ylabel(ylabel, fontsize=15)
def main():
task = input("""Ivēlieties uzdevumu:
task = input("""Ivēlieties uzdevumu:
1 - pirmais uzdevums
2 - otrais uzdevums
3 - trešais uzdevums
4 - ceturtais uzdevums
""")
if task == "1":
task_1()
elif task == "2":
task_2()
elif task == "3":
task_3()
elif task == "4":
task_4()
else:
print("Tika ievadīts nepareiz cipars")
if task == "1":
task_1()
elif task == "2":
task_2()
elif task == "3":
task_3()
elif task == "4":
task_4()
else:
print("Tika ievadīts nepareiz cipars")
if __name__ == '__main__':
main()
main()

View File

@ -8,37 +8,37 @@ url = "https://www.ikea.lv/"
all_page = requests.get(url)
if all_page.status_code == 200:
page = BeautifulSoup(all_page.content, 'html.parser')
found = page.find_all(class_="itemBlock")
page = BeautifulSoup(all_page.content, 'html.parser')
found = page.find_all(class_="itemBlock")
info = []
item_array = []
for item in found:
item = item.findChild("div").findChild(class_="card-body")
info = []
item_array = []
for item in found:
item = item.findChild("div").findChild(class_="card-body")
item_name = item.findChild(class_="itemName")
item_name = item_name.findChild("div").findChild("h6")
item_name = item.findChild(class_="itemName")
item_name = item_name.findChild("div").findChild("h6")
item_array.append(item_name.string)
item_array.append(item_name.string)
price = item.findChild(class_="itemPrice-wrapper")
price = price.findChild("p").findChild("span")
price = item.findChild(class_="itemPrice-wrapper")
price = price.findChild("p").findChild("span")
try:
item_array.append(price.attrs["data-price"])
except:
item_array.append(price.attrs["data-pricefamily"])
try:
item_array.append(price.attrs["data-price"])
except:
item_array.append(price.attrs["data-pricefamily"])
all_facts = []
for facts in all_facts:
if len(facts) == 1:
all_facts.append(facts.string)
else:
atrasts = facts.findChildren("span")
for i in atrasts:
all_facts.append(i.string)
all_facts = []
for facts in all_facts:
if len(facts) == 1:
all_facts.append(facts.string)
else:
atrasts = facts.findChildren("span")
for i in atrasts:
all_facts.append(i.string)
item_array.append(all_facts)
info.append(item_array)
for ieraksts in info:
print(ieraksts)
item_array.append(all_facts)
info.append(item_array)
for ieraksts in info:
print(ieraksts)

View File

@ -7,21 +7,22 @@ all_page = requests.get(url)
# print(all_page)
if all_page.status_code == 200:
print(":)")
page = BeautifulSoup(all_page.content, 'html.parser')
found = page.find(id="Etymology")
# print(found)
# print(found.constents)
# print(found.string)
found = page.find_all(class_="mw-headline")
# print(found)
found = page.find_all("li", class_="interlanguage-link")
# print(found)
found = page.find_all("a", class_="interlanguage-link-target")
# print(found)
for i in found:
# print(i.prettify())
if i.attrs["lang"] == "ru":
print(f"{i.attrs['lang']} \t {i.attrs['title']} \n {i.attrs['href']}")
print(":)")
page = BeautifulSoup(all_page.content, 'html.parser')
found = page.find(id="Etymology")
# print(found)
# print(found.constents)
# print(found.string)
found = page.find_all(class_="mw-headline")
# print(found)
found = page.find_all("li", class_="interlanguage-link")
# print(found)
found = page.find_all("a", class_="interlanguage-link-target")
# print(found)
for i in found:
# print(i.prettify())
if i.attrs["lang"] == "ru":
print(
f"{i.attrs['lang']} \t {i.attrs['title']} \n {i.attrs['href']}")
else:
print(":(")
print(":(")

View File

@ -7,38 +7,42 @@ CHAPTERS = 61
# creates file with chapters and row numbers
def read_array(document):
with open(document, "r", encoding='utf-8') as book:
lines = [line.strip('\n') for line in book] # removes 'enter' characters
with open('array_output.txt', 'w') as output:
for i in range(1, CHAPTERS + 1):
line = lines.index(f"Chapter {i}") + 1 # finds all chapter indexes/lines
output.write(f"Line {line} - Chapter {i}\n") # writes line in file
with open(document, "r", encoding='utf-8') as book:
lines = [line.strip('\n')
for line in book] # removes 'enter' characters
with open('array_output.txt', 'w') as output:
for i in range(1, CHAPTERS + 1):
# finds all chapter indexes/lines
line = lines.index(f"Chapter {i}") + 1
output.write(f"Line {line} - Chapter {i}\n") # writes line in file
# creates file with chapter positions
def read_string(document):
with open(document, "r", encoding='utf-8') as book:
lines = book.read()
with open('str_output.txt', 'w') as output:
for i in range(1, CHAPTERS + 1):
_, position = re.finditer(rf"\bChapter {i}\b", lines) # finds all chapter positions
output.write(f"Position {position.start()} - Chapter {i}\n") # writes position in file
with open(document, "r", encoding='utf-8') as book:
lines = book.read()
with open('str_output.txt', 'w') as output:
for i in range(1, CHAPTERS + 1):
# finds all chapter positions
_, position = re.finditer(rf"\bChapter {i}\b", lines)
# writes position in file
output.write(f"Position {position.start()} - Chapter {i}\n")
def read_book(document):
read_array(document)
read_string(document)
read_array(document)
read_string(document)
def main():
try:
read_book("book.txt")
except:
try:
read_book("1342-0.txt")
except:
read_book(input("Ievadiet faila nosaukumu: "))
try:
read_book("book.txt")
except:
try:
read_book("1342-0.txt")
except:
read_book(input("Ievadiet faila nosaukumu: "))
if __name__ == '__main__':
main()
main()

View File

@ -5,182 +5,189 @@ from random import randrange
class Cube:
def __init__(self, position, color=DARK_PURPLE) -> None:
self.pos = position
self.direction = (1, 0)
self.color = color
def __init__(self, position, color=DARK_PURPLE) -> None:
self.pos = position
self.direction = (1, 0)
self.color = color
def move(self, direction: tuple) -> None:
self.direction = direction
self.pos = (self.pos[0] + self.direction[0], self.pos[1] + self.direction[1])
def move(self, direction: tuple) -> None:
self.direction = direction
self.pos = (self.pos[0] + self.direction[0],
self.pos[1] + self.direction[1])
def draw(self, eyes=False) -> None:
distance = WIDTH // ROWS
i, j = self.pos
def draw(self, eyes=False) -> None:
distance = WIDTH // ROWS
i, j = self.pos
pygame.draw.rect(WINDOW, self.color, (i * distance + 1, j * distance + 1, distance - 2, distance - 2))
if eyes:
center = distance // 2
radius = 3
circle_middle = (i * distance + center - radius, j * distance + 8)
circle_middle_2 = (i * distance + distance - radius * 2, j * distance + 8)
pygame.draw.circle(WINDOW, BLACK, circle_middle, radius)
pygame.draw.circle(WINDOW, BLACK, circle_middle_2, radius)
pygame.draw.rect(WINDOW, self.color, (i * distance + 1,
j * distance + 1, distance - 2, distance - 2))
if eyes:
center = distance // 2
radius = 3
circle_middle = (i * distance + center - radius, j * distance + 8)
circle_middle_2 = (i * distance + distance -
radius * 2, j * distance + 8)
pygame.draw.circle(WINDOW, BLACK, circle_middle, radius)
pygame.draw.circle(WINDOW, BLACK, circle_middle_2, radius)
class Snake:
def __init__(self, position: tuple, color: tuple, name: str, player_number: int = 1, multiplayer: bool = False) -> None:
self.color = color
self.head = Cube(position, self.color)
self.body = []
self.body.append(self.head)
self.turns = {}
self.direction = (1, 0)
self.number = player_number
self.name = name
self.multiplayer = multiplayer
def __init__(self, position: tuple, color: tuple, name: str, player_number: int = 1, multiplayer: bool = False) -> None:
self.color = color
self.head = Cube(position, self.color)
self.body = []
self.body.append(self.head)
self.turns = {}
self.direction = (1, 0)
self.number = player_number
self.name = name
self.multiplayer = multiplayer
def move(self) -> None:
keys = pygame.key.get_pressed()
if self.multiplayer:
num_1, num_2 = 1, 2
else:
num_1, num_2 = 1, 1
def move(self) -> None:
keys = pygame.key.get_pressed()
if self.multiplayer:
num_1, num_2 = 1, 2
else:
num_1, num_2 = 1, 1
if self.number == num_1:
if keys[pygame.K_LEFT] and self.direction != (1, 0): # turn left
self.direction = -1, 0
self.turns[self.head.pos[:]] = self.direction
if self.number == num_1:
if keys[pygame.K_LEFT] and self.direction != (1, 0): # turn left
self.direction = -1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_RIGHT] and self.direction != (-1, 0): # turn right
self.direction = 1, 0
self.turns[self.head.pos[:]] = self.direction
# turn right
if keys[pygame.K_RIGHT] and self.direction != (-1, 0):
self.direction = 1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_UP] and self.direction != (0, 1): # turn up
self.direction = 0, -1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_UP] and self.direction != (0, 1): # turn up
self.direction = 0, -1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_DOWN] and self.direction != (0, -1): # turn down
self.direction = 0, 1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_DOWN] and self.direction != (0, -1): # turn down
self.direction = 0, 1
self.turns[self.head.pos[:]] = self.direction
if self.number == num_2:
if keys[pygame.K_a] and self.direction != (1, 0): # turn left
self.direction = -1, 0
self.turns[self.head.pos[:]] = self.direction
if self.number == num_2:
if keys[pygame.K_a] and self.direction != (1, 0): # turn left
self.direction = -1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_d] and self.direction != (-1, 0): # turn right
self.direction = 1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_d] and self.direction != (-1, 0): # turn right
self.direction = 1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_w] and self.direction != (0, 1): # turn up
self.direction = 0, -1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_w] and self.direction != (0, 1): # turn up
self.direction = 0, -1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_s] and self.direction != (0, -1): # turn down
self.direction = 0, 1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_s] and self.direction != (0, -1): # turn down
self.direction = 0, 1
self.turns[self.head.pos[:]] = self.direction
for index, head in enumerate(self.body):
head_pos = head.pos[:]
if head_pos in self.turns:
turn = self.turns[head_pos]
head.move((turn[0], turn[1]))
if index == len(self.body) - 1:
self.turns.pop(head_pos)
else:
from globals import walls
from snake import end_screen
if walls: # end game if goes into the wall
head.move(head.direction)
if head.direction[0] == -1 and head.pos[0] < 0: # left to right
end_screen()
for index, head in enumerate(self.body):
head_pos = head.pos[:]
if head_pos in self.turns:
turn = self.turns[head_pos]
head.move((turn[0], turn[1]))
if index == len(self.body) - 1:
self.turns.pop(head_pos)
else:
from globals import walls
from snake import end_screen
if walls: # end game if goes into the wall
head.move(head.direction)
if head.direction[0] == -1 and head.pos[0] < 0: # left to right
end_screen()
if head.direction[0] == 1 and head.pos[0] >= ROWS: # right to left
end_screen()
if head.direction[0] == 1 and head.pos[0] >= ROWS: # right to left
end_screen()
if head.direction[1] == 1 and head.pos[1] >= COLUMNS: # bottom to top
end_screen()
if head.direction[1] == 1 and head.pos[1] >= COLUMNS: # bottom to top
end_screen()
if head.direction[1] == -1 and head.pos[1] < 0: # top to bottom
end_screen()
if head.direction[1] == -1 and head.pos[1] < 0: # top to bottom
end_screen()
else: # move player to other screen size
if head.direction[0] == -1 and head.pos[0] <= 0: # left to right
head.pos = (ROWS - 1, head.pos[1])
else: # move player to other screen size
if head.direction[0] == -1 and head.pos[0] <= 0: # left to right
head.pos = (ROWS - 1, head.pos[1])
elif head.direction[0] == 1 and head.pos[0] >= ROWS - 1: # right to left
head.pos = (0, head.pos[1])
elif head.direction[0] == 1 and head.pos[0] >= ROWS - 1: # right to left
head.pos = (0, head.pos[1])
elif head.direction[1] == 1 and head.pos[1] >= COLUMNS - 1: # bottom to top
head.pos = (head.pos[0], 0)
# bottom to top
elif head.direction[1] == 1 and head.pos[1] >= COLUMNS - 1:
head.pos = (head.pos[0], 0)
elif head.direction[1] == -1 and head.pos[1] <= 0: # top to bottom
head.pos = (head.pos[0], COLUMNS - 1)
elif head.direction[1] == -1 and head.pos[1] <= 0: # top to bottom
head.pos = (head.pos[0], COLUMNS - 1)
else:
head.move(head.direction)
else:
head.move(head.direction)
def add_cube(self) -> None:
tail = self.body[-1]
if tail.direction == (1, 0):
self.body.append(Cube((tail.pos[0] - 1, tail.pos[1]), self.color))
elif tail.direction == (-1, 0):
self.body.append(Cube((tail.pos[0] + 1, tail.pos[1]), self.color))
elif tail.direction == (0, 1):
self.body.append(Cube((tail.pos[0], tail.pos[1] - 1), self.color))
elif tail.direction == (0, -1):
self.body.append(Cube((tail.pos[0], tail.pos[1] + 1), self.color))
def add_cube(self) -> None:
tail = self.body[-1]
if tail.direction == (1, 0):
self.body.append(Cube((tail.pos[0] - 1, tail.pos[1]), self.color))
elif tail.direction == (-1, 0):
self.body.append(Cube((tail.pos[0] + 1, tail.pos[1]), self.color))
elif tail.direction == (0, 1):
self.body.append(Cube((tail.pos[0], tail.pos[1] - 1), self.color))
elif tail.direction == (0, -1):
self.body.append(Cube((tail.pos[0], tail.pos[1] + 1), self.color))
self.body[-1].direction = tail.direction
self.body[-1].direction = tail.direction
def remove_cube(self) -> None:
self.body.pop(-1)
def remove_cube(self) -> None:
self.body.pop(-1)
def draw(self) -> None:
for index, head in enumerate(self.body):
if index == 0:
head.draw(eyes=True)
else:
head.draw()
def draw(self) -> None:
for index, head in enumerate(self.body):
if index == 0:
head.draw(eyes=True)
else:
head.draw()
class Snack:
def __init__(self, texture) -> None:
self.texture = texture
self.randomize()
def __init__(self, texture) -> None:
self.texture = texture
self.randomize()
def draw_snack(self) -> None:
snack_rect = pygame.Rect(self.pos[0] * CELL_SIZE, self.pos[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE)
WINDOW.blit(self.texture, snack_rect)
def draw_snack(self) -> None:
snack_rect = pygame.Rect(
self.pos[0] * CELL_SIZE, self.pos[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE)
WINDOW.blit(self.texture, snack_rect)
def randomize(self) -> None:
self.pos = (randrange(ROWS), randrange(COLUMNS))
def randomize(self) -> None:
self.pos = (randrange(ROWS), randrange(COLUMNS))
class Button():
def __init__(self, position, text, font_size, base_color, hover_color) -> None:
self.pos = position
self.font = set_font(font_size)
self.base_color = base_color
self.hover_color = hover_color
self.text = text
self.text_rect = self.font.render(self.text, 1, self.base_color).get_rect(center=(self.pos))
def __init__(self, position, text, font_size, base_color, hover_color) -> None:
self.pos = position
self.font = set_font(font_size)
self.base_color = base_color
self.hover_color = hover_color
self.text = text
self.text_rect = self.font.render(
self.text, 1, self.base_color).get_rect(center=(self.pos))
def update(self) -> None:
WINDOW.blit(self.text, self.text_rect)
def update(self) -> None:
WINDOW.blit(self.text, self.text_rect)
def check_input(self, mouse_pos) -> bool:
if mouse_pos[0] in range(self.text_rect.left, self.text_rect.right) and mouse_pos[1] in range(self.text_rect.top, self.text_rect.bottom):
return True
return False
def check_input(self, mouse_pos) -> bool:
if mouse_pos[0] in range(self.text_rect.left, self.text_rect.right) and mouse_pos[1] in range(self.text_rect.top, self.text_rect.bottom):
return True
return False
def change_color(self, mouse_pos) -> None:
if mouse_pos[0] in range(self.text_rect.left,
self.text_rect.right) and mouse_pos[1] in range(self.text_rect.top, self.text_rect.bottom): # on hover
self.text = self.font.render(self.text, 1, self.hover_color)
else:
self.text = self.font.render(self.text, 1, self.base_color)
def change_color(self, mouse_pos) -> None:
if mouse_pos[0] in range(self.text_rect.left,
self.text_rect.right) and mouse_pos[1] in range(self.text_rect.top, self.text_rect.bottom): # on hover
self.text = self.font.render(self.text, 1, self.hover_color)
else:
self.text = self.font.render(self.text, 1, self.base_color)

View File

@ -11,178 +11,225 @@ color_index = [0, 1]
def main_menu() -> None:
pygame.display.set_caption("Snake - Menu")
while True:
WINDOW.fill(BLACK)
mouse_pos = pygame.mouse.get_pos()
menu_text = set_font(100).render("SNAKE GAME", 1, WHITE)
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(menu_text, menu_rect)
pygame.display.set_caption("Snake - Menu")
while True:
WINDOW.fill(BLACK)
mouse_pos = pygame.mouse.get_pos()
menu_text = set_font(100).render("SNAKE GAME", 1, WHITE)
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(menu_text, menu_rect)
play_button = Button((MID_WIDTH, MID_HEIGHT - 50), "PLAY", 75, GRAY, WHITE)
options_button = Button((MID_WIDTH, MID_HEIGHT + 50), "OPTIONS", 75, GRAY, WHITE)
score_button = Button((MID_WIDTH, MID_HEIGHT + 150), "SCORE", 75, GRAY, WHITE)
quit_button = Button((MID_WIDTH, MID_HEIGHT + 250), "QUIT", 75, GRAY, WHITE)
buttons = [play_button, options_button, score_button, quit_button]
play_button = Button((MID_WIDTH, MID_HEIGHT - 50),
"PLAY", 75, GRAY, WHITE)
options_button = Button(
(MID_WIDTH, MID_HEIGHT + 50), "OPTIONS", 75, GRAY, WHITE)
score_button = Button((MID_WIDTH, MID_HEIGHT + 150),
"SCORE", 75, GRAY, WHITE)
quit_button = Button((MID_WIDTH, MID_HEIGHT + 250),
"QUIT", 75, GRAY, WHITE)
buttons = [play_button, options_button, score_button, quit_button]
on_hover(buttons)
on_hover(buttons)
for event in pygame.event.get():
if event.type == pygame.QUIT: quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if play_button.check_input(mouse_pos): user_input(0)
if options_button.check_input(mouse_pos): options()
if score_button.check_input(mouse_pos): scoreboard()
if quit_button.check_input(mouse_pos): quit()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if play_button.check_input(mouse_pos):
user_input(0)
if options_button.check_input(mouse_pos):
options()
if score_button.check_input(mouse_pos):
scoreboard()
if quit_button.check_input(mouse_pos):
quit()
pygame.display.update()
pygame.display.update()
def user_input(player: int) -> None:
from snake import main
global user_name
global color_index
pygame.display.set_caption("Snake")
select_active = True
outline_color = WHITE
name_rect_w = 140
while True:
from globals import multiplayer
WINDOW.fill(BLACK)
mouse_pos = pygame.mouse.get_pos()
menu_text = set_font(100).render(f"PLAYER {player + 1}", 1, WHITE)
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(menu_text, menu_rect)
from snake import main
global user_name
global color_index
pygame.display.set_caption("Snake")
select_active = True
outline_color = WHITE
name_rect_w = 140
while True:
from globals import multiplayer
WINDOW.fill(BLACK)
mouse_pos = pygame.mouse.get_pos()
menu_text = set_font(100).render(f"PLAYER {player + 1}", 1, WHITE)
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(menu_text, menu_rect)
back_button = Button((130, WINDOW_HEIGHT - 50), "BACK", 75, GRAY, WHITE)
if multiplayer and player == 0:
next_button = Button((WIDTH - 130, WINDOW_HEIGHT - 50), "NEXT", 75, GRAY, WHITE)
buttons = [back_button, next_button]
else:
play_button = Button((WIDTH - 130, WINDOW_HEIGHT - 50), "PLAY", 75, GRAY, WHITE)
buttons = [back_button, play_button]
back_button = Button((130, WINDOW_HEIGHT - 50),
"BACK", 75, GRAY, WHITE)
if multiplayer and player == 0:
next_button = Button(
(WIDTH - 130, WINDOW_HEIGHT - 50), "NEXT", 75, GRAY, WHITE)
buttons = [back_button, next_button]
else:
play_button = Button(
(WIDTH - 130, WINDOW_HEIGHT - 50), "PLAY", 75, GRAY, WHITE)
buttons = [back_button, play_button]
on_hover(buttons)
on_hover(buttons)
name_rect = pygame.Rect(MID_WIDTH - name_rect_w / 2, 200, name_rect_w, 32)
pygame.draw.rect(WINDOW, outline_color, name_rect, 2)
user_text = set_font(20).render(user_name[player], 1, WHITE)
WINDOW.blit(user_text, (name_rect.x + 5, name_rect.y + 5))
name_rect_w = max(140, user_text.get_width() + 10)
name_rect = pygame.Rect(
MID_WIDTH - name_rect_w / 2, 200, name_rect_w, 32)
pygame.draw.rect(WINDOW, outline_color, name_rect, 2)
user_text = set_font(20).render(user_name[player], 1, WHITE)
WINDOW.blit(user_text, (name_rect.x + 5, name_rect.y + 5))
name_rect_w = max(140, user_text.get_width() + 10)
color = COLORS[color_index[player]]
color_rect = pygame.Rect(MID_WIDTH - 50, 350, 100, 100)
pygame.draw.rect(WINDOW, color, color_rect)
color = COLORS[color_index[player]]
color_rect = pygame.Rect(MID_WIDTH - 50, 350, 100, 100)
pygame.draw.rect(WINDOW, color, color_rect)
if select_active: outline_color = WHITE
else: outline_color = DARK_GRAY
if select_active:
outline_color = WHITE
else:
outline_color = DARK_GRAY
for event in pygame.event.get():
if event.type == pygame.QUIT: quit()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if name_rect.collidepoint(event.pos): select_active = True
else: select_active = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if name_rect.collidepoint(event.pos):
select_active = True
else:
select_active = False
if back_button.check_input(mouse_pos): main_menu()
if multiplayer and player == 0:
if next_button.check_input(mouse_pos): user_input(1)
else:
if play_button.check_input(mouse_pos): main()
if color_rect.collidepoint(event.pos):
color_index[player] += 1
if color_index[player] == len(COLORS) - 1:
color_index[player] = 0
if back_button.check_input(mouse_pos):
main_menu()
if multiplayer and player == 0:
if next_button.check_input(mouse_pos):
user_input(1)
else:
if play_button.check_input(mouse_pos):
main()
if color_rect.collidepoint(event.pos):
color_index[player] += 1
if color_index[player] == len(COLORS) - 1:
color_index[player] = 0
if event.button == 3: # clear user name on mouse right click
if name_rect.collidepoint(event.pos): user_name[player] = ""
if event.button == 3: # clear user name on mouse right click
if name_rect.collidepoint(event.pos):
user_name[player] = ""
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: main_menu()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
main_menu()
if select_active:
if event.key == pygame.K_BACKSPACE: user_name[player] = user_name[player][:-1]
elif event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER: continue
else: user_name[player] += event.unicode
if select_active:
if event.key == pygame.K_BACKSPACE:
user_name[player] = user_name[player][:-1]
elif event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
continue
else:
user_name[player] += event.unicode
if event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
if multiplayer and player == 0: user_input(1)
else: main()
if event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
if multiplayer and player == 0:
user_input(1)
else:
main()
pygame.display.update()
pygame.display.update()
def options() -> None:
pygame.display.set_caption("Snake - Options")
while True:
from globals import fps, multiplayer, walls
mouse_pos = pygame.mouse.get_pos()
pygame.display.set_caption("Snake - Options")
while True:
from globals import fps, multiplayer, walls
mouse_pos = pygame.mouse.get_pos()
WINDOW.fill(BLACK)
options_text = set_font(100).render("OPTIONS", 1, WHITE)
options_rect = options_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(options_text, options_rect)
WINDOW.fill(BLACK)
options_text = set_font(100).render("OPTIONS", 1, WHITE)
options_rect = options_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(options_text, options_rect)
# change state names
# multiplayer
if multiplayer: multiplayer_state = "on"
else: multiplayer_state = "off"
# walls
if walls: walls_state = "on"
else: walls_state = "off"
# change state names
# multiplayer
if multiplayer:
multiplayer_state = "on"
else:
multiplayer_state = "off"
# walls
if walls:
walls_state = "on"
else:
walls_state = "off"
speed_state = {5: "Slow", 10: "Normal", 15: "Fast"}
speed_state = {5: "Slow", 10: "Normal", 15: "Fast"}
speed_button = Button((MID_WIDTH, MID_HEIGHT - 100), f"SPEED - {speed_state[fps]}", 75, GRAY, WHITE)
multiplayer_button = Button((MID_WIDTH, MID_HEIGHT), f"MULTIPLAYER - {multiplayer_state}", 75, GRAY, WHITE)
walls_button = Button((MID_WIDTH, MID_HEIGHT + 100), f"WALLS - {walls_state}", 75, GRAY, WHITE)
back_button = Button((MID_WIDTH, MID_HEIGHT + 200), "BACK", 75, GRAY, WHITE)
buttons = [speed_button, multiplayer_button, walls_button, back_button]
speed_button = Button((MID_WIDTH, MID_HEIGHT - 100),
f"SPEED - {speed_state[fps]}", 75, GRAY, WHITE)
multiplayer_button = Button(
(MID_WIDTH, MID_HEIGHT), f"MULTIPLAYER - {multiplayer_state}", 75, GRAY, WHITE)
walls_button = Button((MID_WIDTH, MID_HEIGHT + 100),
f"WALLS - {walls_state}", 75, GRAY, WHITE)
back_button = Button((MID_WIDTH, MID_HEIGHT + 200),
"BACK", 75, GRAY, WHITE)
buttons = [speed_button, multiplayer_button, walls_button, back_button]
on_hover(buttons)
on_hover(buttons)
for event in pygame.event.get():
if event.type == pygame.QUIT: quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: main_menu()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if speed_button.check_input(mouse_pos): change_speed()
if multiplayer_button.check_input(mouse_pos): switch_multiplayer()
if walls_button.check_input(mouse_pos): switch_walls()
if back_button.check_input(mouse_pos): main_menu()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
main_menu()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if speed_button.check_input(mouse_pos):
change_speed()
if multiplayer_button.check_input(mouse_pos):
switch_multiplayer()
if walls_button.check_input(mouse_pos):
switch_walls()
if back_button.check_input(mouse_pos):
main_menu()
pygame.display.update()
pygame.display.update()
def scoreboard() -> None:
while True:
mouse_pos = pygame.mouse.get_pos()
WINDOW.fill(BLACK)
top_text = set_font(100).render("TOP 10", 1, WHITE)
top_rect = top_text.get_rect(center=(MID_WIDTH, 55))
WINDOW.blit(top_text, top_rect)
back_button = Button((MID_WIDTH, MID_HEIGHT + 250), "BACK", 75, GRAY, WHITE)
on_hover([back_button])
while True:
mouse_pos = pygame.mouse.get_pos()
WINDOW.fill(BLACK)
top_text = set_font(100).render("TOP 10", 1, WHITE)
top_rect = top_text.get_rect(center=(MID_WIDTH, 55))
WINDOW.blit(top_text, top_rect)
back_button = Button((MID_WIDTH, MID_HEIGHT + 250),
"BACK", 75, GRAY, WHITE)
on_hover([back_button])
for event in pygame.event.get():
if event.type == pygame.QUIT: quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: main_menu()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if back_button.check_input(mouse_pos): main_menu()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
main_menu()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if back_button.check_input(mouse_pos):
main_menu()
csv_file = read_score(BASE_PATH)
for i, line in enumerate(sort(csv_file, reverse=True)[:11]):
for j, text in enumerate(line):
score_text = set_font(30).render(text, 1, WHITE)
score_rect = score_text.get_rect(center=(MID_WIDTH - 150 + 300 * j, 150 + 30 * i))
WINDOW.blit(score_text, score_rect)
csv_file = read_score(BASE_PATH)
for i, line in enumerate(sort(csv_file, reverse=True)[:11]):
for j, text in enumerate(line):
score_text = set_font(30).render(text, 1, WHITE)
score_rect = score_text.get_rect(
center=(MID_WIDTH - 150 + 300 * j, 150 + 30 * i))
WINDOW.blit(score_text, score_rect)
pygame.display.update()
pygame.display.update()
def on_hover(buttons: list) -> None:
for button in buttons:
button.change_color(pygame.mouse.get_pos())
button.update()
for button in buttons:
button.change_color(pygame.mouse.get_pos())
button.update()

View File

@ -5,33 +5,34 @@ fields = ["Name", "Score"]
def write_score(name: str, score: int, base_path: str) -> None:
create_header = False
path = join(base_path, "score.csv")
if not exists(path):
create_header = True
with open(path, 'a', encoding='UTF-8', newline='') as file:
write = csv.writer(file)
if create_header:
write.writerow(fields)
write.writerows([[name, score]])
create_header = False
path = join(base_path, "score.csv")
if not exists(path):
create_header = True
with open(path, 'a', encoding='UTF-8', newline='') as file:
write = csv.writer(file)
if create_header:
write.writerow(fields)
write.writerows([[name, score]])
def read_score(path: str):
lines = []
path = join(path, "score.csv")
try:
with open(path, 'r', encoding='UTF-8') as file:
for line in csv.reader(file):
lines.append(line)
return lines
except FileNotFoundError:
return [fields]
lines = []
path = join(path, "score.csv")
try:
with open(path, 'r', encoding='UTF-8') as file:
for line in csv.reader(file):
lines.append(line)
return lines
except FileNotFoundError:
return [fields]
def sort(data, reverse: bool):
if reverse == None: reverse = False
header = data[0]
data.remove(header) # remove header
data = sorted(data, key=lambda x: int(x[1]), reverse=reverse) # sort data
data.insert(0, header) # add header
return data
if reverse == None:
reverse = False
header = data[0]
data.remove(header) # remove header
data = sorted(data, key=lambda x: int(x[1]), reverse=reverse) # sort data
data.insert(0, header) # add header
return data

View File

@ -1,5 +1,5 @@
import pygame
from os.path import join, abspath, dirname
import pygame
CELL_SIZE = 30
ROWS, COLUMNS = 30, 20
@ -11,9 +11,12 @@ pygame.font.init()
BASE_PATH = abspath(dirname(__file__))
FONT = join(BASE_PATH, "fonts", "roboto.ttf")
SPRITE_PATH = join(BASE_PATH, "assets", "sprites")
APPLE_TEXTURE = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "golden_apple.png")), (CELL_SIZE, CELL_SIZE))
POISON_TEXTURE = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "poison.png")), (CELL_SIZE, CELL_SIZE))
COBBLESTONE_TEXTURE = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "cobblestone.jpeg")), (CELL_SIZE, CELL_SIZE))
APPLE_TEXTURE = pygame.transform.scale(pygame.image.load(
join(SPRITE_PATH, "golden_apple.png")), (CELL_SIZE, CELL_SIZE))
POISON_TEXTURE = pygame.transform.scale(pygame.image.load(
join(SPRITE_PATH, "poison.png")), (CELL_SIZE, CELL_SIZE))
COBBLESTONE_TEXTURE = pygame.transform.scale(pygame.image.load(
join(SPRITE_PATH, "cobblestone.jpeg")), (CELL_SIZE, CELL_SIZE))
BLACK = (0, 0, 0)
DARK_BLUE = (0, 0, 170)
@ -32,9 +35,12 @@ LIGHT_PURPLE = (255, 85, 255)
YELLOW = (255, 255, 85)
WHITE = (242, 242, 242)
COLORS = [DARK_BLUE, DARK_GREEN, DARK_AQUA, DARK_RED, DARK_PURPLE, GOLD, BLUE, GREEN, AQUA, RED, LIGHT_PURPLE, YELLOW]
COLORS = [DARK_BLUE, DARK_GREEN, DARK_AQUA, DARK_RED, DARK_PURPLE,
GOLD, BLUE, GREEN, AQUA, RED, LIGHT_PURPLE, YELLOW]
def set_font(size): return pygame.font.Font(FONT, size) # sets font size
set_font = lambda size: pygame.font.Font(FONT, size) # sets font size
fps = 10 # speed
multiplayer = False
@ -42,17 +48,20 @@ walls = False
def change_speed() -> None:
global fps
if fps == 5: fps = 10
elif fps == 10: fps = 15
elif fps == 15: fps = 5
global fps
if fps == 5:
fps = 10
elif fps == 10:
fps = 15
elif fps == 15:
fps = 5
def switch_multiplayer() -> None:
global multiplayer
multiplayer = not multiplayer
global multiplayer
multiplayer = not multiplayer
def switch_walls() -> None:
global walls
walls = not walls
global walls
walls = not walls

159
pygame/snake/source/snake.py Executable file → Normal file
View File

@ -17,104 +17,109 @@ snakes = []
def draw_grid() -> None:
x, y = 0, 0
for _ in range(ROWS):
x += CELL_SIZE
pygame.draw.line(WINDOW, WHITE, (x, 0), (x, HEIGHT))
for _ in range(COLUMNS):
y += CELL_SIZE
pygame.draw.line(WINDOW, WHITE, (0, y), (WIDTH, y))
x, y = 0, 0
for _ in range(ROWS):
x += CELL_SIZE
pygame.draw.line(WINDOW, WHITE, (x, 0), (x, HEIGHT))
for _ in range(COLUMNS):
y += CELL_SIZE
pygame.draw.line(WINDOW, WHITE, (0, y), (WIDTH, y))
def draw_score(snakes) -> None:
for index, snake in enumerate(snakes):
score_label = set_font(40).render(f"Score {len(snake.body) - 1}", 1, snake.color)
WINDOW.blit(score_label, (10 + (index * (WIDTH - score_label.get_width() - 20)), (WINDOW_HEIGHT - score_label.get_height())))
for index, snake in enumerate(snakes):
score_label = set_font(40).render(
f"Score {len(snake.body) - 1}", 1, snake.color)
WINDOW.blit(score_label, (10 + (index * (WIDTH - score_label.get_width() - 20)),
(WINDOW_HEIGHT - score_label.get_height())))
def collision_check(snakes, snack) -> None:
for snake in snakes:
for block in snake.body:
if block.pos == snack.pos:
snack.randomize()
for snake in snakes:
for block in snake.body:
if block.pos == snack.pos:
snack.randomize()
def end_screen() -> None:
for snake in snakes:
if len(snake.body) > 1:
write_score(snake.name, len(snake.body) - 1, BASE_PATH)
main_menu()
for snake in snakes:
if len(snake.body) > 1:
write_score(snake.name, len(snake.body) - 1, BASE_PATH)
main_menu()
def main() -> None:
snakes.clear()
from globals import fps, multiplayer, walls
pygame.display.set_caption("Snake")
snakes.clear()
from globals import fps, multiplayer, walls
pygame.display.set_caption("Snake")
clock = pygame.time.Clock()
from assets.scripts.menu import user_name, color_index
snake_one = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)), COLORS[color_index[0]], user_name[0], 1, multiplayer)
snakes.append(snake_one)
clock = pygame.time.Clock()
from assets.scripts.menu import user_name, color_index
snake_one = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)),
COLORS[color_index[0]], user_name[0], 1, multiplayer)
snakes.append(snake_one)
if multiplayer:
snake_two = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)), COLORS[color_index[1]], user_name[1], 2, multiplayer)
snakes.append(snake_two)
apple = Snack(APPLE_TEXTURE)
collision_check(snakes, apple)
poison = Snack(POISON_TEXTURE)
collision_check(snakes, poison)
if multiplayer:
snake_two = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)),
COLORS[color_index[1]], user_name[1], 2, multiplayer)
snakes.append(snake_two)
apple = Snack(APPLE_TEXTURE)
collision_check(snakes, apple)
poison = Snack(POISON_TEXTURE)
collision_check(snakes, poison)
def redraw_window() -> None:
WINDOW.fill(BLACK)
draw_grid()
draw_score(snakes)
for snake in snakes:
snake.draw()
apple.draw_snack()
poison.draw_snack()
if walls:
for i in range(ROWS):
COBBLE_RECT = pygame.Rect(i * CELL_SIZE, HEIGHT, WIDTH, CELL_SIZE)
WINDOW.blit(COBBLESTONE_TEXTURE, COBBLE_RECT)
pygame.display.update()
def redraw_window() -> None:
WINDOW.fill(BLACK)
draw_grid()
draw_score(snakes)
for snake in snakes:
snake.draw()
apple.draw_snack()
poison.draw_snack()
if walls:
for i in range(ROWS):
COBBLE_RECT = pygame.Rect(
i * CELL_SIZE, HEIGHT, WIDTH, CELL_SIZE)
WINDOW.blit(COBBLESTONE_TEXTURE, COBBLE_RECT)
pygame.display.update()
while True:
clock.tick(fps)
pygame.time.delay(0)
while True:
clock.tick(fps)
pygame.time.delay(0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
end_screen()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
end_screen()
for snake in snakes:
snake.move()
if snake.body[0].pos == apple.pos:
snake.add_cube()
apple = Snack(APPLE_TEXTURE)
collision_check(snakes, apple)
for snake in snakes:
snake.move()
if snake.body[0].pos == apple.pos:
snake.add_cube()
apple = Snack(APPLE_TEXTURE)
collision_check(snakes, apple)
if snake.body[0].pos == poison.pos:
if len(snake.body) > 1:
snake.remove_cube()
poison = Snack(POISON_TEXTURE)
collision_check(snakes, poison)
if snake.body[0].pos == poison.pos:
if len(snake.body) > 1:
snake.remove_cube()
poison = Snack(POISON_TEXTURE)
collision_check(snakes, poison)
for i in range(len(snake.body)):
if snake.body[i].pos in list(map(lambda z: z.pos, snake.body[i + 1:])):
end_screen()
if multiplayer:
for i in snakes[0].body:
if i.pos == snakes[1].head.pos:
end_screen()
for i in snakes[1].body:
if i.pos == snakes[0].head.pos:
end_screen()
for i in range(len(snake.body)):
if snake.body[i].pos in list(map(lambda z: z.pos, snake.body[i + 1:])):
end_screen()
if multiplayer:
for i in snakes[0].body:
if i.pos == snakes[1].head.pos:
end_screen()
for i in snakes[1].body:
if i.pos == snakes[0].head.pos:
end_screen()
redraw_window()
redraw_window()
if __name__ == '__main__':
main_menu()
main_menu()

View File

@ -20,17 +20,23 @@ FONT = join(BASE_PATH, "fonts", "space_invaders.ttf")
# load sprites
SPACESHIP = pygame.image.load(join(SPRITE_PATH, "playership.png")) # player
PLAYER_MISSILE = pygame.image.load(join(SPRITE_PATH, "missiles", "playermissile.png")) # player missile
PLAYER_MISSILE = pygame.image.load(
join(SPRITE_PATH, "missiles", "playermissile.png")) # player missile
# enemies
ENEMY_1 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_magenta.png")), (40, 35))
ENEMY_2 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_cyan.png")), (40, 35))
ENEMY_3 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_lime.png")), (40, 35))
ENEMY_MISSILE = pygame.image.load(join(SPRITE_PATH, "missiles", "enemymissile.png")) # enemy missile
ENEMY_1 = pygame.transform.scale(pygame.image.load(
join(ENEMY_PATH, "enemy_magenta.png")), (40, 35))
ENEMY_2 = pygame.transform.scale(pygame.image.load(
join(ENEMY_PATH, "enemy_cyan.png")), (40, 35))
ENEMY_3 = pygame.transform.scale(pygame.image.load(
join(ENEMY_PATH, "enemy_lime.png")), (40, 35))
ENEMY_MISSILE = pygame.image.load(
join(SPRITE_PATH, "missiles", "enemymissile.png")) # enemy missile
pygame.display.set_icon(ENEMY_3)
# background
BACKGROUND = pygame.transform.scale(pygame.image.load(join(BASE_PATH, "assets", "background.jpg")), (WIDTH, HEIGHT))
BACKGROUND = pygame.transform.scale(pygame.image.load(
join(BASE_PATH, "assets", "background.jpg")), (WIDTH, HEIGHT))
# colors (R, G, B)
BLUE = (16, 16, 69)
@ -40,259 +46,267 @@ RED = (188, 2, 5)
class Missile:
def __init__(self, x: int, y: int, img) -> None:
self.x = x
self.y = y
self.img = img
self.mask = pygame.mask.from_surface(self.img)
def __init__(self, x: int, y: int, img) -> None:
self.x = x
self.y = y
self.img = img
self.mask = pygame.mask.from_surface(self.img)
def draw(self, window) -> None:
window.blit(self.img, (self.x, self.y))
def draw(self, window) -> None:
window.blit(self.img, (self.x, self.y))
def move(self, vel: int) -> None:
self.y += vel
def move(self, vel: int) -> None:
self.y += vel
def off_screen(self, height: int) -> bool:
return not (self.y <= height and self.y >= 0)
def off_screen(self, height: int) -> bool:
return not (self.y <= height and self.y >= 0)
def collision(self, obj) -> bool:
return collide(self, obj)
def collision(self, obj) -> bool:
return collide(self, obj)
class Ship:
COOLDOWN = 30 # cooldown before shooting next missile
COOLDOWN = 30 # cooldown before shooting next missile
def __init__(self, x: int, y: int, lives: int = 3) -> None:
self.x = x
self.y = y
self.lives = lives
self.ship_img = None
self.missile_img = None
self.missiles = []
self.cooldown_counter = 0
def __init__(self, x: int, y: int, lives: int = 3) -> None:
self.x = x
self.y = y
self.lives = lives
self.ship_img = None
self.missile_img = None
self.missiles = []
self.cooldown_counter = 0
def draw(self, window) -> None:
window.blit(self.ship_img, (self.x, self.y))
for missile in self.missiles:
missile.draw(WINDOW)
def draw(self, window) -> None:
window.blit(self.ship_img, (self.x, self.y))
for missile in self.missiles:
missile.draw(WINDOW)
def move_missiles(self, vel: int, obj) -> None:
self.cooldown()
for missile in self.missiles:
missile.move(vel)
if missile.off_screen(HEIGHT):
self.missiles.remove(missile)
elif missile.collision(obj):
obj.lives -= 1
self.missiles.remove(missile)
def move_missiles(self, vel: int, obj) -> None:
self.cooldown()
for missile in self.missiles:
missile.move(vel)
if missile.off_screen(HEIGHT):
self.missiles.remove(missile)
elif missile.collision(obj):
obj.lives -= 1
self.missiles.remove(missile)
def cooldown(self) -> None:
if self.cooldown_counter >= self.COOLDOWN:
self.cooldown_counter = 0
elif self.cooldown_counter > 0:
self.cooldown_counter += 1
def cooldown(self) -> None:
if self.cooldown_counter >= self.COOLDOWN:
self.cooldown_counter = 0
elif self.cooldown_counter > 0:
self.cooldown_counter += 1
def shoot(self) -> None:
if self.cooldown_counter == 0:
missile = Missile(self.x + self.get_width() / 2 - 5 / 2, self.y, self.missile_img) # missile spawn with offset
self.missiles.append(missile)
self.cooldown_counter = 1
def shoot(self) -> None:
if self.cooldown_counter == 0:
missile = Missile(self.x + self.get_width() / 2 - 5 / 2,
self.y, self.missile_img) # missile spawn with offset
self.missiles.append(missile)
self.cooldown_counter = 1
def get_width(self) -> int:
return self.ship_img.get_width()
def get_width(self) -> int:
return self.ship_img.get_width()
def get_height(self) -> int:
return self.ship_img.get_height()
def get_height(self) -> int:
return self.ship_img.get_height()
class Player(Ship):
def __init__(self, x: int, y: int, lives: int = 3) -> None:
super().__init__(x, y, lives)
self.ship_img = SPACESHIP
self.missile_img = PLAYER_MISSILE
self.mask = pygame.mask.from_surface(self.ship_img)
self.max_lives = lives
self.score = 0
def __init__(self, x: int, y: int, lives: int = 3) -> None:
super().__init__(x, y, lives)
self.ship_img = SPACESHIP
self.missile_img = PLAYER_MISSILE
self.mask = pygame.mask.from_surface(self.ship_img)
self.max_lives = lives
self.score = 0
def move_missiles(self, vel: int, objs: list) -> None:
self.cooldown()
for missile in self.missiles:
missile.move(vel)
if missile.off_screen(HEIGHT):
self.missiles.remove(missile)
self.score -= 10
else:
for obj in objs:
if missile.collision(obj):
objs.remove(obj)
def move_missiles(self, vel: int, objs: list) -> None:
self.cooldown()
for missile in self.missiles:
missile.move(vel)
if missile.off_screen(HEIGHT):
self.missiles.remove(missile)
self.score -= 10
else:
for obj in objs:
if missile.collision(obj):
objs.remove(obj)
# different scores for different colored enemies
if obj.color == "lime":
self.score += 10
elif obj.color == "cyan":
self.score += 20
elif obj.color == "magenta":
self.score += 30
if missile in self.missiles:
self.missiles.remove(missile)
# different scores for different colored enemies
if obj.color == "lime":
self.score += 10
elif obj.color == "cyan":
self.score += 20
elif obj.color == "magenta":
self.score += 30
if missile in self.missiles:
self.missiles.remove(missile)
class Enemy(Ship):
COLOR_MAP = {
"magenta": ENEMY_1,
"cyan": ENEMY_2,
"lime": ENEMY_3,
}
COLOR_MAP = {
"magenta": ENEMY_1,
"cyan": ENEMY_2,
"lime": ENEMY_3,
}
def __init__(self, x: int, y: int, color: str) -> None:
super().__init__(x, y)
self.missile_img = ENEMY_MISSILE
self.ship_img = self.COLOR_MAP[color]
self.mask = pygame.mask.from_surface(self.ship_img)
self.color = color
def __init__(self, x: int, y: int, color: str) -> None:
super().__init__(x, y)
self.missile_img = ENEMY_MISSILE
self.ship_img = self.COLOR_MAP[color]
self.mask = pygame.mask.from_surface(self.ship_img)
self.color = color
def move(self, vel_x: int, vel_y: int = 0) -> None:
self.x += vel_x
self.y += vel_y
def move(self, vel_x: int, vel_y: int = 0) -> None:
self.x += vel_x
self.y += vel_y
def main() -> None:
FPS = 60
run = True
lost = False
lost_count = 0
level = 0
FPS = 60
run = True
lost = False
lost_count = 0
level = 0
enemies = []
player_vel = 7
player_missile_vel = 15
enemy_x_vel = 2
enemy_y_vel = 2
vel_x = enemy_x_vel
enemy_missile_vel = 6
last_enemy_shot = 0
enemies = []
player_vel = 7
player_missile_vel = 15
enemy_x_vel = 2
enemy_y_vel = 2
vel_x = enemy_x_vel
enemy_missile_vel = 6
last_enemy_shot = 0
player = Player(WIDTH / 2, 650)
player = Player(WIDTH / 2, 650)
clock = pygame.time.Clock()
clock = pygame.time.Clock()
def redraw_window() -> None:
WINDOW.blit(BACKGROUND, (0, 0))
# draw text
lives_label = set_font(40).render(f"Lives: {player.lives}", 1, WHITE)
score_label = set_font(40).render(f"Score {player.score}", 1, WHITE)
level_label = set_font(40).render(f"Level: {level}", 1, WHITE)
WINDOW.blit(lives_label, (10, 10))
WINDOW.blit(score_label, (10, lives_label.get_height() + 10))
WINDOW.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))
def redraw_window() -> None:
WINDOW.blit(BACKGROUND, (0, 0))
# draw text
lives_label = set_font(40).render(f"Lives: {player.lives}", 1, WHITE)
score_label = set_font(40).render(f"Score {player.score}", 1, WHITE)
level_label = set_font(40).render(f"Level: {level}", 1, WHITE)
WINDOW.blit(lives_label, (10, 10))
WINDOW.blit(score_label, (10, lives_label.get_height() + 10))
WINDOW.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))
for enemy in enemies:
enemy.draw(WINDOW)
for enemy in enemies:
enemy.draw(WINDOW)
player.draw(WINDOW)
player.draw(WINDOW)
if lost:
lost_label = set_font(60).render("You lost!", 1, RED)
WINDOW.blit(lost_label, (WIDTH / 2 - lost_label.get_width() / 2, 350))
if lost:
lost_label = set_font(60).render("You lost!", 1, RED)
WINDOW.blit(lost_label, (WIDTH / 2 -
lost_label.get_width() / 2, 350))
pygame.display.update()
pygame.display.update()
while run:
clock.tick(FPS)
redraw_window()
while run:
clock.tick(FPS)
redraw_window()
if player.lives <= 0:
lost = True
lost_count += 1
if player.lives <= 0:
lost = True
lost_count += 1
# stop game
if lost:
if lost_count > FPS * 3: # wait for 3 sec
run = False
else:
continue
# stop game
if lost:
if lost_count > FPS * 3: # wait for 3 sec
run = False
else:
continue
# spawn enemies
if len(enemies) == 0:
level += 1
margin = 75
for x in range(margin, WIDTH - margin, margin):
for y in range(margin, int(HEIGHT / 2), margin):
if y == margin: # top row
color = "magenta"
elif y == 2 * margin: # rows 2-3
color = "cyan"
elif y == 4 * margin: # rows 4-5
color = "lime"
enemy = Enemy(x, y, color)
enemies.append(enemy)
# spawn enemies
if len(enemies) == 0:
level += 1
margin = 75
for x in range(margin, WIDTH - margin, margin):
for y in range(margin, int(HEIGHT / 2), margin):
if y == margin: # top row
color = "magenta"
elif y == 2 * margin: # rows 2-3
color = "cyan"
elif y == 4 * margin: # rows 4-5
color = "lime"
enemy = Enemy(x, y, color)
enemies.append(enemy)
for event in pygame.event.get():
# quit game
if event.type == pygame.QUIT:
quit()
for event in pygame.event.get():
# quit game
if event.type == pygame.QUIT:
quit()
keys = pygame.key.get_pressed()
keys = pygame.key.get_pressed()
# move left
if (keys[pygame.K_a] or keys[pygame.K_LEFT]) and (player.x - player_vel > 0):
player.x -= player_vel
# move right
if (keys[pygame.K_d] or keys[pygame.K_RIGHT]) and (player.x + player_vel + player.get_width() < WIDTH):
player.x += player_vel
# shoot
if keys[pygame.K_SPACE]:
player.shoot()
# move left
if (keys[pygame.K_a] or keys[pygame.K_LEFT]) and (player.x - player_vel > 0):
player.x -= player_vel
# move right
if (keys[pygame.K_d] or keys[pygame.K_RIGHT]) and (player.x + player_vel + player.get_width() < WIDTH):
player.x += player_vel
# shoot
if keys[pygame.K_SPACE]:
player.shoot()
# enemies action
for enemy in enemies[:]:
if enemy.x >= WIDTH - enemy.get_width():
move(0, enemy_y_vel, enemies)
vel_x = -enemy_x_vel
# enemies action
for enemy in enemies[:]:
if enemy.x >= WIDTH - enemy.get_width():
move(0, enemy_y_vel, enemies)
vel_x = -enemy_x_vel
elif enemy.x <= 0:
move(0, enemy_y_vel, enemies)
vel_x = enemy_x_vel
elif enemy.x <= 0:
move(0, enemy_y_vel, enemies)
vel_x = enemy_x_vel
enemy.move_missiles(enemy_missile_vel, player)
enemy.move_missiles(enemy_missile_vel, player)
if collide(enemy, player) or (enemy.y + enemy.get_height() > HEIGHT):
player.score -= 10
player.lives -= 1
enemies.remove(enemy)
if collide(enemy, player) or (enemy.y + enemy.get_height() > HEIGHT):
player.score -= 10
player.lives -= 1
enemies.remove(enemy)
move(vel_x, 0, enemies)
move(vel_x, 0, enemies)
if pygame.time.get_ticks() - last_enemy_shot > 2000:
choice(enemies).shoot()
last_enemy_shot = pygame.time.get_ticks()
if pygame.time.get_ticks() - last_enemy_shot > 2000:
choice(enemies).shoot()
last_enemy_shot = pygame.time.get_ticks()
player.move_missiles(-player_missile_vel, enemies)
player.move_missiles(-player_missile_vel, enemies)
# lambda functions
set_font = lambda size, font=FONT: pygame.font.Font(font, size) # sets font size
collide = lambda obj1, obj2: obj1.mask.overlap(obj2.mask, (obj2.x - obj1.x, obj2.y - obj1.y)) != None # checks if 2 objs collide/overlap
def set_font(size, font=FONT): return pygame.font.Font(
font, size) # sets font size
def collide(obj1, obj2): return obj1.mask.overlap(obj2.mask, (obj2.x -
obj1.x, obj2.y - obj1.y)) != None # checks if 2 objs collide/overlap
def move(vel_x: int, vel_y: int, enemies: list) -> None:
for enemy in enemies:
enemy.move(vel_x, vel_y)
for enemy in enemies:
enemy.move(vel_x, vel_y)
def main_menu() -> None:
while True:
WINDOW.blit(BACKGROUND, (0, 0))
title_label = set_font(50).render("Press any key to start...", 1, WHITE)
WINDOW.blit(title_label, (WIDTH / 2 - title_label.get_width() / 2, HEIGHT / 2 - title_label.get_height() / 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
main()
while True:
WINDOW.blit(BACKGROUND, (0, 0))
title_label = set_font(50).render(
"Press any key to start...", 1, WHITE)
WINDOW.blit(title_label, (WIDTH / 2 - title_label.get_width() /
2, HEIGHT / 2 - title_label.get_height() / 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
main()
if __name__ == "__main__":
main_menu()
main_menu()

View File

@ -1,29 +1,29 @@
beautifulsoup4==4.10.0
beautifulsoup4==4.11.1
bs4==0.0.1
certifi==2021.10.8
charset-normalizer==2.0.12
click==8.1.2
certifi==2022.6.15
charset-normalizer==2.1.0
click==8.1.3
cycler==0.11.0
defusedxml==0.7.1
et-xmlfile==1.1.0
fonttools==4.31.2
fpdf2==2.5.1
fonttools==4.34.4
fpdf2==2.5.5
idna==3.3
kiwisolver==1.4.2
matplotlib==3.5.1
numpy==1.22.3
openpyxl==3.0.9
kiwisolver==1.4.4
matplotlib==3.5.2
numpy==1.23.1
openpyxl==3.0.10
packaging==21.3
pandas==1.4.2
Pillow==9.1.0
pyparsing==3.0.7
pandas==1.4.3
Pillow==9.2.0
pyparsing==3.0.9
python-dateutil==2.8.2
pytz==2022.1
requests==2.27.1
scipy==1.8.0
requests==2.28.1
scipy==1.9.0
seaborn==0.11.2
six==1.16.0
soupsieve==2.3.1
urllib3==1.26.9
soupsieve==2.3.2.post1
urllib3==1.26.11
word2number==1.1
yapf==0.32.0

View File

@ -4,76 +4,85 @@
# task 1 - train
def trains():
# blue train from Jelgava to Riga
blue_train_speed = 57
blue_train_time_driven = 10 / 60
# blue train from Jelgava to Riga
blue_train_speed = 57
blue_train_time_driven = 10 / 60
# green train form Riga to Jelgava
green_train_speed = 60
# green train form Riga to Jelgava
green_train_speed = 60
# red train from Valka to Jelgava
red_train_speed = 60
red_train_time_driven = 4
# red train from Valka to Jelgava
red_train_speed = 60
red_train_time_driven = 4
# distances
distance_riga_jelgava = 42 # from Riga to Jelgava (blue and green train)
distance_riga_valka = 164 # from Riga to Valka (red train)
# distances
distance_riga_jelgava = 42 # from Riga to Jelgava (blue and green train)
distance_riga_valka = 164 # from Riga to Valka (red train)
def blue_green_train():
blue_train_already_driven_distance = blue_train_speed * blue_train_time_driven # blue train driven distance in 10 min
meeting_time = (distance_riga_jelgava - blue_train_already_driven_distance) / (blue_train_speed + green_train_speed) # time after which the two trains meet
green_train_distance = meeting_time * green_train_speed # distance green train has driven
meeting_distance = distance_riga_jelgava - green_train_distance # distance from meeting point to Riga
def blue_green_train():
blue_train_already_driven_distance = blue_train_speed * \
blue_train_time_driven # blue train driven distance in 10 min
meeting_time = (distance_riga_jelgava - blue_train_already_driven_distance) / (
blue_train_speed + green_train_speed) # time after which the two trains meet
green_train_distance = meeting_time * \
green_train_speed # distance green train has driven
meeting_distance = distance_riga_jelgava - \
green_train_distance # distance from meeting point to Riga
return f"Zilais un zaļais vilciens tiksies {round(meeting_distance, 2)}km no Rīgas."
return f"Zilais un zaļais vilciens tiksies {round(meeting_distance, 2)}km no Rīgas."
def red_train():
red_train_distance_driven = red_train_time_driven * red_train_speed # red train driven distance in given time
print(f"Sarkanais vilciens ir nobraucis {round(red_train_distance_driven, 2)}km.")
if red_train_distance_driven > distance_riga_valka:
return "Sarkanais vilciens ir pabraucis garām Rīgai."
def red_train():
red_train_distance_driven = red_train_time_driven * \
red_train_speed # red train driven distance in given time
print(
f"Sarkanais vilciens ir nobraucis {round(red_train_distance_driven, 2)}km.")
if red_train_distance_driven > distance_riga_valka:
return "Sarkanais vilciens ir pabraucis garām Rīgai."
print(blue_green_train())
print(red_train())
print(blue_green_train())
print(red_train())
# task 2 - sheep
def farm():
sheep_amount = 255 # amount of sheep in farm
sheep_price = 20.5 # price per sheep's wool
wool_total_price = sheep_amount * sheep_price # price for all sheep wool
sheep_amount = 255 # amount of sheep in farm
sheep_price = 20.5 # price per sheep's wool
wool_total_price = sheep_amount * sheep_price # price for all sheep wool
additional_sheep = 120 # additional sheep
new_sheep_amount = sheep_amount + additional_sheep # sum of original and added sheep
new_wool_total_price = new_sheep_amount * wool_total_price # price for original and added sheep wool
additional_sheep = 120 # additional sheep
# sum of original and added sheep
new_sheep_amount = sheep_amount + additional_sheep
# price for original and added sheep wool
new_wool_total_price = new_sheep_amount * wool_total_price
ostrich_amount = 15 # amount of ostrich in farm
ostrich_egg_price = 30 # price per egg
ostrich_time = 2 # time required to get one ostrich egg
days = 30 # the time when ostriches lay eggs
ostrich_egg_total_price = ostrich_amount * ostrich_egg_price * days / ostrich_time # price for all ostrich eggs in 30 days
ostrich_amount = 15 # amount of ostrich in farm
ostrich_egg_price = 30 # price per egg
ostrich_time = 2 # time required to get one ostrich egg
days = 30 # the time when ostriches lay eggs
ostrich_egg_total_price = ostrich_amount * ostrich_egg_price * \
days / ostrich_time # price for all ostrich eggs in 30 days
if wool_total_price >= ostrich_egg_total_price:
return "Iegūtās naudas pietiks, lai nopirktu visas mēneša olas."
else:
print("Iegūtās naudas nepietiks, lai nopirktu visas mēneša olas.")
if new_wool_total_price >= ostrich_egg_total_price:
return f"Ja aitu būtu par {additional_sheep}, tad iegūtās naudas pietiktu, lai nopirktu visas mēneša olas."
else:
return f"Ja aitu būtu par {additional_sheep}, tad iegūtās naudas nepietiktu, lai nopirktu visas mēneša olas."
if wool_total_price >= ostrich_egg_total_price:
return "Iegūtās naudas pietiks, lai nopirktu visas mēneša olas."
else:
print("Iegūtās naudas nepietiks, lai nopirktu visas mēneša olas.")
if new_wool_total_price >= ostrich_egg_total_price:
return f"Ja aitu būtu par {additional_sheep}, tad iegūtās naudas pietiktu, lai nopirktu visas mēneša olas."
else:
return f"Ja aitu būtu par {additional_sheep}, tad iegūtās naudas nepietiktu, lai nopirktu visas mēneša olas."
def main():
task = int(input("""Ivēlieties uzdevumu:
task = int(input("""Ivēlieties uzdevumu:
1 - pirmais uzdevums
2 - otrais uzdevums
"""))
if task == 1:
trains()
elif task == 2:
print(farm())
if task == 1:
trains()
elif task == 2:
print(farm())
if __name__ == '__main__':
main()
main()

View File

@ -3,22 +3,24 @@
class SalaryBonus():
def __init__(self):
self.percent = .15 # percent
self.salary = float(input("Mēneša algas apjoms: ")) # salary per month
self.time_worked = int(input("Nostrādātais gadu skaits: ")) # number of years worked
def __init__(self):
self.percent = .15 # percent
self.salary = float(input("Mēneša algas apjoms: ")) # salary per month
# number of years worked
self.time_worked = int(input("Nostrādātais gadu skaits: "))
def _calculate_bonus(self):
if self.time_worked > 2: # if worked for more than 2 years
salary_bonus = self.percent * self.salary * (self.time_worked - 2) # calculates salary bonus
return f"Algas bonuss ir {round(salary_bonus, 2)}"
else:
return "Algas bonuss nepienākas."
def _calculate_bonus(self):
if self.time_worked > 2: # if worked for more than 2 years
salary_bonus = self.percent * self.salary * \
(self.time_worked - 2) # calculates salary bonus
return f"Algas bonuss ir {round(salary_bonus, 2)}"
else:
return "Algas bonuss nepienākas."
def main():
print(SalaryBonus()._calculate_bonus())
print(SalaryBonus()._calculate_bonus())
if __name__ == "__main__":
main()
main()

View File

@ -4,36 +4,38 @@
# task 1 - prime numbers
def is_prime(number):
import math
if number > 0:
if number == 1:
return "1 nav pirmsskaitlis"
else:
for i in range(2, int(math.sqrt(number)) + 1): # range from 2 to sqrt(n)
if number % i == 0:
return f"{number} nav pirmsskaitlis"
return f"{number} ir pirmsskaitlis"
else:
return "Skaitlim jābūt lielākam par 0"
import math
if number > 0:
if number == 1:
return "1 nav pirmsskaitlis"
else:
for i in range(2, int(math.sqrt(number)) + 1): # range from 2 to sqrt(n)
if number % i == 0:
return f"{number} nav pirmsskaitlis"
return f"{number} ir pirmsskaitlis"
else:
return "Skaitlim jābūt lielākam par 0"
# task 2 - cities
class Cities:
def __init__(self, p0, perc, delta, p):
self.p0 = p0 # initial population
self.perc = float(perc[:-1]) / 100 # annual percentage population growth
self.delta = delta # number of arrivals (departures) per year
self.p = p # population size required
def __init__(self, p0, perc, delta, p):
self.p0 = p0 # initial population
# annual percentage population growth
self.perc = float(perc[:-1]) / 100
self.delta = delta # number of arrivals (departures) per year
self.p = p # population size required
def _calculate(self):
years = 0
while (True):
self.p0 = self.p0 + self.p0 * self.perc + self.delta # calculate the new population in each year via the formula
years += 1
if self.p0 >= self.p: # if the initial population reaches the required
return f"{self.p} iedzīvotāju skaits tiks sasniegts pēc {years} gadiem"
if self.p0 < 0: # if the required population is unreachable
return -1
def _calculate(self):
years = 0
while (True):
# calculate the new population in each year via the formula
self.p0 = self.p0 + self.p0 * self.perc + self.delta
years += 1
if self.p0 >= self.p: # if the initial population reaches the required
return f"{self.p} iedzīvotāju skaits tiks sasniegts pēc {years} gadiem"
if self.p0 < 0: # if the required population is unreachable
return -1
city_0 = Cities(1000, "2%", 50, 1200)
@ -43,33 +45,33 @@ city_3 = Cities(1_500_000, "2.5%", 10_000, 2_000_000)
def main():
task = int(input("""Ivēlieties uzdevumu:
task = int(input("""Ivēlieties uzdevumu:
1 - pirmais uzdevums
2 - otrais uzdevums
"""))
if task == 1:
print(is_prime(int(input("Ievadiet skaitli: "))))
elif task == 2:
city = int(input("""Izvēlieties pilsētu:
if task == 1:
print(is_prime(int(input("Ievadiet skaitli: "))))
elif task == 2:
city = int(input("""Izvēlieties pilsētu:
0 - piemēra pilsēta
1 - pirmā pilsēta
2 - otrā pilsēta
3 - trešā pilsēta
"""))
if city == 0:
print(city_0._calculate())
elif city == 1:
print(city_1._calculate())
elif city == 2:
print(city_2._calculate())
elif city == 3:
print(city_3._calculate())
else:
print("Ievadīts nepareizs skaitlis.")
else:
print("Ievadīts nepareizs skaitlis.")
if city == 0:
print(city_0._calculate())
elif city == 1:
print(city_1._calculate())
elif city == 2:
print(city_2._calculate())
elif city == 3:
print(city_3._calculate())
else:
print("Ievadīts nepareizs skaitlis.")
else:
print("Ievadīts nepareizs skaitlis.")
if __name__ == '__main__':
main()
main()