<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hans Bonnie on Medium]]></title>
        <description><![CDATA[Stories by Hans Bonnie on Medium]]></description>
        <link>https://medium.com/@hans-bonnie?source=rss-4abef243a4f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EAa_JMpGPwRy95bJ.jpg</url>
            <title>Stories by Hans Bonnie on Medium</title>
            <link>https://medium.com/@hans-bonnie?source=rss-4abef243a4f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:41:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hans-bonnie/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Playlist for Your Life]]></title>
            <link>https://hans-bonnie.medium.com/playlist-for-your-life-b97cfc42ff62?source=rss-4abef243a4f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b97cfc42ff62</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[spotify-playlist]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Hans Bonnie]]></dc:creator>
            <pubDate>Tue, 28 May 2024 14:03:18 GMT</pubDate>
            <atom:updated>2024-05-28T14:03:18.450Z</atom:updated>
            <content:encoded><![CDATA[<p>In the era of digital streaming, music recommendation systems have become an essential part of our listening experience. These systems leverage sophisticated algorithms and data analysis techniques to suggest songs that resonate with our tastes and preferences. This article explores the development of a music recommendation system using Python and machine learning, focusing on text preprocessing, tokenization, and similarity measurement.</p><p>The foundation of any recommendation system is the dataset. For this project, we used the “spotify_millsongdata.csv” dataset, which contains detailed information about various songs, including their lyrics, titles, and other metadata. The initial steps involve loading this dataset and performing some basic exploratory data analysis (EDA) to understand its structure and content.</p><pre>import pandas as pd<br>import nltk<br>from nltk.stem.porter import PorterStemmer<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.metrics.pairwise import cosine_similarity<br><br>music_data = pd.read_csv(&quot;spotify_millsongdata.csv&quot;)<br><br>display(music_data.head())<br>display(music_data.tail())<br>display(music_data.shape)<br>display(music_data.isna().sum())</pre><p>This snippet reads the dataset and displays its first and last few records, along with its dimensions and missing values. EDA helps us identify any anomalies or missing data that might need handling before we proceed further.</p><p>Given the large size of the dataset, we sample 20,000 records for our analysis to ensure computational efficiency. Additionally, we drop any unnecessary columns, such as links to the songs, which do not contribute to our recommendation logic.</p><pre>music_data =music_data.sample(20000).drop(&#39;link&#39;, axis=1).reset_index(drop=True)</pre><p>Next, we focus on text preprocessing. Lyrics, stored in the ‘text’ column, need to be cleaned and standardized. This involves converting all text to lowercase and removing unwanted characters like newline characters.</p><pre>music_data[&#39;text&#39;] = music_data[&#39;text&#39;].str.lower().replace(r&#39;^\w\s&#39;, &#39; &#39;).replace(r&#39;\n&#39;, &#39; &#39;, regex = True)</pre><p>Tokenization is the process of splitting text into individual words or tokens. Following tokenization, we apply stemming to reduce words to their root form. This reduces the complexity of the text data and enhances the performance of our model.</p><pre>stemmer = PorterStemmer()<br><br>def tokenization(txt):<br>    tokens = nltk.word_tokenize(txt)<br>    stemming = [stemmer.stem(w) for w in tokens]<br>    return &quot; &quot;.join(stemming)<br><br>music_data[&#39;text&#39;] = music_data[&#39;text&#39;].apply(lambda x: tokenization(x))</pre><p>Here, we define a function tokenization that tokenizes and stems each song’s lyrics, then apply this function to the entire ‘text’ column.</p><p>To measure the similarity between songs, we transform the cleaned lyrics into a numerical format using the Term Frequency-Inverse Document Frequency (TF-IDF) vectorizer. This technique evaluates how important a word is to a document in a collection of documents, providing a more meaningful numerical representation of the lyrics.</p><pre>tfidvector = TfidfVectorizer(analyzer=&#39;word&#39;,stop_words=&#39;english&#39;)<br>matrix = tfidvector.fit_transform(music_data[&#39;text&#39;])<br>similarity = cosine_similarity(matrix)</pre><p>The core of our recommendation system is a function that, given a song, finds and returns a list of similar songs based on the cosine similarity scores.</p><pre>def recommendation(song_df):<br>    idx = music_data[music_data[&#39;song&#39;] == song_df].index[0]<br>    distances = sorted(list(enumerate(similarity[idx])),reverse=True,key=lambda x:x[1])<br>    <br>    songs = []<br>    for m_id in distances[1:21]:<br>        songs.append(music_data.iloc[m_id[0]].song)<br>        <br>    return songs</pre><p>This function first identifies the index of the given song in the dataset. It then sorts all other songs based on their similarity to the given song, excluding the song itself, and returns the top 20 most similar songs.</p><p>To ensure our recommendation system can be used in the future without the need to recompute the similarity matrix, we save both the similarity matrix and the cleaned dataset using the pickle module.</p><pre>import pickle<br>pickle.dump(similarity,open(&#39;rec_spotify.pkl&#39;,&#39;wb&#39;))<br>pickle.dump(music_data,open(&#39;music_data.pkl&#39;,&#39;wb&#39;))</pre><p>After we save the model then we are deploying a music recommendation system allows users to receive personalized song suggestions based on their favorite tracks. Here’s how you can deploy such a system using Streamlit and the Spotify API.</p><p>First, import necessary libraries and initialize the Spotify client with your credentials.</p><pre>import pickle<br>import streamlit as st<br>import spotipy<br>from spotipy.oauth2 import SpotifyClientCredentials<br><br>CLIENT_ID = &quot;your_client_id&quot;<br>CLIENT_SECRET = &quot;your_client_secret&quot;<br><br>client_credentials_manager = SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)<br>sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)</pre><p>Define functions to get album cover URLs and recommend songs.</p><pre>def get_song_album_cover_url(https://medium.com/song_name,%20artist_name):<br>    search_query = f&quot;track:{song_name} artist:{artist_name}&quot;<br>    results = sp.search(q=search_query, type=&quot;track&quot;)<br>    if results[&quot;tracks&quot;][&quot;items&quot;]:<br>        return results[&quot;tracks&quot;][&quot;items&quot;][0][&quot;album&quot;][&quot;images&quot;][0][&quot;url&quot;]<br>    return &quot;https://i.postimg.cc/0QNxYz4V/social.png&quot;<br><br>def recommend(song):<br>    index = music[music[&#39;song&#39;] == song].index[0]<br>    distances = sorted(list(enumerate(similarity[index])), reverse=True, key=lambda x: x[1])<br>    recommended_music_names = [music.iloc[i[0]].song for i in distances[1:11]]<br>    recommended_music_posters = [get_song_album_cover_url(https://medium.com/music.iloc[i[0]].song,%20music.iloc[i[0]].artist) for i in distances[1:11]]<br>    return recommended_music_names, recommended_music_posters</pre><p>Design the UI using Streamlit.</p><pre>st.markdown(&#39;&lt;div class=&quot;header&quot;&gt;&lt;img src=&quot;https://storage.googleapis.com/pr-newsroom-wp/1/2018/11/Spotify_Logo_CMYK_Green.png&quot; width=&quot;200&quot; alt=&quot;Spotify Logo&quot;&gt;&lt;h1 class=&quot;title&quot;&gt;🎵 Playlist for Yours 🎵&lt;/h1&gt;&lt;/div&gt;&#39;, unsafe_allow_html=True)<br>st.markdown(&quot;Bosen dengan lagu yang itu-itu aja? Coba pilih satu lagu yang kamu suka dan kami akan urus sisanya.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nO9Kb9WgAqOnt2V8MV7Xqw.png" /></figure><p>Load the pre-trained model and dataset, and create the recommendation system.</p><pre>music = pickle.load(open(&#39;music_data.pkl&#39;, &#39;rb&#39;))<br>similarity = pickle.load(open(&#39;rec_spotify.pkl&#39;, &#39;rb&#39;))<br><br>music_list = music[&#39;song&#39;].values<br>selected_song = st.selectbox(&quot;Type or select a song from the dropdown&quot;, music_list)<br><br>if st.button(&#39;Show Recommendation&#39;):<br>    try:<br>        recommended_music_names, recommended_music_posters = recommend(selected_song)<br>        st.markdown(&#39;&lt;div class=&quot;recommendations&quot;&gt;&#39;, unsafe_allow_html=True)<br>        for name, poster in zip(recommended_music_names, recommended_music_posters):<br>            st.markdown(f&#39;&#39;&#39;<br>                &lt;div class=&quot;recommendation&quot;&gt;<br>                    &lt;img src=&quot;{poster}&quot; width=&quot;100%&quot;&gt;<br>                    &lt;p style=&#39;color:#1DB954;&#39;&gt;{name}&lt;/p&gt;<br>                &lt;/div&gt;<br>            &#39;&#39;&#39;, unsafe_allow_html=True)<br>        st.markdown(&#39;&lt;/div&gt;&#39;, unsafe_allow_html=True)<br>    except Exception as e:<br>        st.error(f&quot;An error occurred: {e}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nu60Gd1OyUJ7Gt44KG9DDA.png" /><figcaption>Example of showing recommended song</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b97cfc42ff62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Becoming a Swiftie : Good Strategy or Tragedy]]></title>
            <link>https://hans-bonnie.medium.com/becoming-a-swiftie-good-strategy-or-tragedy-39ca68520126?source=rss-4abef243a4f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ca68520126</guid>
            <category><![CDATA[taylor-swift]]></category>
            <category><![CDATA[concerts]]></category>
            <category><![CDATA[eras-tour]]></category>
            <category><![CDATA[swiftonomics]]></category>
            <dc:creator><![CDATA[Hans Bonnie]]></dc:creator>
            <pubDate>Fri, 03 May 2024 15:26:43 GMT</pubDate>
            <atom:updated>2024-05-03T15:26:43.111Z</atom:updated>
            <content:encoded><![CDATA[<h3>Becoming a Swiftie : Good Strategy or Tragedy</h3><p>Taylor Swift, born on December 13, 1989, in West Reading, Pennsylvania, USA, is more than just a singer-songwriter; she’s a global sensation. With her heartfelt lyrics and catchy melodies, Swift has solidified herself as one of the most influential artists in contemporary music. Her superstar status is underscored by her impressive Spotify following, ranking as the third most-followed artist and the second most-listened-to artist monthly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*CpCN1n0FSkwyUxUWGeVb6w.png" /><figcaption>Worldwide most streamed artist monthly</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*IZ2oZP2tPfw5FIHgjOVZvw.png" /><figcaption>Most Follower Artist in Spotify</figcaption></figure><p>But Swift’s influence extends far beyond streaming numbers. In 2024, she made history by clinching the Grammy Award for Album of the Year for “Midnights” (2022), marking her fourth win in this prestigious category.</p><p>Beyond her musical accolades, Swift boasts an exceptional track record in concert revenue. Her “Eras Tour” stands as the highest-grossing concert tour of all time, raking in over $1 billion from “The Eras Tour” alone and a staggering $3 billion from all her concerts combined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*kdUqbKnRIEpuwTqyY8D-yA.png" /><figcaption>Taylor Swift Gross Income from Every Concert</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rmKNVUbcGEJCb1SfNPIOPg.png" /><figcaption>Top 10 concerts with the highest all-time earnings</figcaption></figure><p>This economic impact isn’t just beneficial for the megastar herself; it’s a boon for the entire nation. The “Eras Tour” played a crucial role in revitalizing the American economy, contributing an estimated $4.1 billion in revenue, according to Peter Cohan, an associate professor at Babson College.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*AqY8GMdWN_PkgPZHeX5SdQ.png" /></figure><p>When you tally up the figures, the U.S. tour alone injected a $5.7 billion boost into the economy. To put that into perspective, it surpasses the GDP of 39 countries.</p><p>This surge in spending has breathed new life into the entertainment industry after years of pandemic-induced slumps. According to Chris Leyden, director of growth marketing at SeatGeek, Swift and her “Eras” tour have reshaped entertainment economics.</p><p>Hotel analytics group STR calculated tour cities produced a $208 million bump in hotel room revenue, over and above normal seasonal. In Seattle, Swift set a record for single-day revenue for downtown hotels — notching $7.4 million, about $2 million more than the record set during a Major League Baseball All-Star Game earlier the same month, according to Visit Seattle and STR.</p><p>The impact of Swift’s tour extends globally, leading to the emergence of what’s now termed “Swiftonomics.” Heads of state, like Singapore’s PM Lee Hsien Loong, have taken notice. PM Lee even personally lobbied Swift to extend her concert in Singapore from three days to six, making Singapore the sole Southeast Asian destination for her tour.</p><p>And the results speak for themselves. Swift’s concert injected an additional S$300 million (US$225 million ) to S$400 million into Singapore’s economy, bumping up the country’s economic growth from an initial estimate of 2.3% to 2.5%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*KwR0BZyPLtf8ZGRNX1XihQ.png" /><figcaption>Hotel Occupancy in Singapore (Feb-Mar 2024)</figcaption></figure><p>From this graph, it can be clearly seen that there is a significant increase in occupancy, from a usual day of only 57% to 83% during the concert. This occurs uniformly across all hotels in Singapore, evident from the number of hotels that are unavailable or fully booked during the concert.</p><p>In addition to the increase in occupancy, hotels also raised their room rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*WkKSxCCQqxdaktFqMMJY3w.png" /><figcaption>Hotel Room Rate in Singapore (Feb-Mar 2024)</figcaption></figure><p>It can be observed that hotels raised their room rates ranging from 14% to peaking at 63% on the day before the concert (h-1).</p><p>The impact isn’t limited to Singapore; it’s felt across the Asia-Pacific region. From Melbourne to Tokyo, Swift’s concerts lead to significant spikes in hotel occupancy and room rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*FW1co_1Bbq5KbtdCD1G1Qw.png" /><figcaption>Hotel Occupancy (Feb-Mar 2024)</figcaption></figure><p>There is a noticeable increase in occupancy, and upon closer examination, it is evident that there is also a considerable rise in prices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*jone62rJdo-SdzDqDXcvRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*fQdtjZ5p0NwY1-LfJ87wHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*9eHLCBY63fpcG9tM2r8Z7A.png" /></figure><p>This phenomenon isn’t lost on leaders like Indonesia’s President Jokowi, who has set ambitious goals through the “Indonesia Emas 2045” program. By leveraging the “Swiftonomics” phenomenon, countries can harness the economic benefits brought about by one extraordinary performer.</p><p>In conclusion, Taylor Swift isn’t just a music icon; she’s a force driving economic growth and reshaping the entertainment industry on a global scale.</p><p>And if you’d like to see more detailed visualizations, you can access them through this link : <a href="https://public.tableau.com/app/profile/hans.bonnie/viz/Swiftonomics/Dashboard2?publish=yes">https://public.tableau.com/app/profile/hans.bonnie/viz/Swiftonomics/Dashboard2?publish=yes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39ca68520126" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ENCRYPTED TEXT]]></title>
            <link>https://hans-bonnie.medium.com/encrypted-text-fb453f8bae38?source=rss-4abef243a4f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb453f8bae38</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[caesar-cipher]]></category>
            <category><![CDATA[alan-turing]]></category>
            <category><![CDATA[enigma]]></category>
            <dc:creator><![CDATA[Hans Bonnie]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 14:02:23 GMT</pubDate>
            <atom:updated>2024-03-15T14:02:23.419Z</atom:updated>
            <content:encoded><![CDATA[<p>In this day and age, we are certainly familiar with “This Message has been Encrypted,” starting from WhatsApp, Telegram, iMessage, and other applications that already utilize encryption features. The widespread use of encryption serves to maintain the confidentiality of messages and other user information, preventing unauthorized access by third parties.</p><p>Indeed, encryption is not something new. Encryption was first used between 100 BC and 44 BC. The method of encryption was first utilized by Julius Caesar, a Roman general and leader in the 1st century BC, and the method was named Caesar Cipher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*-RjjKY7-FB7CKiW85zIY6g.png" /><figcaption>The analogy of how the Caesar cipher works</figcaption></figure><p>History records its use during wars and secret communication between Caesar and his generals. No wonder they could win war after war because no one could understand the communication and instructions from Julius Caesar except his generals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*NvAuJtHJQeYYxr6Xtcd0_Q.png" /><figcaption>Julius Caesar during the Roman war.</figcaption></figure><p>In modern times, there’s also a figure who became a milestone in computer science and encryption. He was a brilliant mathematician, logician, cryptographer, and a key figure in the Allies’ success in winning World War II. Documentary enthusiasts surely know who this figure is. Yes, indeed, Alan Turing, who gained widespread recognition after the film “The Imitation Game” (2014), was a genius mathematician born in England who successfully decrypted the code from the Nazi Enigma using the “Bombe”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*fmvnYT2MzxyKsssAMulKJw.png" /></figure><p>But what exactly is encryption? Encryption is a method of locking data so that only those with specific keys can unlock it.</p><p>There are many types of encryption used in the world of cryptography, each with different strengths and weaknesses. Here are some common types of encryption:</p><p>1. Symmetric Encryption</p><p>A type of encryption where users use the same key to encrypt and decrypt data. This method is fast and efficient but requires a secure method of sharing keys.</p><p>2. Asymmetric Encryption</p><p>A type of encryption where users use a pair of different keys: a public key for encryption and a private key for decryption. This allows for secure message exchange without needing to share secret keys.</p><p>3. Hash Functions (Fungsi Hash)</p><p>A method that produces a hash value (often in a fixed format) from input data. It cannot be decrypted; it can only be used to verify data integrity.</p><p>4. Stream Ciphers</p><p>A type of encryption where each bit of the original text is encrypted separately using a key stream. This is useful for encrypting continuous data, such as real-time communication.</p><p>5. Block Ciphers</p><p>A method that encrypts data blocks of a specific size (e.g., 64-bit or 128-bit). The same data block will be encrypted into different blocks depending on the key used.</p><p>With the vast journey of encryption development, encryption systems have now reached an incredibly advanced stage. However, before we delve into the latest encryption technologies, we can try to learn from the simplest concepts of cryptography.</p><pre>kalimat = &quot;IT  TSJ  YMNSL  JAJWD  IFD  YMFY  XHFWJX  DTZ&quot;</pre><p>This sentence might look like a sentence from an alien trying to attack Earth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*c3ugTpBAUEHBquo3_2U26g.png" /><figcaption>The result of decryption</figcaption></figure><p>This sentence might actually be seen as a rallying cry, inspiring unity and determination among its readers!</p><p>Then, how can we achieve such results?</p><p>First, we need to understand that the original sentence is a sentence where each letter is shifted several times. It would certainly take a long time if we were to manually sort each letter that has been shifted, but a program can do it in seconds.</p><p>The basis of creating this program lies in the methods of Looping and Conditional Statements (if-else statements). Let’s dissect each one:</p><p>- Looping Method</p><p>The Looping method is a process where the program will repeatedly perform the same task based on certain conditions.</p><p>There are 2 common types of loops known in the Python programming language, namely:</p><p>1. While Loop</p><p>2. For Loop</p><p>- Conditional Statement</p><p>Conditional Statement is a logical construct that allows the program to make decisions based on certain conditions. The functions present in this method are: ‘if’, ‘elif’, and ‘else’.</p><p>For example:</p><pre>x = 10<br>if x&gt;5 :<br>  print(&#39;Nilai x lebih besar dari 5&#39;)<br>else :<br>  print(&#39;Nilai x lebih kecil dari 5&#39;)</pre><p>In the example provided, we know that the value of ‘x’ is 10. Then, we give the statement ‘IF x&gt;5’ (if the value is greater than 5), it will display the message “The value of x is greater than 5”. But if the IF statement is false or evaluates to False (ELSE), it will display the message “The value of x is not greater than 5”. Based on this condition, the message displayed will be “The value of x is greater than 5”.</p><p>After understanding the basic concepts of Looping and Conditional Statement methods, now we will try to apply both methods to decrypt the alien sentence mentioned at the beginning of this article.</p><pre>Alfabet = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;</pre><p>In this program, we will use the common Alphabet pattern (A-Z) as the basis for the program to translate the sentence later on.</p><pre>def hitung_frekuensi (text):<br>    frekuensi = {}<br>    total = 0<br><br>    for char in text:<br>        if char.isalpha():<br>            if char in frekuensi :<br>                frekuensi[char]+=1<br>            else :<br>                frekuensi[char]=1<br>            total += 1<br>    for char in frekuensi:<br>        frekuensi[char]/=total<br>    return frekuensi</pre><p>First, we need to prepare the “<strong>hitung_frekuensi</strong>” function to count the frequency of occurrences from the sentence to be translated. We create several initial variables to ensure the counting runs smoothly:</p><p>- “<strong>frekeunsi</strong>” with an empty dictionary (“{ }”) that will be used to store the frequency of each character.</p><p>- “<strong>total</strong>” which will later count the total number of alphabets from the sentence to be translated.</p><p>Then, we perform a For-Loop and Conditional Statement:</p><p>For-Loop :</p><p>“<strong>for char in text</strong>” = In this first loop, we want to iterate over each character (“char”) in the input sentence.</p><p>Conditional Statement :</p><p>“<strong>if char</strong>.<strong>isalpha()</strong>” = We want to impose the condition that only alphabetic characters are considered from the separated characters of the sentence.</p><p>If the “IF” condition is true, it will execute the second condition, which is:</p><p>“<strong>if char in frekuensi</strong>” = If the character is already present in the “frequency” variable, then it will increment the frequency count of that character by 1.</p><p>“<strong>else</strong>” = But if the character is not yet present in the “frequency” variable, then it will create the character with a frequency of 1 in the “frequency” dictionary.</p><p>For-loop :</p><p>“<strong>for char in frekuensi</strong>” = For each character that already exists in the “frekuensi”, we will find the frequency of each letter by dividing the “frekuensi” by the “total”</p><p>From the obtained frequencies, we can match them with the frequency of letter occurrences in each language as long as there are publications related to the frequency of letter occurrences in that language. In this program, the decryption process can only be done in English because there are publications from credible institutions. The frequency used in this program is sourced from the Corpus of Contemporary American English (COCA).</p><pre>frekuensi_bahasa_inggris = {<br>    &#39;A&#39;: 0.08167, &#39;B&#39;: 0.01492, &#39;C&#39;: 0.02782, &#39;D&#39;: 0.04253, &#39;E&#39;: 0.12702,<br>    &#39;F&#39;: 0.02228, &#39;G&#39;: 0.02015, &#39;H&#39;: 0.06094, &#39;I&#39;: 0.06966, &#39;J&#39;: 0.00153,<br>    &#39;K&#39;: 0.00772, &#39;L&#39;: 0.04025, &#39;M&#39;: 0.02406, &#39;N&#39;: 0.06749, &#39;O&#39;: 0.07507,<br>    &#39;P&#39;: 0.01929, &#39;Q&#39;: 0.00095, &#39;R&#39;: 0.05987, &#39;S&#39;: 0.06327, &#39;T&#39;: 0.09056,<br>    &#39;U&#39;: 0.02758, &#39;V&#39;: 0.00978, &#39;W&#39;: 0.02360, &#39;X&#39;: 0.00150, &#39;Y&#39;: 0.01974,<br>    &#39;Z&#39;: 0.00074<br>}<br><br>def cocokan_bahasa (frekuensi_kalimat, frekuensi_bahasa):<br>    total_perbedaan = 0<br>    for huruf in Alfabet:<br>        total_perbedaan += abs (frekuensi_kalimat.get(huruf, 0)-frekuensi_bahasa.get(huruf, 0))<br>    return total_perbedaan<br><br>min_perbedaan = float(&#39;inf&#39;)<br>bahasa_terbaik = &#39;&#39;</pre><p>After adding the letter frequencies in English, then we create a function “<strong>cocokan_bahasa</strong>” to match the letter frequencies in the input sentence with the letter frequencies in English.</p><p>We add a variable “<strong>total</strong>” with a value of 0 as a container to store the total difference. We sum the absolute difference between “<strong>frekuensi_kalimat</strong>” and“<strong>frekuensi_bahasa</strong>”, using “<strong>abs()</strong>” function to get the absolute value.</p><p>After determining the function to match letters in the input sentence with letters from English, we create 2 new variables, namely:</p><p>“<strong>min_perbedaan</strong> = float(’inf’)” = is used to initialize the minimum difference with an infinite value.</p><p>“<strong>bahasa_terbaik</strong> = ‘ ‘ = serves as a container to store the decrypted sentence result that we will perform.</p><pre>for geser in range (26):<br>    kalimat_terdekripsi = &#39;&#39;<br>    for char in kalimat.upper() :<br>        if char.isalpha():<br>            index_lama = Alfabet.index(char)<br>            index_baru = (index_lama + geser)%26<br>            kalimat_terdekripsi += Alfabet[index_baru]<br>        else :<br>            kalimat_terdekripsi+= char<br>    <br>    frekuensi_kalimat_terdekripsi = hitung_frekuensi(kalimat_terdekripsi.upper())<br>    perbedaan = cocokan_bahasa(frekuensi_kalimat_terdekripsi, frekuensi_bahasa_inggris)</pre><p>In this section, we will again perform a For-Looping to try all possible shifts within the range of 26, according to the number of alphabets we specified earlier.</p><p><strong>“for char in kalimat</strong>” is a loop for each character in the alien sentence we want to decipher.</p><p>“<strong>if char.isalpha()</strong>” we impose the condition that we will only translate characters that are alphabetic.</p><p>“<strong>else</strong>” For every character that is not a letter (such as numbers or punctuation (- , . , ?)), it will remain displayed as it is.</p><p>If the condition in the IF statement is met, then we will create a new variable called “<strong>index_lama</strong>” to determine the character index of the sentence we will break against the alphabet.</p><p>After successfully identifying the initial index of the letters in the input sentence, we create a new variable “<strong>index_baru</strong>” where we add “<strong>index_lama</strong>” and the shift, which will then be modulus by 26. The use of modulus here is because we want the program to wrap back to the beginning of the alphabet (A) after reaching the last index of the alphabet (Z).</p><p>The variable “<strong>frekuensi_kalimat_terdekripsi</strong>” call the“<strong>hitung_frekuensi</strong>” function to calculate the frequency of the decrypted sentence, and then we add the “<strong>upper()</strong>” function to avoid case sensitivity that could cause program errors.</p><p>The variable “<strong>perbedaan</strong>” also calls the function “<strong>cocokan_bahasa</strong>” to compare the letter frequencies in the decrypted sentence with the letter frequencies in English.</p><pre>if perbedaan&lt;min_perbedaan:<br>        min_perbedaan = perbedaan<br>        bahasa_terbaik = kalimat_terdekripsi</pre><p>After all decryption processes are completed, we perform the final conditional statement still within the “<strong>geser</strong>” loop, namely:</p><p>“<strong>if perbedaan &lt; min_perbedaan</strong>” is the condition we set to compare the difference value with the min_perbedaan value.</p><p>If the result of this condition is True, then we will set the value of “perbedaan” to be the new value of “<strong>min_perbedaan</strong>” and the value of “<strong>kalimat_terdekripsi</strong>” to be the new value of “<strong>bahasa_terbaik</strong>”.</p><p>After ensuring that all writing and syntax are done correctly, we just need to give the command to display the decryption results.</p><pre>print (bahasa_terbaik)</pre><p>and the result is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*c3ugTpBAUEHBquo3_2U26g.png" /><figcaption>The result of decryption</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb453f8bae38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>