<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: ElianeS</title>
    <description>The latest articles on DEV Community by ElianeS (@elianesato).</description>
    <link>https://dev.to/elianesato</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F734509%2F7eb5be2a-ce7c-4f2e-8b59-f3de75566efd.jpeg</url>
      <title>DEV Community: ElianeS</title>
      <link>https://dev.to/elianesato</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/elianesato"/>
    <language>en</language>
    <item>
      <title>Brazilian Social Security Benefits - linear search</title>
      <dc:creator>ElianeS</dc:creator>
      <pubDate>Fri, 03 Jun 2022 12:59:48 +0000</pubDate>
      <link>https://dev.to/elianesato/brazilian-social-security-benefits-linear-search-1f0n</link>
      <guid>https://dev.to/elianesato/brazilian-social-security-benefits-linear-search-1f0n</guid>
      <description>&lt;p&gt;There are a great deal of benefits provided by the Brazilian Social Security Agency. Each of them has its own set of requirements that it's challenging finding out whether one is entitled to it.&lt;br&gt;
Regardless one's knowledge about legal affairs related to this matter, most people in Brazil have a common sense about these benefits. &lt;br&gt;
In order to help to figure out if one has the right to a given benefit, the program, written in Python3, intends to be a straightforward way to learn about its legal requirements.&lt;br&gt;
For instance: if the user wants to learn what the requirements are to get a retirement pension ('aposentadoria' in Portuguese), all that one should do is typing few letters such as "apo".&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--S7iBxEYP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ju6m14snhhwsm6u3hiu2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--S7iBxEYP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ju6m14snhhwsm6u3hiu2.png" alt="Searching retirement pensions" width="880" height="376"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After confirming, the user can see all the eight(!) types of retirement pensions available and criteria that should be met.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1twK5SKT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jesxztzpfppvd4skaaxc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1twK5SKT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jesxztzpfppvd4skaaxc.png" alt="Image description" width="880" height="802"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Hash Map algorithm
&lt;/h2&gt;

&lt;p&gt;I chose a Hash Map data structure to organize the information  about the benefits.&lt;/p&gt;

&lt;p&gt;A map relates two pieces of information where the inputs (called keys) have a single output (called value) only. There can't be more than one value per key.&lt;/p&gt;

&lt;p&gt;In order to keep track of values (=requirements) in memory, an array was created, so each benefit (key) was given an index in the array by using a &lt;em&gt;hashing function&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;First of all, a &lt;code&gt;Hash Map&lt;/code&gt; class&lt;sup id="fnref1"&gt;1&lt;/sup&gt; was created to implement an array. Then, two methods to find out the indices (&lt;code&gt;hash&lt;/code&gt; and &lt;code&gt;compressor&lt;/code&gt;) and another one to assign the key-value pair to an index (&lt;code&gt;assign&lt;/code&gt;) were implemented like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class HashMap:
    def __init__(self, array_size):
        self.array_size = array_size
        self.array = [None for item in range(array_size)]

    def hash(self, key,count_collisions=0):
        key_bytes = key.encode()
        hash_code = sum(key_bytes)
        return hash_code + count_collisions

    def compressor(self, hash_code):
        return hash_code % self.array_size

    def assign(self, key, value):
        array_index = self.compressor(self.hash(key))
        current_array_value = self.array[array_index]
        if current_array_value is None:
            self.array[array_index] = [key, value]
            return
        if current_array_value[0] == key:
            self.array[array_index] = [key, value]
            return
        number_collisions = 1
        while (current_array_value[0] != key):
            new_hash_code = self.hash(key, number_collisions)
            new_array_index = self.compressor(new_hash_code)
            current_array_value = self.array[new_array_index]
            if current_array_value is None:
                self.array[new_array_index] = [key, value]
                return
            if current_array_value[0] == key:
                self.array[new_array_index] = [key, value]
                return

            number_collisions += 1
        return
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Linear Search
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Linear Search&lt;/code&gt;is an algorithm used to locate and retrieve information from a list by scanning every item sequentially. If the target is found, the search stops and returns the position (index) in the list where the target value is located. Otherwise, it returns a message that the target is not in the list.&lt;/p&gt;

&lt;p&gt;Here is the way the algorithm was implemented:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def linear_search(lista):
    matches = []
    data = []
    while True:
        target_chunk = input("  Digite as iniciais do benefício a pesquisar e pressione &amp;lt;enter&amp;gt;. \n  Sua escolha: ")
        for key, value in lista:
            if (target_chunk in key) or (target_chunk in value.values()):
                matches.append(key)
                data.append(value)
        if len(matches) == 0:
            raise ValueError(f"  Nenhum tópico com as letras {target_chunk} foi encontrado.")
        else:
            break

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After the user typed the letters, the program checks whether these letters are part of the benefit's name. If there's a match, the corresponding key is added to a list called &lt;em&gt;matches&lt;/em&gt; whereas its value is appended to another list called &lt;em&gt;data&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The program runs recursively until there's only one type of benefit in the &lt;em&gt;matches&lt;/em&gt; list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; if len(matches) &amp;gt; 1:
        print(f"  Com essas letras, as opções são: {matches}")
        linear_search(lista)
    else:
        print(f"  A opção disponível com essas letras é {matches[0]}. Você quer consultar {matches[0]}?"
              f" Digite 'S' para sim.")
        answer = input("  Sua escolha: ")
        if answer == "S":
            os.system("clear")
            print(f"\n  Estes são os dados do benefício escolhido: {matches[0]}")
            if type(list(data[0].values())[0]) is not str:
                for beneficio, item in data[0].items():
                    print("\n ", beneficio.upper())
                    for dado, valor in item.items():
                        print(f"  - {dado}: {valor}")
            else:
                print("\n ", matches[0].upper())
                for dado, valor in data[0].items():
                    print(f"  - {dado}: {valor}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, the program retrieves the data stored in the &lt;em&gt;data&lt;/em&gt; list where &lt;em&gt;beneficio&lt;/em&gt; is the key and &lt;em&gt;item&lt;/em&gt; is the value.&lt;/p&gt;

&lt;h2&gt;
  
  
  Main
&lt;/h2&gt;

&lt;p&gt;Putting everything together:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def main():
    os.system('clear')
    welcome_message = "Plano de benefícios da Previdência Social"
    print("\n  " + ((len(welcome_message) + 40) * '=') + '\n  ' + (len(welcome_message) + 40) * '=' + "\n")
    print(("  " + " " * 20) + f"{welcome_message:20}")
    print("\n  " + ((len(welcome_message) + 40) * '=') + '\n  ' + (len(welcome_message) + 40) * '=' + "\n")
    try:
        linear_search(plano_HM.array)
    except ValueError as error_message:
        print("{}".format(error_message))
        linear_search(plano_HM.array)
    while True:
        print()
        again = input("  Gostaria de realizar nova pesquisa? Digite 'S' para sim ou qualquer tecla para sair.\n"
                      '  Sua escolha: ')
        if again == "S":
            os.system("clear")
            linear_search(plano_HM.array)
        else:
            print("  Até a próxima!")
            break
    os.system('exit')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Check it out: &lt;a href="https://www.linkedin.com/embed/feed/update/urn:li:ugcPost:6929782563968278528" title="Embedded post"&gt;video&lt;/a&gt;, &lt;a href="https://github.com/ElianeSato/recommendation_program"&gt;GitHub&lt;/a&gt;&lt;/p&gt;




&lt;ol&gt;

&lt;li id="fn1"&gt;
&lt;p&gt;The code was borrowed from Codecademy. ↩&lt;/p&gt;
&lt;/li&gt;

&lt;/ol&gt;

</description>
      <category>python</category>
      <category>hashmap</category>
      <category>linearsearch</category>
      <category>codecademy</category>
    </item>
    <item>
      <title>Mortgage Calculator to help determining financial suitability with Python: an OOP approach</title>
      <dc:creator>ElianeS</dc:creator>
      <pubDate>Sat, 30 Oct 2021 14:07:00 +0000</pubDate>
      <link>https://dev.to/elianesato/mortgage-calculator-to-help-determining-financial-suitability-with-python-an-oop-approach-30b7</link>
      <guid>https://dev.to/elianesato/mortgage-calculator-to-help-determining-financial-suitability-with-python-an-oop-approach-30b7</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;If one is willing to buy a home, land, or other type of real estate without paying the entire price upfront, may have considered borrowing some money from a bank or other institution.&lt;/p&gt;

&lt;p&gt;Mortgage is a type of loan to raise funds to purchase real estate. Sometimes, property's owners may use a mortgage to raise funds as well. The borrower grants the real estate as collateral to ensure that the loan will be paid.&lt;/p&gt;

&lt;p&gt;One of the consequences of defaulting on the mortgage for the borrower is losing the property. On the other hand, the lender must follow a procedure in order to seize and sell the property to recoup the debt.&lt;/p&gt;

&lt;p&gt;That said, it's crucial for lenders and borrowers assessing the financial suitability of the mortgage program beforehand. A potential borrower can check which property's value he or she can afford and test different terms and interest rates. Lenders can check whether a plan is feasible.&lt;/p&gt;

&lt;p&gt;Despite the fact there are several types of mortgage, a loan is satisfied by paying to zero balance over the course of the loan term. Regular payments are divided into principal and interest charged and may include others costs like taxes, fees, and insurance.&lt;/p&gt;

&lt;h2&gt;
  
  
  The program
&lt;/h2&gt;

&lt;p&gt;One way to implement this calculator is by using classes, which allows splitting the program into 'zones' with some code and data in order to create several objects using the same template.&lt;/p&gt;

&lt;p&gt;This is a basic terminal program written with Python that uses fixed-rate mortgage to estimate monthly payments and loan's term, the major variables in a mortgage calculation, along loan's principal and interest rate.&lt;/p&gt;

&lt;p&gt;Off the bat, principal and yearly interest rate are provided by the user and stored as attributes of the class Mortgage, since they remain the same for both monthly amount calculus and term calculus.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Mortgage:
    def __init__(self):
        self.principal = pyip.inputFloat("Type loan's principal: ")
        self.interest_rate = pyip.inputFloat("Type yearly interest rate: ")
        self.interest_rate = self.interest_rate / 100 / 12  # yearly percentage rate divided by 12

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The methods defined inside the class Mortgage are in charge of the calculus involved and will be run according to the user option: calculating monthly payment over a provided yearly term or estimating how long it would take to have the loan paid off in full for a given monthly payment.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; def monthly_amount(self):
        self.yearly_term = pyip.inputInt("Type yearly term: ")
        self.yearly_term *= 12 #number of monthly payments
        payment = ((self.interest_rate * self.principal) / ((1 - ((1 + (self.interest_rate)) ** (-self.yearly_term)))))
        return f'Monthly amount payment for ${self.principal:6.2f} in {self.yearly_term} months: ${payment:6.2f}'

    def term(self):
        self.payment = pyip.inputFloat("Type the monthly amount: $")
        term = 0
        balance = self.principal
        while balance &amp;gt; 0:
            balance = balance + (self.interest_rate * balance) - self.payment
            term += 1
        return f"The loan's principal ${self.principal} would take {term} months to be paid."
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At the end of the script, an instance of the class is created and a menu is prompted:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mortgage = Mortgage()
print("Choose '1' for monthly amount, '2' for loan's term(years), or '3' to exit.")
choice = pyip.inputMenu(choices=['monthly amount', "loan's term", "quit"], numbered=True)
print('Your choice:', choice)
if choice == 'monthly amount':
    print('=' * (len(mes) + 10))
    print(mortgage.monthly_amount())
    print('=' * (len(mes) + 10))
elif choice == "loan's term":
    print('=' * (len(mes) + 10))
    print(mortgage.term())
    print('=' * (len(mes) + 10))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The module pyinputplus, imported at the beginning of the script as pyip, was used for input validation.&lt;/p&gt;

&lt;p&gt;When the script is run in the terminal, the result on the screen will be as such: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--iCWA3QOk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lu9rtvs8hbp3lp4v76cf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--iCWA3QOk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lu9rtvs8hbp3lp4v76cf.png" alt="A terminal screen showing initial message &amp;quot;Welcome to the mortgage calculator&amp;quot; followed by &amp;quot;type loan's principal: 200000&amp;quot;, &amp;quot;type yearly interest rate: 6.5&amp;quot;, &amp;quot;Choose '1'for monthly amount, '2'for loan's term(years), or '3'to exit&amp;quot;. So the menu is provided like so: &amp;quot;Please select one of the following: 1. monthly amount 2. loan's term 3. quit&amp;quot;. Option 1 was selected and the program prints &amp;quot;1 Your choice: monthly amount&amp;quot;. After a line separating the previous content, you can see &amp;quot;Type yearly term: 30&amp;quot;, and the result &amp;quot;Monthly amount payment for $200000.00 in 360 months: $1264.14&amp;quot;. " width="880" height="380"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A link to the code on GitHub:&lt;br&gt;
&lt;a href="https://github.com/ElianeSato/CS_101"&gt;https://github.com/ElianeSato/CS_101&lt;/a&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>codecademy</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
