mirror of
https://github.com/kristoferssolo/School.git
synced 2025-10-21 20:10:38 +00:00
Final changes and commit
This commit is contained in:
parent
db328c4350
commit
253802ac88
1
.gitignore
vendored
1
.gitignore
vendored
@ -6,3 +6,4 @@
|
|||||||
/december/task_081221/*.log
|
/december/task_081221/*.log
|
||||||
**.pkl
|
**.pkl
|
||||||
**test.py
|
**test.py
|
||||||
|
pygame/snake/source/score.csv
|
||||||
|
|||||||
@ -67,29 +67,36 @@ bed_frames = IKEA('bedroom/beds-and-sofa-beds/bed-frames')
|
|||||||
bookcases = IKEA('living-room/bookcases/bookcases')
|
bookcases = IKEA('living-room/bookcases/bookcases')
|
||||||
boxes_and_baskets = IKEA('bedroom/sorting-solutions/boxes-and-baskets')
|
boxes_and_baskets = IKEA('bedroom/sorting-solutions/boxes-and-baskets')
|
||||||
candles = IKEA('kitchen/kitchen-decoration/candles')
|
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')
|
chairs_and_benches = IKEA('dining-room/dining-seating/chairs-and-benches')
|
||||||
chest_of_drawers = IKEA('bedroom/chest-of-drawers-other-furniture/chest-of-drawers')
|
chest_of_drawers = IKEA(
|
||||||
children_storage_furniture = IKEA('children-s-room/children-3-7/children-s-storage-furniture')
|
'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')
|
curtains = IKEA('kitchen/curtains-blinds-and-fabrics/curtains')
|
||||||
day_beds = IKEA('bedroom/beds-and-sofa-beds/day-beds')
|
day_beds = IKEA('bedroom/beds-and-sofa-beds/day-beds')
|
||||||
dining_tables = IKEA('dining-room/dining-tables/dining-tables')
|
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')
|
glasses = IKEA('kitchen/cookware-and-dinnerware/glasses')
|
||||||
home_desks = IKEA('home-office/desks/home-desks')
|
home_desks = IKEA('home-office/desks/home-desks')
|
||||||
interior_organisers = IKEA('home-office/wardrobes/interior-organisers')
|
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')
|
light_bulbs = IKEA('bedroom/bedroom-lighting/light-bulbs')
|
||||||
mattresses = IKEA('bedroom/mattresses/mattresses')
|
mattresses = IKEA('bedroom/mattresses/mattresses')
|
||||||
mirrors = IKEA('kitchen/kitchen-decoration/mirrors')
|
mirrors = IKEA('kitchen/kitchen-decoration/mirrors')
|
||||||
office_chairs = IKEA('home-office/work-seating-range/office-chairs')
|
office_chairs = IKEA('home-office/work-seating-range/office-chairs')
|
||||||
office_desks_and_tables = IKEA('home-office/desks/office-desks-and-tables')
|
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')
|
pax_wardrobes = IKEA('ikea-for-business/retail/system-wardrobes')
|
||||||
pendant_lamps = IKEA('ikea-for-business/retail/pendant-lamps')
|
pendant_lamps = IKEA('ikea-for-business/retail/pendant-lamps')
|
||||||
pillows = IKEA('bedroom/bedding/pillows')
|
pillows = IKEA('bedroom/bedding/pillows')
|
||||||
pots = IKEA('kitchen/cookware-and-dinnerware/pots')
|
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')
|
quilts = IKEA('bedroom/bedding/quilts')
|
||||||
rugs = IKEA('living-room/home-furnishing-rugs/rugs')
|
rugs = IKEA('living-room/home-furnishing-rugs/rugs')
|
||||||
sheets_and_pillow_cases = IKEA('bedroom/bedding/sheets-and-pillow-cases')
|
sheets_and_pillow_cases = IKEA('bedroom/bedding/sheets-and-pillow-cases')
|
||||||
@ -100,7 +107,8 @@ solitaire_wardrobes = IKEA('bedroom/wardrobes/solitaire-wardrobes')
|
|||||||
system_cabinets = IKEA('living-room/solitaire-cabinets/system-cabinets')
|
system_cabinets = IKEA('living-room/solitaire-cabinets/system-cabinets')
|
||||||
table_lamps = IKEA('bedroom/bedroom-lighting/table-lamps')
|
table_lamps = IKEA('bedroom/bedroom-lighting/table-lamps')
|
||||||
towels = IKEA('bathroom/towels/towels')
|
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')
|
tv_benches = IKEA('living-room/tv-stands-media-units/tv-benches')
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -17,9 +17,13 @@
|
|||||||
<option value="Bed frames">Bed frames</option>
|
<option value="Bed frames">Bed frames</option>
|
||||||
<option value="Bookcases">Bookcases</option>
|
<option value="Bookcases">Bookcases</option>
|
||||||
<option value="Boxes and baskets">Boxes and baskets</option>
|
<option value="Boxes and baskets">Boxes and baskets</option>
|
||||||
<option value="Ceiling lamps and spotlight">Ceiling lamps and spotlight</option>
|
<option value="Ceiling lamps and spotlight">
|
||||||
|
Ceiling lamps and spotlight
|
||||||
|
</option>
|
||||||
<option value="Chest of drawers">Chest of drawers</option>
|
<option value="Chest of drawers">Chest of drawers</option>
|
||||||
<option value="Children's storage furniture">Children's storage furniture</option>
|
<option value="Children's storage furniture">
|
||||||
|
Children's storage furniture
|
||||||
|
</option>
|
||||||
<option value="curtains">Curtains</option>
|
<option value="curtains">Curtains</option>
|
||||||
<option value="day beds">Day beds</option>
|
<option value="day beds">Day beds</option>
|
||||||
<option value="dining tables">Dining tables</option>
|
<option value="dining tables">Dining tables</option>
|
||||||
@ -27,7 +31,9 @@
|
|||||||
<option value="glasses">Glasses</option>
|
<option value="glasses">Glasses</option>
|
||||||
<option value="home desks">Home desks</option>
|
<option value="home desks">Home desks</option>
|
||||||
<option value="interior organisers">Interior organisers</option>
|
<option value="interior organisers">Interior organisers</option>
|
||||||
<option value="kitchen interior organisers">Kitchen interior organisers</option>
|
<option value="kitchen interior organisers">
|
||||||
|
Kitchen interior organisers
|
||||||
|
</option>
|
||||||
<option value="light bulbs">Light bulbs</option>
|
<option value="light bulbs">Light bulbs</option>
|
||||||
<option value="mattresses">Mattresses</option>
|
<option value="mattresses">Mattresses</option>
|
||||||
<option value="mirrors">Mirrors</option>
|
<option value="mirrors">Mirrors</option>
|
||||||
@ -38,7 +44,9 @@
|
|||||||
<option value="pendant lamps">Pendant lamps</option>
|
<option value="pendant lamps">Pendant lamps</option>
|
||||||
<option value="pillows">Pillows</option>
|
<option value="pillows">Pillows</option>
|
||||||
<option value="pots">Pots</option>
|
<option value="pots">Pots</option>
|
||||||
<option value="quilt covers and pillow cases">Quilt covers and pillow cases</option>
|
<option value="quilt covers and pillow cases">
|
||||||
|
Quilt covers and pillow cases
|
||||||
|
</option>
|
||||||
<option value="quilts">Quilts</option>
|
<option value="quilts">Quilts</option>
|
||||||
<option value="rugs">Rugs</option>
|
<option value="rugs">Rugs</option>
|
||||||
<option value="sheets and pillow cases">Sheets and pillow cases</option>
|
<option value="sheets and pillow cases">Sheets and pillow cases</option>
|
||||||
@ -59,14 +67,14 @@
|
|||||||
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
|
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
|
||||||
<script>
|
<script>
|
||||||
async function call() {
|
async function call() {
|
||||||
let product = document.getElementById("product").value;
|
let product = document.getElementById('product').value
|
||||||
|
|
||||||
let res = await eel.call_in_js(product)();
|
let res = await eel.call_in_js(product)()
|
||||||
document.getElementById("info").innerHTML = res;
|
document.getElementById('info').innerHTML = res
|
||||||
}
|
}
|
||||||
jQuery("#show").on("click", function () {
|
jQuery('#show').on('click', function () {
|
||||||
call();
|
call()
|
||||||
});
|
})
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
html,
|
html,
|
||||||
body {
|
body {
|
||||||
font-family: "Roboto", sans-serif;
|
font-family: 'Roboto', sans-serif;
|
||||||
background: #f2f2f2;
|
background: #f2f2f2;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
|
|||||||
@ -10,7 +10,8 @@ from io import BytesIO
|
|||||||
from openpyxl.styles import Font, Alignment
|
from openpyxl.styles import Font, Alignment
|
||||||
import openpyxl
|
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:
|
class SS:
|
||||||
@ -22,7 +23,8 @@ class SS:
|
|||||||
soup = BeautifulSoup(page.content, 'html.parser')
|
soup = BeautifulSoup(page.content, 'html.parser')
|
||||||
|
|
||||||
last_url = soup.find(class_='td2').findChild('a')['href']
|
last_url = soup.find(class_='td2').findChild('a')['href']
|
||||||
page_amount = last_url[last_url.find("page") + 4:last_url.find(".html")]
|
page_amount = last_url[last_url.find(
|
||||||
|
"page") + 4:last_url.find(".html")]
|
||||||
print(f"Page amount = {page_amount}")
|
print(f"Page amount = {page_amount}")
|
||||||
|
|
||||||
return int(page_amount)
|
return int(page_amount)
|
||||||
@ -38,8 +40,10 @@ class SS:
|
|||||||
soup = BeautifulSoup(page.content, 'html.parser')
|
soup = BeautifulSoup(page.content, 'html.parser')
|
||||||
|
|
||||||
# item ids
|
# item ids
|
||||||
ids = [tag['id'] for tag in soup.select('tr[id]')] # creates list with ids
|
ids = [tag['id']
|
||||||
ids = [x for x in ids if "tr_bnr" not in x] # removes "tr_bnr" elements from list
|
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
|
ids.remove("head_line") # removes first "head_line" id
|
||||||
print(f"Page {page_number}")
|
print(f"Page {page_number}")
|
||||||
|
|
||||||
@ -49,7 +53,8 @@ class SS:
|
|||||||
item_no += 1
|
item_no += 1
|
||||||
|
|
||||||
# image
|
# image
|
||||||
image_url = el.find(class_='msga2').find_next_sibling().findChild('a').findChild('img')['src'] # gets image url
|
image_url = el.find(class_='msga2').find_next_sibling().findChild(
|
||||||
|
'a').findChild('img')['src'] # gets image url
|
||||||
response = requests.get(image_url)
|
response = requests.get(image_url)
|
||||||
img = Image.open(BytesIO(response.content))
|
img = Image.open(BytesIO(response.content))
|
||||||
images.append(img)
|
images.append(img)
|
||||||
@ -58,24 +63,31 @@ class SS:
|
|||||||
items.append(elem.get_text())
|
items.append(elem.get_text())
|
||||||
|
|
||||||
# adverts url
|
# adverts url
|
||||||
item_url = el.findChild(class_='msg2').findChild('div').findChild('a')['href'] # gets url
|
item_url = el.findChild(class_='msg2').findChild(
|
||||||
|
'div').findChild('a')['href'] # gets url
|
||||||
item_url = "https://www.ss.com" + item_url
|
item_url = "https://www.ss.com" + item_url
|
||||||
item_page = requests.get(item_url, headers=HEADERS)
|
item_page = requests.get(item_url, headers=HEADERS)
|
||||||
item_soup = BeautifulSoup(item_page.content, 'html.parser')
|
item_soup = BeautifulSoup(item_page.content, 'html.parser')
|
||||||
|
|
||||||
# adverts full text
|
# adverts full text
|
||||||
item_text = item_soup.find(id='msg_div_msg').get_text() # gets full text
|
item_text = item_soup.find(
|
||||||
item_text = item_text[:item_text.find("Pilsēta:")] # removes text last part (table)
|
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)
|
items.append(item_text)
|
||||||
|
|
||||||
# adverts publication date
|
# adverts publication date
|
||||||
item_date = item_soup.find_all('td', class_='msg_footer') # gets all 'msg_footer' class'
|
# 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
|
item_date = item_date[2].get_text() # extracts 3rd element
|
||||||
items.append(item_date[8:18]) # crops date
|
items.append(item_date[8:18]) # crops date
|
||||||
|
|
||||||
chunk_size = 8
|
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
|
# 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"]
|
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 = pd.DataFrame(chunked_items_list, columns=columns)
|
||||||
df.to_excel(excel_writer='output.xlsx', index=False)
|
df.to_excel(excel_writer='output.xlsx', index=False)
|
||||||
|
|
||||||
@ -96,7 +108,8 @@ class SS:
|
|||||||
|
|
||||||
for i in range(len(images)):
|
for i in range(len(images)):
|
||||||
sheet.row_dimensions[i + 2].height = 51 # sets cell height
|
sheet.row_dimensions[i + 2].height = 51 # sets cell height
|
||||||
ws[f'G{i + 2}'].alignment = Alignment(wrap_text=True) # enables word wrap
|
# enables word wrap
|
||||||
|
ws[f'G{i + 2}'].alignment = Alignment(wrap_text=True)
|
||||||
|
|
||||||
img = openpyxl.drawing.image.Image(images[i])
|
img = openpyxl.drawing.image.Image(images[i])
|
||||||
ws.add_image(img, f"I{i + 2}") # adds images
|
ws.add_image(img, f"I{i + 2}") # adds images
|
||||||
|
|||||||
@ -25,7 +25,8 @@ search = browser.find_element_by_class_name('search-link')
|
|||||||
search.click()
|
search.click()
|
||||||
|
|
||||||
delay = 2
|
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 = browser.find_element_by_id('edit-search')
|
||||||
search.send_keys("dokum") # writes in search line
|
search.send_keys("dokum") # writes in search line
|
||||||
|
|
||||||
@ -33,9 +34,11 @@ search = browser.find_element_by_id('search-header-button')
|
|||||||
search.click()
|
search.click()
|
||||||
|
|
||||||
browser.maximize_window()
|
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
|
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 = browser.find_element_by_css_selector('label[for="filter_type_file"]')
|
||||||
filter.click()
|
filter.click()
|
||||||
|
|||||||
@ -55,7 +55,8 @@ def get_user_input():
|
|||||||
else:
|
else:
|
||||||
browser = input("").lower()
|
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.")
|
print(
|
||||||
|
f"\nChoose from which pages you want to download files (1 4 7; 2-5; all). Maximum is {last_page} pages.")
|
||||||
try:
|
try:
|
||||||
if debug == True:
|
if debug == True:
|
||||||
user_input = "1"
|
user_input = "1"
|
||||||
@ -63,20 +64,26 @@ def get_user_input():
|
|||||||
user_input = input("").lower()
|
user_input = input("").lower()
|
||||||
|
|
||||||
if user_input == "all":
|
if user_input == "all":
|
||||||
pages = list(map(int, range(1, last_page + 1))) # creates list with all pages
|
# creates list with all pages
|
||||||
|
pages = list(map(int, range(1, last_page + 1)))
|
||||||
else:
|
else:
|
||||||
user_page_list = user_input.split(" ")
|
user_page_list = user_input.split(" ")
|
||||||
for page_range in user_page_list:
|
for page_range in user_page_list:
|
||||||
if "-" in page_range:
|
if "-" in page_range:
|
||||||
|
|
||||||
first_num = int(page_range[:page_range.find("-")]) # gets first number
|
# gets first number
|
||||||
second_num = int(page_range[page_range.find("-") + 1:]) + 1 # gets second 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
|
if second_num > last_page: # reduces user input to max page amount
|
||||||
second_num = last_page
|
second_num = last_page
|
||||||
|
|
||||||
user_page_list = user_page_list + list(map(str, range(first_num, second_num))) # creates list with str range
|
user_page_list = user_page_list + \
|
||||||
pages = [elem for elem in user_page_list if not "-" in elem] # removes all elements containing "-"
|
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 = list(map(int, pages)) # convers str to int
|
||||||
pages.sort() # sorts list
|
pages.sort() # sorts list
|
||||||
pages = list(set(pages)) # removes duplicates from list
|
pages = list(set(pages)) # removes duplicates from list
|
||||||
@ -94,7 +101,8 @@ def get_max_page_amount(keyword: str):
|
|||||||
except:
|
except:
|
||||||
try:
|
try:
|
||||||
last_page = soup.find_all(class_='pager__item page-item')
|
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
|
# gets last number from navigation bar
|
||||||
|
last_page = last_page[-1].get_text().strip()[-1]
|
||||||
except:
|
except:
|
||||||
print("Something went wrong. Please try again or try another keyword.")
|
print("Something went wrong. Please try again or try another keyword.")
|
||||||
return int(last_page)
|
return int(last_page)
|
||||||
|
|||||||
@ -37,16 +37,20 @@ def get_data():
|
|||||||
browser.find_element(By.CLASS_NAME, 'search-link').click()
|
browser.find_element(By.CLASS_NAME, 'search-link').click()
|
||||||
|
|
||||||
delay = 2
|
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 = browser.find_element(By.ID, 'edit-search')
|
||||||
search.send_keys(search_word) # writes in search line
|
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(
|
||||||
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.ID, 'filter_type_file')))
|
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()
|
browser.find_element(By.ID, 'search-view-button').click()
|
||||||
for current_page in range(1, last_page + 1):
|
for current_page in range(1, last_page + 1):
|
||||||
@ -79,7 +83,8 @@ def get_user_input():
|
|||||||
else:
|
else:
|
||||||
browser = input("").lower()
|
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.")
|
print(
|
||||||
|
f"\nChoose from which pages you want to download files (1 4 7; 2-5; all). Maximum is {last_page} pages.")
|
||||||
try:
|
try:
|
||||||
if debug == True:
|
if debug == True:
|
||||||
user_input = "16-17"
|
user_input = "16-17"
|
||||||
@ -87,19 +92,25 @@ def get_user_input():
|
|||||||
user_input = input("").lower()
|
user_input = input("").lower()
|
||||||
|
|
||||||
if user_input == "all":
|
if user_input == "all":
|
||||||
pages = list(map(int, range(1, last_page + 1))) # creates list with all pages
|
# creates list with all pages
|
||||||
|
pages = list(map(int, range(1, last_page + 1)))
|
||||||
else:
|
else:
|
||||||
user_page_list = user_input.split(" ")
|
user_page_list = user_input.split(" ")
|
||||||
for page_range in user_page_list:
|
for page_range in user_page_list:
|
||||||
if "-" in page_range:
|
if "-" in page_range:
|
||||||
|
|
||||||
first_num = int(page_range[:page_range.find("-")]) # gets first number
|
# gets first number
|
||||||
second_num = int(page_range[page_range.find("-") + 1:]) + 1 # gets second 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
|
if second_num > last_page: # reduces user input to max page amount
|
||||||
second_num = last_page
|
second_num = last_page
|
||||||
user_page_list = user_page_list + list(map(str, range(first_num, second_num + 1))) # creates list with str range
|
user_page_list = user_page_list + \
|
||||||
pages = [elem for elem in user_page_list if not "-" in elem] # removes all elements containing "-"
|
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 = list(map(int, pages)) # convers str to int
|
||||||
pages.sort() # sorts list
|
pages.sort() # sorts list
|
||||||
pages = list(set(pages)) # removes duplicates from list
|
pages = list(set(pages)) # removes duplicates from list
|
||||||
@ -117,7 +128,8 @@ def get_max_page_amount(keyword: str):
|
|||||||
except:
|
except:
|
||||||
try:
|
try:
|
||||||
last_page = soup.find_all(class_='pager__item page-item')
|
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
|
# gets last number from navigation bar
|
||||||
|
last_page = last_page[-1].get_text().strip()[-1]
|
||||||
except:
|
except:
|
||||||
print("Something went wrong. Please try again or try another keyword.")
|
print("Something went wrong. Please try again or try another keyword.")
|
||||||
return int(last_page)
|
return int(last_page)
|
||||||
|
|||||||
@ -7,10 +7,15 @@ def main():
|
|||||||
else:
|
else:
|
||||||
for page_range in user_input_array:
|
for page_range in user_input_array:
|
||||||
if "-" in page_range:
|
if "-" in page_range:
|
||||||
first_num = int(page_range[:page_range.find("-")]) # gets first number
|
# gets first number
|
||||||
second_num = int(page_range[page_range.find("-") + 1:]) + 1 # gets second number
|
first_num = int(page_range[:page_range.find("-")])
|
||||||
user_input_array = user_input_array + list(map(str, range(first_num, second_num))) # creates list with str range
|
# gets second number
|
||||||
pages = [elem for elem in user_input_array if not "-" in elem] # removes all elements containing "-"
|
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 = list(map(int, pages)) # convers str to int
|
||||||
pages.sort() # sorts list
|
pages.sort() # sorts list
|
||||||
pages = list(set(pages)) # removes duplicates from list
|
pages = list(set(pages)) # removes duplicates from list
|
||||||
|
|||||||
@ -22,6 +22,7 @@ for sheet_name in file.sheet_names:
|
|||||||
new_data = pd.concat([data[0], data[1]]) # concatenates data
|
new_data = pd.concat([data[0], data[1]]) # concatenates data
|
||||||
# print(new_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)
|
||||||
@ -29,7 +29,8 @@ def get_data():
|
|||||||
for column in columns:
|
for column in columns:
|
||||||
for value in data_copy3[column]:
|
for value in data_copy3[column]:
|
||||||
try:
|
try:
|
||||||
data_copy3 = data_copy3.replace(to_replace=value, value=w2n.word_to_num(value))
|
data_copy3 = data_copy3.replace(
|
||||||
|
to_replace=value, value=w2n.word_to_num(value))
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
|
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
|
||||||
|
|||||||
@ -2,13 +2,13 @@
|
|||||||
# Date - 04.02.2022
|
# Date - 04.02.2022
|
||||||
# Title - Classwork
|
# Title - Classwork
|
||||||
|
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from word2number import w2n
|
from word2number import w2n
|
||||||
import seaborn as sns
|
import seaborn as sns
|
||||||
import matplotlib
|
import matplotlib
|
||||||
|
|
||||||
matplotlib.use('Qt5Agg')
|
matplotlib.use('Qt5Agg')
|
||||||
import matplotlib.pyplot as plt
|
|
||||||
|
|
||||||
# mathplotlib ir bibliotēka statisku, animētu un interaktīvu vizualizāciju izveidei
|
# mathplotlib ir bibliotēka statisku, animētu un interaktīvu vizualizāciju izveidei
|
||||||
# seaborn padara matplotlib sarežģītākos momentus par vienkāršākiem
|
# seaborn padara matplotlib sarežģītākos momentus par vienkāršākiem
|
||||||
@ -29,7 +29,8 @@ def get_data():
|
|||||||
for column in columns:
|
for column in columns:
|
||||||
for value in data_copy3[column]:
|
for value in data_copy3[column]:
|
||||||
try:
|
try:
|
||||||
data_copy3 = data_copy3.replace(to_replace=value, value=w2n.word_to_num(value))
|
data_copy3 = data_copy3.replace(
|
||||||
|
to_replace=value, value=w2n.word_to_num(value))
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
|
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
|
||||||
|
|||||||
@ -18,7 +18,8 @@ data = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
|
|||||||
del data["normalized-losses"]
|
del data["normalized-losses"]
|
||||||
|
|
||||||
select_data = data[["make", "engine-size", "num-of-doors"]]
|
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()
|
select_data = select_data.drop_duplicates()
|
||||||
|
|
||||||
col_width = usable_w / 3
|
col_width = usable_w / 3
|
||||||
@ -26,8 +27,10 @@ height = pdf.font_size * 2
|
|||||||
|
|
||||||
for i in range(select_data.shape[0]):
|
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["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(
|
||||||
pdf.cell(col_width, height, str(select_data["num-of-doors"].iloc[i]), border=1)
|
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.ln(height)
|
||||||
|
|
||||||
# pdf.image("output.png", x=None, y=None, w=usable_w, h=0)
|
# pdf.image("output.png", x=None, y=None, w=usable_w, h=0)
|
||||||
|
|||||||
@ -73,16 +73,20 @@ def read():
|
|||||||
|
|
||||||
for file_path in files:
|
for file_path in files:
|
||||||
all_df.append(pd.read_excel(file_path))
|
all_df.append(pd.read_excel(file_path))
|
||||||
df_combined = pd.concat(all_df).reset_index(drop=True) # combine DataFrames
|
df_combined = pd.concat(all_df).reset_index(
|
||||||
df_combined.sort_values(by=[PRICE, PUB_DATE], inplace=True) # sort DataFrame
|
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
|
df_combined.drop_duplicates(keep="first", inplace=True) # drop duplicates
|
||||||
# replaces floor value to intiger
|
# replaces floor value to intiger
|
||||||
for value in df_combined[FLOOR]:
|
for value in df_combined[FLOOR]:
|
||||||
df_combined = df_combined.replace(value, int(float(value[:value.find("/")])))
|
df_combined = df_combined.replace(
|
||||||
|
value, int(float(value[:value.find("/")])))
|
||||||
|
|
||||||
# replaces price value to intiger
|
# replaces price value to intiger
|
||||||
for value in df_combined[PRICE]:
|
for value in df_combined[PRICE]:
|
||||||
df_combined = df_combined.replace(value, replace_value(value, " ", ",", ""))
|
df_combined = df_combined.replace(
|
||||||
|
value, replace_value(value, " ", ",", ""))
|
||||||
|
|
||||||
# replaces "Citi" to 7
|
# replaces "Citi" to 7
|
||||||
for _ in df_combined[ROOM_AMOUNT]:
|
for _ in df_combined[ROOM_AMOUNT]:
|
||||||
@ -93,14 +97,16 @@ def read():
|
|||||||
df_combined = df_combined.replace(value, int(value))
|
df_combined = df_combined.replace(value, int(value))
|
||||||
|
|
||||||
# converts to datetime
|
# converts to datetime
|
||||||
df_combined[PUB_DATE] = pd.to_datetime(df_combined[PUB_DATE], format="%d.%m.%Y").dt.date
|
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)
|
df_combined.to_excel("output/excel/combined.xlsx", index=False)
|
||||||
return df_combined.sort_values(by=PUB_DATE)
|
return df_combined.sort_values(by=PUB_DATE)
|
||||||
|
|
||||||
|
|
||||||
# replace value
|
# 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):
|
def graph_corr(data):
|
||||||
@ -122,9 +128,12 @@ def graph_price(data):
|
|||||||
plt.figure(figsize=(50, 30))
|
plt.figure(figsize=(50, 30))
|
||||||
plt.rc("font", size=15)
|
plt.rc("font", size=15)
|
||||||
|
|
||||||
plot1 = priceGraph(data, (0, 0), "Price to floor", FLOOR, "Floor", range(1, max(data[FLOOR]) + 1))
|
plot1 = priceGraph(data, (0, 0), "Price to floor", FLOOR,
|
||||||
plot2 = priceGraph(data, (0, 1), "Price to room amount", ROOM_AMOUNT, "Room amount")
|
"Floor", range(1, max(data[FLOOR]) + 1))
|
||||||
plot3 = priceGraph(data, (1, 0), "Price to quadrature", QUADRATURE, "Quadrature")
|
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")
|
plot4 = priceGraph(data, (1, 1), "Price to series", SERIES, "Series")
|
||||||
plot5 = priceGraph(data, (2, 0), "Price to date", PUB_DATE, "Date")
|
plot5 = priceGraph(data, (2, 0), "Price to date", PUB_DATE, "Date")
|
||||||
|
|
||||||
@ -165,12 +174,14 @@ def create_pdf(data):
|
|||||||
col_width = width * 2
|
col_width = width * 2
|
||||||
else:
|
else:
|
||||||
col_width = width
|
col_width = width
|
||||||
pdf.cell(col_width, height, str(data[column].iloc[rand_num]), border=1)
|
pdf.cell(col_width, height, str(
|
||||||
|
data[column].iloc[rand_num]), border=1)
|
||||||
pdf.ln(height)
|
pdf.ln(height)
|
||||||
|
|
||||||
pdf.ln(height)
|
pdf.ln(height)
|
||||||
pdf.image(f"{output_path}/korelacija.png", w=usable_w) # corr graph
|
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.write(
|
||||||
|
LINE_HEIGHT, "Starp istabu skaitu un cenu, kvadratūru un cenu ir liela korelācija.")
|
||||||
pdf.ln(height)
|
pdf.ln(height)
|
||||||
pdf.image(f"{output_path}/cenu_grafiki.png", w=usable_w) # price graph
|
pdf.image(f"{output_path}/cenu_grafiki.png", w=usable_w) # price graph
|
||||||
|
|
||||||
@ -228,11 +239,16 @@ def graph_plot():
|
|||||||
create_pdf(data)
|
create_pdf(data)
|
||||||
|
|
||||||
|
|
||||||
flats_riga = SS("https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga")
|
flats_riga = SS(
|
||||||
flats_rigareg = SS("https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg")
|
"https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga")
|
||||||
flats_aizkraukle = SS("https://www.ss.com/lv/real-estate/flats/aizkraukle-and-reg/sell/", "aizkraukle")
|
flats_rigareg = SS(
|
||||||
flats_tukums = SS("https://www.ss.com/lv/real-estate/flats/tukums-and-reg/sell/", "tukums")
|
"https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg")
|
||||||
flats_ogre = SS("https://www.ss.com/lv/real-estate/flats/ogre-and-reg/sell/", "ogre")
|
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 = """
|
OPERATIONS = """
|
||||||
python pd_pandas_k_f_cagulis.py
|
python pd_pandas_k_f_cagulis.py
|
||||||
|
|||||||
@ -27,7 +27,8 @@ class SS:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
last_url = soup.find(class_='td2').findChild('a')['href']
|
last_url = soup.find(class_='td2').findChild('a')['href']
|
||||||
page_amount = last_url[last_url.find("page") + 4:last_url.find(".html")]
|
page_amount = last_url[last_url.find(
|
||||||
|
"page") + 4:last_url.find(".html")]
|
||||||
except:
|
except:
|
||||||
page_amount = 1
|
page_amount = 1
|
||||||
# print(f"Page amount = {page_amount}")
|
# print(f"Page amount = {page_amount}")
|
||||||
@ -50,8 +51,10 @@ class SS:
|
|||||||
soup = BeautifulSoup(page.content, 'html.parser')
|
soup = BeautifulSoup(page.content, 'html.parser')
|
||||||
|
|
||||||
# item ids
|
# item ids
|
||||||
ids = [tag['id'] for tag in soup.select('tr[id]')] # creates list with ids
|
ids = [tag['id']
|
||||||
ids = [x for x in ids if "tr_bnr" not in x] # removes "tr_bnr" elements from list
|
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
|
ids.remove("head_line") # removes first "head_line" id
|
||||||
# print(f"Page {page_number}")
|
# print(f"Page {page_number}")
|
||||||
|
|
||||||
@ -69,36 +72,49 @@ class SS:
|
|||||||
del items[-2]
|
del items[-2]
|
||||||
|
|
||||||
# adverts url
|
# adverts url
|
||||||
item_url = id.findChild(class_='msg2').findChild('div').findChild('a')['href'] # gets url
|
item_url = id.findChild(class_='msg2').findChild(
|
||||||
|
'div').findChild('a')['href'] # gets url
|
||||||
item_url = "https://www.ss.com" + item_url
|
item_url = "https://www.ss.com" + item_url
|
||||||
item_page = requests.get(item_url, headers=HEADERS)
|
item_page = requests.get(item_url, headers=HEADERS)
|
||||||
item_soup = BeautifulSoup(item_page.content, 'html.parser')
|
item_soup = BeautifulSoup(item_page.content, 'html.parser')
|
||||||
|
|
||||||
# adverts full text
|
# adverts full text
|
||||||
item_text = item_soup.find(id='msg_div_msg').get_text() # gets full text
|
item_text = item_soup.find(
|
||||||
item_text = item_text[:item_text.find("Pilsēta:")] # removes text last part (table)
|
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)
|
items.append(item_text)
|
||||||
|
|
||||||
# adverts publication date
|
# adverts publication date
|
||||||
item_date = item_soup.find_all('td', class_='msg_footer') # gets all 'msg_footer' class'
|
# 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
|
item_date = item_date[2].get_text() # extracts 3rd element
|
||||||
items.append(item_date[8:18]) # crops date
|
items.append(item_date[8:18]) # crops date
|
||||||
bar.end()
|
bar.end()
|
||||||
chunk_size = 8
|
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
|
# 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"]
|
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 = pd.DataFrame(chunked_items_list, columns=columns)
|
||||||
time = datetime.now().strftime("%d%m%y%H%M%S") # current time
|
time = datetime.now().strftime("%d%m%y%H%M%S") # current time
|
||||||
if "excel" not in listdir("output"):
|
if "excel" not in listdir("output"):
|
||||||
mkdir("output/excel")
|
mkdir("output/excel")
|
||||||
df.to_excel(excel_writer=f"output/excel/ss_{self.name}_{time}.xlsx", index=False)
|
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_riga = SS(
|
||||||
flats_rigareg = SS("https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg")
|
"https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga")
|
||||||
flats_aizkraukle = SS("https://www.ss.com/lv/real-estate/flats/aizkraukle-and-reg/sell/", "aizkraukle")
|
flats_rigareg = SS(
|
||||||
flats_tukums = SS("https://www.ss.com/lv/real-estate/flats/tukums-and-reg/sell/", "tukums")
|
"https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg")
|
||||||
flats_ogre = SS("https://www.ss.com/lv/real-estate/flats/ogre-and-reg/sell/", "ogre")
|
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():
|
def main():
|
||||||
|
|||||||
@ -3,4 +3,6 @@ import pandas
|
|||||||
dati = pandas.read_csv('auto_imports_mainits.csv')
|
dati = pandas.read_csv('auto_imports_mainits.csv')
|
||||||
|
|
||||||
for index, element in enumerate(dati.isnull().sum()):
|
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}")
|
||||||
|
|||||||
@ -15,7 +15,8 @@ def main():
|
|||||||
print("-" * 22)
|
print("-" * 22)
|
||||||
|
|
||||||
# 2nd method
|
# 2nd method
|
||||||
print(pd.DataFrame(data.isnull().sum(), data.columns[data.isnull().any()]).to_string(header=None))
|
print(pd.DataFrame(data.isnull().sum(),
|
||||||
|
data.columns[data.isnull().any()]).to_string(header=None))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@ -63,7 +63,8 @@ def main():
|
|||||||
for column in columns:
|
for column in columns:
|
||||||
for value in data_copy3[column]:
|
for value in data_copy3[column]:
|
||||||
try:
|
try:
|
||||||
data_copy3 = data_copy3.replace(to_replace=value, value=w2n.word_to_num(value))
|
data_copy3 = data_copy3.replace(
|
||||||
|
to_replace=value, value=w2n.word_to_num(value))
|
||||||
print(type(w2n.word_to_num(value)))
|
print(type(w2n.word_to_num(value)))
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|||||||
@ -8,10 +8,12 @@ CHAPTERS = 61
|
|||||||
# creates file with chapters and row numbers
|
# creates file with chapters and row numbers
|
||||||
def read_array(document):
|
def read_array(document):
|
||||||
with open(document, "r", encoding='utf-8') as book:
|
with open(document, "r", encoding='utf-8') as book:
|
||||||
lines = [line.strip('\n') for line in book] # removes 'enter' characters
|
lines = [line.strip('\n')
|
||||||
|
for line in book] # removes 'enter' characters
|
||||||
with open('array_output.txt', 'w') as output:
|
with open('array_output.txt', 'w') as output:
|
||||||
for i in range(1, CHAPTERS + 1):
|
for i in range(1, CHAPTERS + 1):
|
||||||
line = lines.index(f"Chapter {i}") + 1 # finds all chapter indexes/lines
|
# finds all chapter indexes/lines
|
||||||
|
line = lines.index(f"Chapter {i}") + 1
|
||||||
output.write(f"Line {line} - Chapter {i}\n") # writes line in file
|
output.write(f"Line {line} - Chapter {i}\n") # writes line in file
|
||||||
|
|
||||||
|
|
||||||
@ -21,8 +23,10 @@ def read_string(document):
|
|||||||
lines = book.read()
|
lines = book.read()
|
||||||
with open('str_output.txt', 'w') as output:
|
with open('str_output.txt', 'w') as output:
|
||||||
for i in range(1, CHAPTERS + 1):
|
for i in range(1, CHAPTERS + 1):
|
||||||
_, position = re.finditer(rf"\bChapter {i}\b", lines) # finds all chapter positions
|
# finds all chapter positions
|
||||||
output.write(f"Position {position.start()} - Chapter {i}\n") # writes position in file
|
_, 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):
|
def read_book(document):
|
||||||
|
|||||||
@ -35,7 +35,9 @@ def task_2():
|
|||||||
|
|
||||||
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
|
# 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.legend(new_data_list, loc='upper left', fontsize=15)
|
||||||
plt.show()
|
plt.show()
|
||||||
|
|
||||||
@ -57,12 +59,14 @@ def task_3():
|
|||||||
def task_4():
|
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.xticks(rotation=0) # rotates x lables to 0
|
||||||
plt.grid(ls='dashed', lw=1.5) # sets grid line type and width
|
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")
|
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))
|
new_items_list = list(map(lambda x: x.capitalize() + " Sales Data", items))
|
||||||
plt.legend(new_items_list, loc='upper left', fontsize=15)
|
plt.legend(new_items_list, loc='upper left', fontsize=15)
|
||||||
plt.show()
|
plt.show()
|
||||||
|
|||||||
@ -22,6 +22,7 @@ if all_page.status_code == 200:
|
|||||||
for i in found:
|
for i in found:
|
||||||
# print(i.prettify())
|
# print(i.prettify())
|
||||||
if i.attrs["lang"] == "ru":
|
if i.attrs["lang"] == "ru":
|
||||||
print(f"{i.attrs['lang']} \t {i.attrs['title']} \n {i.attrs['href']}")
|
print(
|
||||||
|
f"{i.attrs['lang']} \t {i.attrs['title']} \n {i.attrs['href']}")
|
||||||
else:
|
else:
|
||||||
print(":(")
|
print(":(")
|
||||||
@ -8,10 +8,12 @@ CHAPTERS = 61
|
|||||||
# creates file with chapters and row numbers
|
# creates file with chapters and row numbers
|
||||||
def read_array(document):
|
def read_array(document):
|
||||||
with open(document, "r", encoding='utf-8') as book:
|
with open(document, "r", encoding='utf-8') as book:
|
||||||
lines = [line.strip('\n') for line in book] # removes 'enter' characters
|
lines = [line.strip('\n')
|
||||||
|
for line in book] # removes 'enter' characters
|
||||||
with open('array_output.txt', 'w') as output:
|
with open('array_output.txt', 'w') as output:
|
||||||
for i in range(1, CHAPTERS + 1):
|
for i in range(1, CHAPTERS + 1):
|
||||||
line = lines.index(f"Chapter {i}") + 1 # finds all chapter indexes/lines
|
# finds all chapter indexes/lines
|
||||||
|
line = lines.index(f"Chapter {i}") + 1
|
||||||
output.write(f"Line {line} - Chapter {i}\n") # writes line in file
|
output.write(f"Line {line} - Chapter {i}\n") # writes line in file
|
||||||
|
|
||||||
|
|
||||||
@ -21,8 +23,10 @@ def read_string(document):
|
|||||||
lines = book.read()
|
lines = book.read()
|
||||||
with open('str_output.txt', 'w') as output:
|
with open('str_output.txt', 'w') as output:
|
||||||
for i in range(1, CHAPTERS + 1):
|
for i in range(1, CHAPTERS + 1):
|
||||||
_, position = re.finditer(rf"\bChapter {i}\b", lines) # finds all chapter positions
|
# finds all chapter positions
|
||||||
output.write(f"Position {position.start()} - Chapter {i}\n") # writes position in file
|
_, 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):
|
def read_book(document):
|
||||||
|
|||||||
@ -12,18 +12,21 @@ class Cube:
|
|||||||
|
|
||||||
def move(self, direction: tuple) -> None:
|
def move(self, direction: tuple) -> None:
|
||||||
self.direction = direction
|
self.direction = direction
|
||||||
self.pos = (self.pos[0] + self.direction[0], self.pos[1] + self.direction[1])
|
self.pos = (self.pos[0] + self.direction[0],
|
||||||
|
self.pos[1] + self.direction[1])
|
||||||
|
|
||||||
def draw(self, eyes=False) -> None:
|
def draw(self, eyes=False) -> None:
|
||||||
distance = WIDTH // ROWS
|
distance = WIDTH // ROWS
|
||||||
i, j = self.pos
|
i, j = self.pos
|
||||||
|
|
||||||
pygame.draw.rect(WINDOW, self.color, (i * distance + 1, j * distance + 1, distance - 2, distance - 2))
|
pygame.draw.rect(WINDOW, self.color, (i * distance + 1,
|
||||||
|
j * distance + 1, distance - 2, distance - 2))
|
||||||
if eyes:
|
if eyes:
|
||||||
center = distance // 2
|
center = distance // 2
|
||||||
radius = 3
|
radius = 3
|
||||||
circle_middle = (i * distance + center - radius, j * distance + 8)
|
circle_middle = (i * distance + center - radius, j * distance + 8)
|
||||||
circle_middle_2 = (i * distance + distance - radius * 2, 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, radius)
|
||||||
pygame.draw.circle(WINDOW, BLACK, circle_middle_2, radius)
|
pygame.draw.circle(WINDOW, BLACK, circle_middle_2, radius)
|
||||||
|
|
||||||
@ -53,7 +56,8 @@ class Snake:
|
|||||||
self.direction = -1, 0
|
self.direction = -1, 0
|
||||||
self.turns[self.head.pos[:]] = self.direction
|
self.turns[self.head.pos[:]] = self.direction
|
||||||
|
|
||||||
if keys[pygame.K_RIGHT] and self.direction != (-1, 0): # turn right
|
# turn right
|
||||||
|
if keys[pygame.K_RIGHT] and self.direction != (-1, 0):
|
||||||
self.direction = 1, 0
|
self.direction = 1, 0
|
||||||
self.turns[self.head.pos[:]] = self.direction
|
self.turns[self.head.pos[:]] = self.direction
|
||||||
|
|
||||||
@ -113,7 +117,8 @@ class Snake:
|
|||||||
elif head.direction[0] == 1 and head.pos[0] >= ROWS - 1: # right to left
|
elif head.direction[0] == 1 and head.pos[0] >= ROWS - 1: # right to left
|
||||||
head.pos = (0, head.pos[1])
|
head.pos = (0, head.pos[1])
|
||||||
|
|
||||||
elif head.direction[1] == 1 and head.pos[1] >= COLUMNS - 1: # bottom to top
|
# bottom to top
|
||||||
|
elif head.direction[1] == 1 and head.pos[1] >= COLUMNS - 1:
|
||||||
head.pos = (head.pos[0], 0)
|
head.pos = (head.pos[0], 0)
|
||||||
|
|
||||||
elif head.direction[1] == -1 and head.pos[1] <= 0: # top to bottom
|
elif head.direction[1] == -1 and head.pos[1] <= 0: # top to bottom
|
||||||
@ -153,7 +158,8 @@ class Snack:
|
|||||||
self.randomize()
|
self.randomize()
|
||||||
|
|
||||||
def draw_snack(self) -> None:
|
def draw_snack(self) -> None:
|
||||||
snack_rect = pygame.Rect(self.pos[0] * CELL_SIZE, self.pos[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE)
|
snack_rect = pygame.Rect(
|
||||||
|
self.pos[0] * CELL_SIZE, self.pos[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE)
|
||||||
WINDOW.blit(self.texture, snack_rect)
|
WINDOW.blit(self.texture, snack_rect)
|
||||||
|
|
||||||
def randomize(self) -> None:
|
def randomize(self) -> None:
|
||||||
@ -168,7 +174,8 @@ class Button():
|
|||||||
self.base_color = base_color
|
self.base_color = base_color
|
||||||
self.hover_color = hover_color
|
self.hover_color = hover_color
|
||||||
self.text = text
|
self.text = text
|
||||||
self.text_rect = self.font.render(self.text, 1, self.base_color).get_rect(center=(self.pos))
|
self.text_rect = self.font.render(
|
||||||
|
self.text, 1, self.base_color).get_rect(center=(self.pos))
|
||||||
|
|
||||||
def update(self) -> None:
|
def update(self) -> None:
|
||||||
WINDOW.blit(self.text, self.text_rect)
|
WINDOW.blit(self.text, self.text_rect)
|
||||||
|
|||||||
@ -19,21 +19,30 @@ def main_menu() -> None:
|
|||||||
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
|
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
|
||||||
WINDOW.blit(menu_text, menu_rect)
|
WINDOW.blit(menu_text, menu_rect)
|
||||||
|
|
||||||
play_button = Button((MID_WIDTH, MID_HEIGHT - 50), "PLAY", 75, GRAY, WHITE)
|
play_button = Button((MID_WIDTH, MID_HEIGHT - 50),
|
||||||
options_button = Button((MID_WIDTH, MID_HEIGHT + 50), "OPTIONS", 75, GRAY, WHITE)
|
"PLAY", 75, GRAY, WHITE)
|
||||||
score_button = Button((MID_WIDTH, MID_HEIGHT + 150), "SCORE", 75, GRAY, WHITE)
|
options_button = Button(
|
||||||
quit_button = Button((MID_WIDTH, MID_HEIGHT + 250), "QUIT", 75, GRAY, WHITE)
|
(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]
|
buttons = [play_button, options_button, score_button, quit_button]
|
||||||
|
|
||||||
on_hover(buttons)
|
on_hover(buttons)
|
||||||
|
|
||||||
for event in pygame.event.get():
|
for event in pygame.event.get():
|
||||||
if event.type == pygame.QUIT: quit()
|
if event.type == pygame.QUIT:
|
||||||
|
quit()
|
||||||
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
|
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
|
||||||
if play_button.check_input(mouse_pos): user_input(0)
|
if play_button.check_input(mouse_pos):
|
||||||
if options_button.check_input(mouse_pos): options()
|
user_input(0)
|
||||||
if score_button.check_input(mouse_pos): scoreboard()
|
if options_button.check_input(mouse_pos):
|
||||||
if quit_button.check_input(mouse_pos): quit()
|
options()
|
||||||
|
if score_button.check_input(mouse_pos):
|
||||||
|
scoreboard()
|
||||||
|
if quit_button.check_input(mouse_pos):
|
||||||
|
quit()
|
||||||
|
|
||||||
pygame.display.update()
|
pygame.display.update()
|
||||||
|
|
||||||
@ -54,17 +63,21 @@ def user_input(player: int) -> None:
|
|||||||
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
|
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
|
||||||
WINDOW.blit(menu_text, menu_rect)
|
WINDOW.blit(menu_text, menu_rect)
|
||||||
|
|
||||||
back_button = Button((130, WINDOW_HEIGHT - 50), "BACK", 75, GRAY, WHITE)
|
back_button = Button((130, WINDOW_HEIGHT - 50),
|
||||||
|
"BACK", 75, GRAY, WHITE)
|
||||||
if multiplayer and player == 0:
|
if multiplayer and player == 0:
|
||||||
next_button = Button((WIDTH - 130, WINDOW_HEIGHT - 50), "NEXT", 75, GRAY, WHITE)
|
next_button = Button(
|
||||||
|
(WIDTH - 130, WINDOW_HEIGHT - 50), "NEXT", 75, GRAY, WHITE)
|
||||||
buttons = [back_button, next_button]
|
buttons = [back_button, next_button]
|
||||||
else:
|
else:
|
||||||
play_button = Button((WIDTH - 130, WINDOW_HEIGHT - 50), "PLAY", 75, GRAY, WHITE)
|
play_button = Button(
|
||||||
|
(WIDTH - 130, WINDOW_HEIGHT - 50), "PLAY", 75, GRAY, WHITE)
|
||||||
buttons = [back_button, play_button]
|
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)
|
name_rect = pygame.Rect(
|
||||||
|
MID_WIDTH - name_rect_w / 2, 200, name_rect_w, 32)
|
||||||
pygame.draw.rect(WINDOW, outline_color, name_rect, 2)
|
pygame.draw.rect(WINDOW, outline_color, name_rect, 2)
|
||||||
user_text = set_font(20).render(user_name[player], 1, WHITE)
|
user_text = set_font(20).render(user_name[player], 1, WHITE)
|
||||||
WINDOW.blit(user_text, (name_rect.x + 5, name_rect.y + 5))
|
WINDOW.blit(user_text, (name_rect.x + 5, name_rect.y + 5))
|
||||||
@ -74,41 +87,56 @@ def user_input(player: int) -> None:
|
|||||||
color_rect = pygame.Rect(MID_WIDTH - 50, 350, 100, 100)
|
color_rect = pygame.Rect(MID_WIDTH - 50, 350, 100, 100)
|
||||||
pygame.draw.rect(WINDOW, color, color_rect)
|
pygame.draw.rect(WINDOW, color, color_rect)
|
||||||
|
|
||||||
if select_active: outline_color = WHITE
|
if select_active:
|
||||||
else: outline_color = DARK_GRAY
|
outline_color = WHITE
|
||||||
|
else:
|
||||||
|
outline_color = DARK_GRAY
|
||||||
|
|
||||||
for event in pygame.event.get():
|
for event in pygame.event.get():
|
||||||
if event.type == pygame.QUIT: quit()
|
if event.type == pygame.QUIT:
|
||||||
|
quit()
|
||||||
|
|
||||||
if event.type == pygame.MOUSEBUTTONDOWN:
|
if event.type == pygame.MOUSEBUTTONDOWN:
|
||||||
if event.button == 1:
|
if event.button == 1:
|
||||||
if name_rect.collidepoint(event.pos): select_active = True
|
if name_rect.collidepoint(event.pos):
|
||||||
else: select_active = False
|
select_active = True
|
||||||
|
|
||||||
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:
|
else:
|
||||||
if play_button.check_input(mouse_pos): main()
|
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):
|
if color_rect.collidepoint(event.pos):
|
||||||
color_index[player] += 1
|
color_index[player] += 1
|
||||||
if color_index[player] == len(COLORS) - 1:
|
if color_index[player] == len(COLORS) - 1:
|
||||||
color_index[player] = 0
|
color_index[player] = 0
|
||||||
|
|
||||||
if event.button == 3: # clear user name on mouse right click
|
if event.button == 3: # clear user name on mouse right click
|
||||||
if name_rect.collidepoint(event.pos): user_name[player] = ""
|
if name_rect.collidepoint(event.pos):
|
||||||
|
user_name[player] = ""
|
||||||
|
|
||||||
if event.type == pygame.KEYDOWN:
|
if event.type == pygame.KEYDOWN:
|
||||||
if event.key == pygame.K_ESCAPE: main_menu()
|
if event.key == pygame.K_ESCAPE:
|
||||||
|
main_menu()
|
||||||
|
|
||||||
if select_active:
|
if select_active:
|
||||||
if event.key == pygame.K_BACKSPACE: user_name[player] = user_name[player][:-1]
|
if event.key == pygame.K_BACKSPACE:
|
||||||
elif event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER: continue
|
user_name[player] = user_name[player][:-1]
|
||||||
else: user_name[player] += event.unicode
|
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 event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
|
||||||
if multiplayer and player == 0: user_input(1)
|
if multiplayer and player == 0:
|
||||||
else: main()
|
user_input(1)
|
||||||
|
else:
|
||||||
|
main()
|
||||||
|
|
||||||
pygame.display.update()
|
pygame.display.update()
|
||||||
|
|
||||||
@ -126,31 +154,45 @@ def options() -> None:
|
|||||||
|
|
||||||
# change state names
|
# change state names
|
||||||
# multiplayer
|
# multiplayer
|
||||||
if multiplayer: multiplayer_state = "on"
|
if multiplayer:
|
||||||
else: multiplayer_state = "off"
|
multiplayer_state = "on"
|
||||||
|
else:
|
||||||
|
multiplayer_state = "off"
|
||||||
# walls
|
# walls
|
||||||
if walls: walls_state = "on"
|
if walls:
|
||||||
else: walls_state = "off"
|
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)
|
speed_button = Button((MID_WIDTH, MID_HEIGHT - 100),
|
||||||
multiplayer_button = Button((MID_WIDTH, MID_HEIGHT), f"MULTIPLAYER - {multiplayer_state}", 75, GRAY, WHITE)
|
f"SPEED - {speed_state[fps]}", 75, GRAY, WHITE)
|
||||||
walls_button = Button((MID_WIDTH, MID_HEIGHT + 100), f"WALLS - {walls_state}", 75, GRAY, WHITE)
|
multiplayer_button = Button(
|
||||||
back_button = Button((MID_WIDTH, MID_HEIGHT + 200), "BACK", 75, GRAY, WHITE)
|
(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]
|
buttons = [speed_button, multiplayer_button, walls_button, back_button]
|
||||||
|
|
||||||
on_hover(buttons)
|
on_hover(buttons)
|
||||||
|
|
||||||
for event in pygame.event.get():
|
for event in pygame.event.get():
|
||||||
if event.type == pygame.QUIT: quit()
|
if event.type == pygame.QUIT:
|
||||||
|
quit()
|
||||||
if event.type == pygame.KEYDOWN:
|
if event.type == pygame.KEYDOWN:
|
||||||
if event.key == pygame.K_ESCAPE: main_menu()
|
if event.key == pygame.K_ESCAPE:
|
||||||
|
main_menu()
|
||||||
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
|
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
|
||||||
if speed_button.check_input(mouse_pos): change_speed()
|
if speed_button.check_input(mouse_pos):
|
||||||
if multiplayer_button.check_input(mouse_pos): switch_multiplayer()
|
change_speed()
|
||||||
if walls_button.check_input(mouse_pos): switch_walls()
|
if multiplayer_button.check_input(mouse_pos):
|
||||||
if back_button.check_input(mouse_pos): main_menu()
|
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()
|
||||||
|
|
||||||
@ -162,21 +204,26 @@ def scoreboard() -> None:
|
|||||||
top_text = set_font(100).render("TOP 10", 1, WHITE)
|
top_text = set_font(100).render("TOP 10", 1, WHITE)
|
||||||
top_rect = top_text.get_rect(center=(MID_WIDTH, 55))
|
top_rect = top_text.get_rect(center=(MID_WIDTH, 55))
|
||||||
WINDOW.blit(top_text, top_rect)
|
WINDOW.blit(top_text, top_rect)
|
||||||
back_button = Button((MID_WIDTH, MID_HEIGHT + 250), "BACK", 75, GRAY, WHITE)
|
back_button = Button((MID_WIDTH, MID_HEIGHT + 250),
|
||||||
|
"BACK", 75, GRAY, WHITE)
|
||||||
on_hover([back_button])
|
on_hover([back_button])
|
||||||
|
|
||||||
for event in pygame.event.get():
|
for event in pygame.event.get():
|
||||||
if event.type == pygame.QUIT: quit()
|
if event.type == pygame.QUIT:
|
||||||
|
quit()
|
||||||
if event.type == pygame.KEYDOWN:
|
if event.type == pygame.KEYDOWN:
|
||||||
if event.key == pygame.K_ESCAPE: main_menu()
|
if event.key == pygame.K_ESCAPE:
|
||||||
|
main_menu()
|
||||||
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
|
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
|
||||||
if back_button.check_input(mouse_pos): main_menu()
|
if back_button.check_input(mouse_pos):
|
||||||
|
main_menu()
|
||||||
|
|
||||||
csv_file = read_score(BASE_PATH)
|
csv_file = read_score(BASE_PATH)
|
||||||
for i, line in enumerate(sort(csv_file, reverse=True)[:11]):
|
for i, line in enumerate(sort(csv_file, reverse=True)[:11]):
|
||||||
for j, text in enumerate(line):
|
for j, text in enumerate(line):
|
||||||
score_text = set_font(30).render(text, 1, WHITE)
|
score_text = set_font(30).render(text, 1, WHITE)
|
||||||
score_rect = score_text.get_rect(center=(MID_WIDTH - 150 + 300 * j, 150 + 30 * i))
|
score_rect = score_text.get_rect(
|
||||||
|
center=(MID_WIDTH - 150 + 300 * j, 150 + 30 * i))
|
||||||
WINDOW.blit(score_text, score_rect)
|
WINDOW.blit(score_text, score_rect)
|
||||||
|
|
||||||
pygame.display.update()
|
pygame.display.update()
|
||||||
|
|||||||
@ -29,7 +29,8 @@ def read_score(path: str):
|
|||||||
|
|
||||||
|
|
||||||
def sort(data, reverse: bool):
|
def sort(data, reverse: bool):
|
||||||
if reverse == None: reverse = False
|
if reverse == None:
|
||||||
|
reverse = False
|
||||||
header = data[0]
|
header = data[0]
|
||||||
data.remove(header) # remove header
|
data.remove(header) # remove header
|
||||||
data = sorted(data, key=lambda x: int(x[1]), reverse=reverse) # sort data
|
data = sorted(data, key=lambda x: int(x[1]), reverse=reverse) # sort data
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import pygame
|
|
||||||
from os.path import join, abspath, dirname
|
from os.path import join, abspath, dirname
|
||||||
|
import pygame
|
||||||
|
|
||||||
CELL_SIZE = 30
|
CELL_SIZE = 30
|
||||||
ROWS, COLUMNS = 30, 20
|
ROWS, COLUMNS = 30, 20
|
||||||
@ -11,9 +11,12 @@ pygame.font.init()
|
|||||||
BASE_PATH = abspath(dirname(__file__))
|
BASE_PATH = abspath(dirname(__file__))
|
||||||
FONT = join(BASE_PATH, "fonts", "roboto.ttf")
|
FONT = join(BASE_PATH, "fonts", "roboto.ttf")
|
||||||
SPRITE_PATH = join(BASE_PATH, "assets", "sprites")
|
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))
|
APPLE_TEXTURE = pygame.transform.scale(pygame.image.load(
|
||||||
POISON_TEXTURE = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "poison.png")), (CELL_SIZE, CELL_SIZE))
|
join(SPRITE_PATH, "golden_apple.png")), (CELL_SIZE, CELL_SIZE))
|
||||||
COBBLESTONE_TEXTURE = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "cobblestone.jpeg")), (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)
|
BLACK = (0, 0, 0)
|
||||||
DARK_BLUE = (0, 0, 170)
|
DARK_BLUE = (0, 0, 170)
|
||||||
@ -32,9 +35,12 @@ LIGHT_PURPLE = (255, 85, 255)
|
|||||||
YELLOW = (255, 255, 85)
|
YELLOW = (255, 255, 85)
|
||||||
WHITE = (242, 242, 242)
|
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
|
fps = 10 # speed
|
||||||
multiplayer = False
|
multiplayer = False
|
||||||
@ -43,9 +49,12 @@ walls = False
|
|||||||
|
|
||||||
def change_speed() -> None:
|
def change_speed() -> None:
|
||||||
global fps
|
global fps
|
||||||
if fps == 5: fps = 10
|
if fps == 5:
|
||||||
elif fps == 10: fps = 15
|
fps = 10
|
||||||
elif fps == 15: fps = 5
|
elif fps == 10:
|
||||||
|
fps = 15
|
||||||
|
elif fps == 15:
|
||||||
|
fps = 5
|
||||||
|
|
||||||
|
|
||||||
def switch_multiplayer() -> None:
|
def switch_multiplayer() -> None:
|
||||||
|
|||||||
15
pygame/snake/source/snake.py
Executable file → Normal file
15
pygame/snake/source/snake.py
Executable file → Normal file
@ -28,8 +28,10 @@ def draw_grid() -> None:
|
|||||||
|
|
||||||
def draw_score(snakes) -> None:
|
def draw_score(snakes) -> None:
|
||||||
for index, snake in enumerate(snakes):
|
for index, snake in enumerate(snakes):
|
||||||
score_label = set_font(40).render(f"Score {len(snake.body) - 1}", 1, snake.color)
|
score_label = set_font(40).render(
|
||||||
WINDOW.blit(score_label, (10 + (index * (WIDTH - score_label.get_width() - 20)), (WINDOW_HEIGHT - score_label.get_height())))
|
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:
|
def collision_check(snakes, snack) -> None:
|
||||||
@ -53,11 +55,13 @@ def main() -> None:
|
|||||||
|
|
||||||
clock = pygame.time.Clock()
|
clock = pygame.time.Clock()
|
||||||
from assets.scripts.menu import user_name, color_index
|
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)
|
snake_one = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)),
|
||||||
|
COLORS[color_index[0]], user_name[0], 1, multiplayer)
|
||||||
snakes.append(snake_one)
|
snakes.append(snake_one)
|
||||||
|
|
||||||
if multiplayer:
|
if multiplayer:
|
||||||
snake_two = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)), COLORS[color_index[1]], user_name[1], 2, 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)
|
snakes.append(snake_two)
|
||||||
apple = Snack(APPLE_TEXTURE)
|
apple = Snack(APPLE_TEXTURE)
|
||||||
collision_check(snakes, apple)
|
collision_check(snakes, apple)
|
||||||
@ -74,7 +78,8 @@ def main() -> None:
|
|||||||
poison.draw_snack()
|
poison.draw_snack()
|
||||||
if walls:
|
if walls:
|
||||||
for i in range(ROWS):
|
for i in range(ROWS):
|
||||||
COBBLE_RECT = pygame.Rect(i * CELL_SIZE, HEIGHT, WIDTH, CELL_SIZE)
|
COBBLE_RECT = pygame.Rect(
|
||||||
|
i * CELL_SIZE, HEIGHT, WIDTH, CELL_SIZE)
|
||||||
WINDOW.blit(COBBLESTONE_TEXTURE, COBBLE_RECT)
|
WINDOW.blit(COBBLESTONE_TEXTURE, COBBLE_RECT)
|
||||||
pygame.display.update()
|
pygame.display.update()
|
||||||
|
|
||||||
|
|||||||
@ -20,17 +20,23 @@ FONT = join(BASE_PATH, "fonts", "space_invaders.ttf")
|
|||||||
|
|
||||||
# load sprites
|
# load sprites
|
||||||
SPACESHIP = pygame.image.load(join(SPRITE_PATH, "playership.png")) # player
|
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
|
# enemies
|
||||||
ENEMY_1 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_magenta.png")), (40, 35))
|
ENEMY_1 = pygame.transform.scale(pygame.image.load(
|
||||||
ENEMY_2 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_cyan.png")), (40, 35))
|
join(ENEMY_PATH, "enemy_magenta.png")), (40, 35))
|
||||||
ENEMY_3 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_lime.png")), (40, 35))
|
ENEMY_2 = pygame.transform.scale(pygame.image.load(
|
||||||
ENEMY_MISSILE = pygame.image.load(join(SPRITE_PATH, "missiles", "enemymissile.png")) # enemy missile
|
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)
|
pygame.display.set_icon(ENEMY_3)
|
||||||
# background
|
# 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)
|
# colors (R, G, B)
|
||||||
BLUE = (16, 16, 69)
|
BLUE = (16, 16, 69)
|
||||||
@ -94,7 +100,8 @@ class Ship:
|
|||||||
|
|
||||||
def shoot(self) -> None:
|
def shoot(self) -> None:
|
||||||
if self.cooldown_counter == 0:
|
if self.cooldown_counter == 0:
|
||||||
missile = Missile(self.x + self.get_width() / 2 - 5 / 2, self.y, self.missile_img) # missile spawn with offset
|
missile = Missile(self.x + self.get_width() / 2 - 5 / 2,
|
||||||
|
self.y, self.missile_img) # missile spawn with offset
|
||||||
self.missiles.append(missile)
|
self.missiles.append(missile)
|
||||||
self.cooldown_counter = 1
|
self.cooldown_counter = 1
|
||||||
|
|
||||||
@ -194,7 +201,8 @@ def main() -> None:
|
|||||||
|
|
||||||
if lost:
|
if lost:
|
||||||
lost_label = set_font(60).render("You lost!", 1, RED)
|
lost_label = set_font(60).render("You lost!", 1, RED)
|
||||||
WINDOW.blit(lost_label, (WIDTH / 2 - lost_label.get_width() / 2, 350))
|
WINDOW.blit(lost_label, (WIDTH / 2 -
|
||||||
|
lost_label.get_width() / 2, 350))
|
||||||
|
|
||||||
pygame.display.update()
|
pygame.display.update()
|
||||||
|
|
||||||
@ -272,8 +280,12 @@ def main() -> None:
|
|||||||
|
|
||||||
|
|
||||||
# lambda functions
|
# lambda functions
|
||||||
set_font = lambda size, font=FONT: pygame.font.Font(font, size) # sets font size
|
def set_font(size, font=FONT): return pygame.font.Font(
|
||||||
collide = lambda obj1, obj2: obj1.mask.overlap(obj2.mask, (obj2.x - obj1.x, obj2.y - obj1.y)) != None # checks if 2 objs collide/overlap
|
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:
|
def move(vel_x: int, vel_y: int, enemies: list) -> None:
|
||||||
@ -284,8 +296,10 @@ def move(vel_x: int, vel_y: int, enemies: list) -> None:
|
|||||||
def main_menu() -> None:
|
def main_menu() -> None:
|
||||||
while True:
|
while True:
|
||||||
WINDOW.blit(BACKGROUND, (0, 0))
|
WINDOW.blit(BACKGROUND, (0, 0))
|
||||||
title_label = set_font(50).render("Press any key to start...", 1, WHITE)
|
title_label = set_font(50).render(
|
||||||
WINDOW.blit(title_label, (WIDTH / 2 - title_label.get_width() / 2, HEIGHT / 2 - title_label.get_height() / 2))
|
"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()
|
pygame.display.update()
|
||||||
for event in pygame.event.get():
|
for event in pygame.event.get():
|
||||||
if event.type == pygame.QUIT:
|
if event.type == pygame.QUIT:
|
||||||
|
|||||||
@ -1,29 +1,29 @@
|
|||||||
beautifulsoup4==4.10.0
|
beautifulsoup4==4.11.1
|
||||||
bs4==0.0.1
|
bs4==0.0.1
|
||||||
certifi==2021.10.8
|
certifi==2022.6.15
|
||||||
charset-normalizer==2.0.12
|
charset-normalizer==2.1.0
|
||||||
click==8.1.2
|
click==8.1.3
|
||||||
cycler==0.11.0
|
cycler==0.11.0
|
||||||
defusedxml==0.7.1
|
defusedxml==0.7.1
|
||||||
et-xmlfile==1.1.0
|
et-xmlfile==1.1.0
|
||||||
fonttools==4.31.2
|
fonttools==4.34.4
|
||||||
fpdf2==2.5.1
|
fpdf2==2.5.5
|
||||||
idna==3.3
|
idna==3.3
|
||||||
kiwisolver==1.4.2
|
kiwisolver==1.4.4
|
||||||
matplotlib==3.5.1
|
matplotlib==3.5.2
|
||||||
numpy==1.22.3
|
numpy==1.23.1
|
||||||
openpyxl==3.0.9
|
openpyxl==3.0.10
|
||||||
packaging==21.3
|
packaging==21.3
|
||||||
pandas==1.4.2
|
pandas==1.4.3
|
||||||
Pillow==9.1.0
|
Pillow==9.2.0
|
||||||
pyparsing==3.0.7
|
pyparsing==3.0.9
|
||||||
python-dateutil==2.8.2
|
python-dateutil==2.8.2
|
||||||
pytz==2022.1
|
pytz==2022.1
|
||||||
requests==2.27.1
|
requests==2.28.1
|
||||||
scipy==1.8.0
|
scipy==1.9.0
|
||||||
seaborn==0.11.2
|
seaborn==0.11.2
|
||||||
six==1.16.0
|
six==1.16.0
|
||||||
soupsieve==2.3.1
|
soupsieve==2.3.2.post1
|
||||||
urllib3==1.26.9
|
urllib3==1.26.11
|
||||||
word2number==1.1
|
word2number==1.1
|
||||||
yapf==0.32.0
|
yapf==0.32.0
|
||||||
|
|||||||
@ -20,16 +20,22 @@ def trains():
|
|||||||
distance_riga_valka = 164 # from Riga to Valka (red train)
|
distance_riga_valka = 164 # from Riga to Valka (red train)
|
||||||
|
|
||||||
def blue_green_train():
|
def blue_green_train():
|
||||||
blue_train_already_driven_distance = blue_train_speed * blue_train_time_driven # blue train driven distance in 10 min
|
blue_train_already_driven_distance = blue_train_speed * \
|
||||||
meeting_time = (distance_riga_jelgava - blue_train_already_driven_distance) / (blue_train_speed + green_train_speed) # time after which the two trains meet
|
blue_train_time_driven # blue train driven distance in 10 min
|
||||||
green_train_distance = meeting_time * green_train_speed # distance green train has driven
|
meeting_time = (distance_riga_jelgava - blue_train_already_driven_distance) / (
|
||||||
meeting_distance = distance_riga_jelgava - green_train_distance # distance from meeting point to Riga
|
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():
|
def red_train():
|
||||||
red_train_distance_driven = red_train_time_driven * red_train_speed # red train driven distance in given time
|
red_train_distance_driven = red_train_time_driven * \
|
||||||
print(f"Sarkanais vilciens ir nobraucis {round(red_train_distance_driven, 2)}km.")
|
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:
|
if red_train_distance_driven > distance_riga_valka:
|
||||||
return "Sarkanais vilciens ir pabraucis garām Rīgai."
|
return "Sarkanais vilciens ir pabraucis garām Rīgai."
|
||||||
|
|
||||||
@ -44,14 +50,17 @@ def farm():
|
|||||||
wool_total_price = sheep_amount * sheep_price # price for all sheep wool
|
wool_total_price = sheep_amount * sheep_price # price for all sheep wool
|
||||||
|
|
||||||
additional_sheep = 120 # additional sheep
|
additional_sheep = 120 # additional sheep
|
||||||
new_sheep_amount = sheep_amount + additional_sheep # sum of original and added sheep
|
# sum of original and added sheep
|
||||||
new_wool_total_price = new_sheep_amount * wool_total_price # price for original and added sheep wool
|
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_amount = 15 # amount of ostrich in farm
|
||||||
ostrich_egg_price = 30 # price per egg
|
ostrich_egg_price = 30 # price per egg
|
||||||
ostrich_time = 2 # time required to get one ostrich egg
|
ostrich_time = 2 # time required to get one ostrich egg
|
||||||
days = 30 # the time when ostriches lay eggs
|
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_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:
|
if wool_total_price >= ostrich_egg_total_price:
|
||||||
return "Iegūtās naudas pietiks, lai nopirktu visas mēneša olas."
|
return "Iegūtās naudas pietiks, lai nopirktu visas mēneša olas."
|
||||||
|
|||||||
@ -6,11 +6,13 @@ class SalaryBonus():
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.percent = .15 # percent
|
self.percent = .15 # percent
|
||||||
self.salary = float(input("Mēneša algas apjoms: ")) # salary per month
|
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
|
# number of years worked
|
||||||
|
self.time_worked = int(input("Nostrādātais gadu skaits: "))
|
||||||
|
|
||||||
def _calculate_bonus(self):
|
def _calculate_bonus(self):
|
||||||
if self.time_worked > 2: # if worked for more than 2 years
|
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
|
salary_bonus = self.percent * self.salary * \
|
||||||
|
(self.time_worked - 2) # calculates salary bonus
|
||||||
return f"Algas bonuss ir {round(salary_bonus, 2)}€"
|
return f"Algas bonuss ir {round(salary_bonus, 2)}€"
|
||||||
else:
|
else:
|
||||||
return "Algas bonuss nepienākas."
|
return "Algas bonuss nepienākas."
|
||||||
|
|||||||
@ -21,14 +21,16 @@ def is_prime(number):
|
|||||||
class Cities:
|
class Cities:
|
||||||
def __init__(self, p0, perc, delta, p):
|
def __init__(self, p0, perc, delta, p):
|
||||||
self.p0 = p0 # initial population
|
self.p0 = p0 # initial population
|
||||||
self.perc = float(perc[:-1]) / 100 # annual percentage population growth
|
# annual percentage population growth
|
||||||
|
self.perc = float(perc[:-1]) / 100
|
||||||
self.delta = delta # number of arrivals (departures) per year
|
self.delta = delta # number of arrivals (departures) per year
|
||||||
self.p = p # population size required
|
self.p = p # population size required
|
||||||
|
|
||||||
def _calculate(self):
|
def _calculate(self):
|
||||||
years = 0
|
years = 0
|
||||||
while (True):
|
while (True):
|
||||||
self.p0 = self.p0 + self.p0 * self.perc + self.delta # calculate the new population in each year via the formula
|
# calculate the new population in each year via the formula
|
||||||
|
self.p0 = self.p0 + self.p0 * self.perc + self.delta
|
||||||
years += 1
|
years += 1
|
||||||
if self.p0 >= self.p: # if the initial population reaches the required
|
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"
|
return f"{self.p} iedzīvotāju skaits tiks sasniegts pēc {years} gadiem"
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user