<?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 Amir Edris on Medium]]></title>
        <description><![CDATA[Stories by Amir Edris on Medium]]></description>
        <link>https://medium.com/@amiredris25?source=rss-ff4ec82091dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4T6zuh93WzqHO7hZkXqxKg.jpeg</url>
            <title>Stories by Amir Edris on Medium</title>
            <link>https://medium.com/@amiredris25?source=rss-ff4ec82091dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:57:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amiredris25/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[List and Dictionary Comprehensions in Python: Tips, Tricks, and Alternatives]]></title>
            <link>https://python.plainenglish.io/list-and-dictionary-comprehensions-in-python-tips-tricks-and-alternatives-2e71ce9b81aa?source=rss-ff4ec82091dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e71ce9b81aa</guid>
            <category><![CDATA[efficient-coding]]></category>
            <category><![CDATA[data-manipulation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Amir Edris]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 08:44:16 GMT</pubDate>
            <atom:updated>2023-04-28T12:10:56.284Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding List and Dictionary Comprehensions in Python: Tips, Tricks, and Alternatives</h3><p>Python is a versatile, high-level programming language widely used in web development, data analysis, artificial intelligence, and more. Its popularity can be attributed to its readability, simplicity, and extensive library support. In this article, we’ll explore one of Python’s powerful features: list and dictionary comprehensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JGm-qmEkcfzFll49.png" /></figure><h4>List and Dictionary Comprehensions in Python</h4><p>List and dictionary comprehensions are powerful constructs in Python that allow you to create new lists or dictionaries from existing iterables, using a single line of code. In this article, we will dive deep into the concepts of list and dictionary comprehensions, show you code examples, explore interesting tips and tricks, and discuss when to use them and when not to. We’ll also look at alternatives to list comprehensions and the performance implications of each technique.</p><h4>List Comprehensions</h4><p>A list comprehension is a concise way of creating a list in Python. It is one of my favorite things about python. List comprehensions consists of an expression followed by a ‘for’ loop inside square brackets. The syntax looks like this:</p><pre>[expression for item in iterable if condition]</pre><p><em>Example:</em></p><pre>squares = [x*x for x in range(1, 11)]<br><br>print(squares)</pre><p><strong>Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</strong></p><p>Instead of making a list then a for loop then then adding i*i to the end of the list each loop we can do all of that in just the definition of squares and all very readable.</p><h4>Dictionary Comprehensions</h4><p>I have been using list comprehensions for 2–3 years now but until last week I never even knew this was a thing. Honestly I think most people don’t know about this.</p><p>Dictionary comprehensions are similar to list comprehensions, but they create dictionaries instead of lists. The syntax is as follows:</p><pre>{key_expression: value_expression for item in iterable if condition}</pre><p><em>Example:</em></p><pre>squares_dict = {x: x*x for x in range(1, 6)}<br><br>print(squares_dict)</pre><p><strong>Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}</strong></p><p>This doesn’t look as clean as the list comprehension but its still doing so much in so little code.</p><h4>Interesting Tips and Tricks</h4><ul><li>Nested Comprehensions: You can nest one comprehension inside another. This is useful when working with multi-dimensional data.</li></ul><p><em>Example:</em></p><pre>matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]<br><br>flattened = [num for row in matrix for num in row]<br><br>print(flattened)</pre><p><strong>Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]</strong></p><ul><li>Set Comprehension: Similar to list and dictionary comprehensions, you can also create a set using a set comprehension.</li></ul><p><em>Example:</em></p><pre>unique_squares = {x*x for x in range(-5, 6)}<br>print(unique_squares)</pre><p><strong>Output: {1, 4, 9, 16, 25}</strong></p><h4>Performance Comparison</h4><p>List and dictionary comprehensions can offer better performance compared to alternatives like `map()`, `filter()`, and for loops, especially for smaller data sets. However, the performance differences may become negligible for large data sets, and readability should be prioritized. Always consider the trade-offs between performance and readability when choosing a technique.</p><h4>Use Cases and Real-World Examples</h4><ul><li>Data transformation: List comprehensions can be used to apply a transformation to each element in a list, such as converting temperatures from Celsius to Fahrenheit.</li><li>Filtering data: Dictionary comprehensions can be used to create a new dictionary containing only specific key-value pairs, such as filtering out words shorter than a certain length from a word-frequency dictionary.</li></ul><h4>Best Practices</h4><ol><li>Keep comprehensions simple: If the logic becomes too complex or hard to understand, consider using alternatives like map(), filter(), or a simple for loop.</li><li>Limit nesting: Avoid nesting too many comprehensions, as this can make the code difficult to read and understand.</li><li>Prioritize readability: Comprehensions should improve the readability of your code. If a comprehension makes your code harder to read, consider using an alternative method.</li><li>Avoid side effects: Comprehensions should not have side effects, such as modifying an existing data structure or calling a function with side effects.</li></ol><p>Basically, if your code looks like this, you’re doing something wrong:</p><pre>print(‘’.join([chr((((i &lt;&lt; 5) | (i &gt;&gt; 3)) ^ 111) &amp; 255) for i in (72, 29, 62, 24, 74, 5, 10, 8, 83, 6, 89, 68)]))</pre><p>Although it is fun to try and beat leetcode questions in one line.</p><h4>Conclusion</h4><p>List and dictionary comprehensions are powerful and concise ways to create new lists and dictionaries from existing iterables. They can improve the readability of your code when used appropriately. However, if the logic becomes too complex, consider using alternatives like map(), filter(), or a simple for loop. Keep these guidelines and best practices in mind, and you’ll write more efficient and readable Python code. Thanks for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3QljBIdifE9piOSt.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e71ce9b81aa" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/list-and-dictionary-comprehensions-in-python-tips-tricks-and-alternatives-2e71ce9b81aa">List and Dictionary Comprehensions in Python: Tips, Tricks, and Alternatives</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making A Discord Bot That Uses GPT and Dalle-2]]></title>
            <link>https://amiredris25.medium.com/making-a-discord-bot-that-uses-gpt-and-dalle-2-a0c6c4b80ce8?source=rss-ff4ec82091dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0c6c4b80ce8</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[discord-bot]]></category>
            <category><![CDATA[openai-api]]></category>
            <dc:creator><![CDATA[Amir Edris]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 19:23:06 GMT</pubDate>
            <atom:updated>2023-04-27T21:29:07.268Z</atom:updated>
            <content:encoded><![CDATA[<p>In the first half of this article, I’ll be sharing a summary/tutorial on building a multi-feature AI-powered Discord bot, which I have created as an open-source project. If you’re interested in using the bot without diving into the coding aspects, feel free to skip to the second part of the article, where I’ll walk you through setting up the bot for your own use, using the existing GitHub repository: <a href="https://github.com/AmirMEdris/Discordbot">https://github.com/AmirMEdris/Discordbot</a>.</p><p>With rapid advancements in AI, creating applications that leverage AI to perform interesting tasks has become more accessible than ever. As a Discord user, I decided to build a Discord bot that my friends and I could enjoy like roasting users and summarizing conversations. I learned a lot from this and wanted to share what I learned.</p><h3>Part 1 — Making A Discord Bot:</h3><h4>Building the AI-Powered Discord Bot:</h4><p>In this section, we’ll walk through the process of building our Discord bot and implementing the roast and summarize features.</p><p>To get started I’m going to first walk you through the process of getting a discord bot online. It requires you to do a few simple things on the discord developer url: <a href="https://discord.com/developers/applications">https://discord.com/developers/applications</a>.</p><p>After you have logged in create a new application using the button on the top right of the screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9dWvQ1MoaG41bKQ5ekvRw.png" /></figure><p>Upon naming your application, agreeing to the discord ToS, and clicking accept you should be brought to a page for your new application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*5gFsIdnCDmEuGgOyrPlofg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AgFN8zyWOCgGIA27-ko2rg.png" /></figure><p>Once on your applications page click the bot tab on the left and generate a token. This token will be what our code uses to communicate with discord api and carry out actions as our bot. Note don’t share this token and if you plan on using github you should add it to a config file that is included in your .gitignore. If the token is in your code and you push it others could get it and use your bot. Discord detected that my bot token was in a my github repository and they immediately gave me a new token. As far as I know tokens and api keys should not just be in your code.</p><p>Instead of that I made a config.yaml file which holds both my bot token and openai api key, also any other api keys or sensitive information I might need to add later. Yaml is an alternative to json and I chose to use it because it’s more human readable but you could also use a json.</p><p>Assuming you have your bot token its time to set things up on our end. Navigate to your environment of choice(I use pycharm but it shouldn’t matter so long as you know how to use pip and the file you plan to work in)</p><p>The following libraries are needed so go ahead and install them if you dont have them already.</p><pre>pip install discord.py<br>pip install openai<br>pip install PyYAML</pre><p>After installing we are going to make two files in our project directory config.yaml and .gitignore.</p><p>Given that you are in your projects directory (The file you plan to work in) you can do this using the one of the following based on what command line you are using.</p><p>Bash (Unix-based systems) :</p><pre>touch config.yaml<br>touch .gitignore</pre><p>PowerShell (Windows):</p><pre>New-Item -ItemType File -Name &quot;config.yaml&quot;<br>New-Item -ItemType File -Name &quot;.gitignore&quot;</pre><p>Command Prompt (Windows):</p><pre>type nul &gt; config.yaml<br>type nul &gt; .gitignore</pre><p>Once those files are made add config.yaml to the gitignore by opening it and typing config.yaml. This will make github ignore this files existence so if someone wishes to clone your repo they will have to make their own in order for the bot to work for said person.</p><p>Now in the yaml file you will want to include an openai api key and the bot token. It should look like this.</p><pre>discord_bot_token: &quot;YOUR_DISCORD_BOT_TOKEN&quot;<br>openai_api_key: &quot;YOUR_OPENAI_API_KEY&quot;</pre><p>Now we can get started on the code. Make a python script, I named mine bot.py, this will act as the main script.</p><p>Originally I had all the code for the bot in one file but it started to become hectic and I split it up using cogs which I’ll talk more about later but essentially our “bot.py” is going to do a few things. First it will load in our tokens then it will add our commands to our bot using Cogs and importing other python files. Then finally it will start the bot.</p><p>When this file runs, if we got to a discord server that has the bot in it, we should see it go online.</p><pre>import openai<br>import discord<br>from discord.ext import commands<br>import yaml<br><br># Read config.yaml and get the openai_key and bot_token<br>with open(&quot;config.yaml&quot;, &quot;r&quot;) as file:<br>    config_data = yaml.safe_load(file)<br><br># Set OpenAI API key<br>openai.api_key = config_data.get(&quot;openai_key&quot;)<br>bot_token = config_data.get(&quot;bot_token&quot;)<br><br># Permissions we need<br>intents = discord.Intents.default()<br>intents.messages = True<br>intents.message_content = True<br>intents.members = True<br><br># Declaring that our bot is named bot and that its command is !!<br># It also gives the intents we set in the section above<br>bot = commands.Bot(command_prefix=&quot;!!&quot;, intents=intents)<br><br>@bot.event<br>async def on_ready():<br>    print(f&quot;{bot.user.name} is online.&quot;)<br><br>@bot.command(name=&quot;test&quot;)<br>async def test(ctx):<br>    await ctx.send(&quot;Hello, this is a test command!&quot;)<br><br>bot.run(bot_token)</pre><p>If you are used to Python but not discord there are likely a few keywords and commands in this that may be unfamiliar to you. I&#39;m going to take this opportunity to give you a break down of the discord features used here.</p><p>Intents are a mechanism provided by Discord to specify the events and data your bot can access, allowing it to receive and process specific information from the server. In our case, we have enabled intents for messages, message content, and members. I believe the correlate to the permissions when you generate the url to add the bot to your server in the oauth tab on your bots developer page.</p><p>The async and await keywords are used in Python for asynchronous programming. They enable our bot to perform multiple tasks simultaneously, such as listening for events and responding to commands, without blocking other operations.</p><p>@bot.event is a decorator that registers an event handler for your bot. In our example, we use it for the on_ready event, which is triggered when the bot successfully connects to Discord and is ready to start processing events. By defining an async def on_ready() function and decorating it with @bot.event, we can execute code when the bot is online, such as printing a status message.</p><p>@bot.command is another decorator that registers a command handler for your bot. Commands are user-triggered actions that the bot can respond to. By defining an async def function for a command and decorating it with @bot.command, we create a custom command that users can invoke in the server using the bot&#39;s command prefix (in our case, &quot;!!&quot;). For example, @bot.command(name=&quot;test&quot;) registers a command called &quot;test&quot; that, when called as !!test, will execute the defined function and send a response to the server.</p><p>Before we move on to implementing the roast feature, let’s create a custom converter class that helps in converting a user’s display name to a Member object. This is useful when you want to perform actions on a specific user or retrieve information about them based on their display name in the server.</p><p>To do this, we’ll create a class called ‘DisplayNameMemberConverter’ that inherits from the commands.MemberConverter class provided by the discord.py library. Inheritance in Python is a way to create a new class that is a modified version of an existing class. The new class (child class) inherits the attributes and behavior methods of the existing class (parent class), allowing you to reuse the code and add or override the methods as needed.</p><p>Before we dive into the code, let’s discuss why we need the DisplayNameMemberConverter class. When implementing the roast command, we want users to be able to mention someone in the server by their display name. However, by default, the commands.MemberConverter class provided by the discord.py library only accepts user IDs or user tags (e.g., UserName#1234) as valid arguments. To enhance the user experience and allow users to mention others by their display name, we&#39;ll create a custom converter class that extends the functionality of the commands.MemberConverter class.</p><p>Inheritance is a powerful concept in object-oriented programming that allows one class (the child class) to inherit the attributes and methods of another class (the parent class). This way, you can create new classes by reusing and extending the code from existing classes, which promotes modularity and maintainability. In this case, we create a DisplayNameMemberConverter class that inherits from the commands.MemberConverter class.</p><pre>class DisplayNameMemberConverter(commands.MemberConverter):<br>    async def convert(self, ctx, argument):<br>        for member in ctx.guild.members:<br>            if member.display_name.lower() == argument.lower():<br>                return member<br>        raise commands.MemberNotFound(argument)</pre><p>In this code, we override the convert() method of the commands.MemberConverter class. Instead of attempting to convert the argument using the superclass&#39;s convert() method, we directly iterate through all the members in the server and check if any of them have a matching display name. If a member is found, the method returns the corresponding Member object.</p><p>The raise keyword in Python is used to raise an exception when a specific condition is not met. In our case, if the DisplayNameMemberConverter class fails to find a member with the provided display name, it raises the commands.MemberNotFound exception, including the argument as a parameter. This allows the exception handler to provide a helpful error message to the user, informing them that the mentioned user was not found.</p><p>By using inheritance and overriding the convert() method, we can create a custom converter that accepts display names as valid arguments, improving the user experience when interacting with our roast command.</p><p>The complete code should now look like this:</p><pre>import openai<br>import discord<br>from discord.ext import commands<br>import yaml<br><br># Read config.yaml and get the openai_key and bot_token<br>with open(&quot;config.yaml&quot;, &quot;r&quot;) as file:<br>    config_data = yaml.safe_load(file)<br><br># Set OpenAI API key<br>openai.api_key = config_data.get(&quot;openai_key&quot;)<br>bot_token = config_data.get(&quot;bot_token&quot;)<br><br># Permissions we need<br>intents = discord.Intents.default()<br>intents.messages = True<br>intents.message_content = True<br>intents.members = True<br><br>class DisplayNameMemberConverter(commands.MemberConverter):<br>    async def convert(self, ctx, argument):<br>        for member in ctx.guild.members:<br>            if member.display_name.lower() == argument.lower():<br>                return member<br>        raise commands.MemberNotFound(argument)<br><br># Declaring that our bot is named bot and that its command is !!<br># It also gives the intents we set in the section above<br>bot = commands.Bot(command_prefix=&quot;!!&quot;, intents=intents)<br><br>@bot.event<br>async def on_ready():<br>    print(f&quot;{bot.user.name} is online.&quot;)<br><br>@bot.command(name=&quot;test&quot;)<br>async def test(ctx):<br>    await ctx.send(&quot;Hello, this is a test command!&quot;)<br><br>bot.run(bot_token)</pre><h4>Implementing the Roast Feature:</h4><p>Before implementing the roast feature, we need a custom converter class that converts a user’s display name to a Member object. This is useful when performing actions or retrieving information about a user based on their display name in the server. We’ll create a class called DisplayNameMemberConverter that inherits from the commands.MemberConverter class provided by the discord.py library.</p><p>Inheritance in Python allows creating a new class that is a modified version of an existing class. The new class (child class) inherits the attributes and behavior methods of the existing class (parent class), enabling code reuse and method additions or overrides as needed.</p><p>We need the DisplayNameMemberConverter class for the roast command, which allows users to mention someone in the server by their display name. By default, the commands.MemberConverter class only accepts user IDs or user tags (e.g., UserName#1234) as valid arguments. To improve user experience, our custom converter class will extend the functionality of the commands.MemberConverter class.</p><p>In the DisplayNameMemberConverter class, we inherit from commands.MemberConverter and override the convert() method. Instead of using the superclass&#39;s convert() method, we iterate through all the server members and check for matching display names. If a member is found, the method returns the corresponding Member object.</p><p>If the DisplayNameMemberConverter class fails to find a member with the provided display name, it raises the commands.MemberNotFound exception, including the argument as a parameter. This allows the exception handler to provide a helpful error message to the user.</p><p>By using inheritance and overriding the convert() method, we create a custom converter that accepts display names as valid arguments, enhancing user experience when interacting with our roast command.</p><p>Here is the updated code:</p><pre>import openai<br>import discord<br>from discord.ext import commands<br>import yaml<br><br># Read config.yaml and get the openai_key and bot_token<br>with open(&quot;config.yaml&quot;, &quot;r&quot;) as file:<br>    config_data = yaml.safe_load(file)<br><br># Set OpenAI API key<br>openai.api_key = config_data.get(&quot;openai_key&quot;)<br>bot_token = config_data.get(&quot;bot_token&quot;)<br><br># Permissions we need<br>intents = discord.Intents.default()<br>intents.messages = True<br>intents.message_content = True<br>intents.members = True<br>class DisplayNameMemberConverter(commands.MemberConverter):<br>    async def convert(self, ctx, argument):<br>        for member in ctx.guild.members:<br>            if member.display_name.lower() == argument.lower():<br>                return member<br>        raise commands.MemberNotFound(argument)<br># Declaring that our bot is named bot and that its command is !!<br># It also gives the intents we set in the section above<br>bot = commands.Bot(command_prefix=&quot;!!&quot;, intents=intents)<br>@bot.event<br>async def on_ready():<br>    print(f&quot;{bot.user.name} is online.&quot;)<br><br>@bot.command(name=&quot;test&quot;)<br>async def test(ctx):<br>    await ctx.send(&quot;Hello, this is a test command!&quot;)<br><br>bot.run(bot_token)</pre><p>Now that we have a basic understanding of how a Discord bot works, let’s dive into our first feature: the roast command. The goal of the roast command is to generate a funny roast based on a user’s message history, providing a lighthearted way to interact with friends on the server. To accomplish this, we’ll make use of OpenAI’s GPT-3 model to generate a contextually relevant roast.</p><p>To create the roast command, we first need a to define an async helper function called. I called it generate_roast(), which takes two parameters: the user&#39;s name and a list of messages. The idea is that a user is going to call our function with !!whateverfunctionname and give it a users name. When that happens we will get the username and the list of messages in his history, at that point we can just pass that into generate_roast() and it will return the roast and our main function can make the bot send that as a message. This function constructs a prompt for GPT-3 based on the user&#39;s message history and generates a roast using OpenAI&#39;s API. The roast is then returned to the calling function.</p><p>So our helper function can look like this</p><pre>async def generate_roast(user_name, messages):<br>    prompt = f&quot;Based on these messages from {user_name}, create a funny roast remember to exclude any &quot; \<br>             f&quot;names mention and focus on topics:\n{messages}\nRoast:&quot;<br>    response = openai.Completion.create(<br>        engine=&quot;text-davinci-003&quot;,<br>        prompt=prompt,<br>        max_tokens=150,<br>        n=1,<br>        stop=None,<br>        temperature=0.7,<br>    )<br>    joke = response.choices[0].text.strip()<br>    return joke<br></pre><p>Now we are going to make the main function which as I said earlier will execute when a user in discord calls it and gives it a name. We define the roast command itself using the @bot.command decorator telling the bot that this is what it should do when it sees that command in chat. We create an async function called roast() that takes a user_name parameter, converts it to a user object, and retrieves the user&#39;s message history. Now that we have both the users name and their message history we can generate a roast with our helper function, which is sent back to the server as a message.</p><p>Here’s how our bots complete code with both functions.</p><pre>import discord<br>import openai<br>from discord.ext import commands<br>import yaml<br><br># Read config.yaml and get the openai_key and bot_token<br>with open(&quot;config.yaml&quot;, &quot;r&quot;) as file:<br>    config_data = yaml.safe_load(file)<br><br># Set OpenAI API key<br>openai.api_key = config_data.get(&quot;openai_key&quot;)<br>bot_token = config_data.get(&quot;bot_token&quot;)<br>intents = discord.Intents.default()<br>intents.messages = True<br>intents.message_content = True<br>intents.members = True<br><br>class DisplayNameMemberConverter(commands.MemberConverter):<br>    async def convert(self, ctx, argument):<br>        for member in ctx.guild.members:<br>            if member.display_name.lower() == argument.lower():<br>                return member<br><br>bot = commands.Bot(command_prefix=&quot;!!&quot;, intents=intents, help_command=None)<br><br>async def generate_roast(user_name, messages):<br>    prompt = f&quot;Based on these messages from {user_name}, create a funny roast remember to exclude any &quot; \<br>             f&quot;names mention and focus on topics:\n{messages}\nRoast:&quot;<br>    response = openai.Completion.create(<br>        engine=&quot;text-davinci-003&quot;,<br>        prompt=prompt,<br>        max_tokens=150,<br>        n=1,<br>        stop=None,<br>        temperature=0.7,<br>    )<br>joke = response.choices[0].text.strip()<br>    return joke<br><br>@bot.command(name=&#39;roast&#39;)<br>async def roast(ctx, *, user_name: str):<br>    try:<br>        user = await DisplayNameMemberConverter().convert(ctx, user_name)<br>    except commands.MemberNotFound:<br>        await ctx.send(f&quot;User {user_name} not found.&quot;)<br>        return<br>    messages = []<br>    async for message in ctx.channel.history(limit=1000):<br>        if message.author == user:<br>            messages.append(message.content)<br>    if not messages:<br>        await ctx.send(f&quot;I couldn&#39;t find any messages from {user.mention}.&quot;)<br>        return<br>    # Combine last 40 messages or less<br>    messages = &quot;\n&quot;.join(messages[:40])<br>    joke = await generate_roast(user_name, messages)<br>    await ctx.send(joke) <br><br>@bot.event<br>async def on_ready():<br>    print(f&quot;{bot.user.name} is online.&quot;)<br>bot.run(bot_token)</pre><p>When I initially did this I realized that the code could look very congested and if you want to make a bot with 5,10,15 or more commands this file will be unmanageable. The discord library has a command in it called Cogs, which are a way to modularize and organize your code, making it easier to manage and maintain as the number of commands and features grow. The idea behind cogs is to separate your bot’s functionalities into distinct Python files, each responsible for a specific command or feature, and then import them into your main script.</p><p>To implement cogs, you create a class for each feature or command and inherit from the commands.Cog class provided by the discord.py library. Within this class, you can define all the necessary functions and command handlers related to the specific functionality. Once your class is set up, you can then import it into your main script and add it to your bot using the add_cog() method. This method takes an instance of the cog class and associates it with the bot.</p><p>Using cogs not only keeps your code clean and organized but also promotes reusability and easier debugging. By having separate files for each functionality, you can quickly locate issues and make updates without having to sift through a cluttered, monolithic script.</p><p>Before we continue, let’s organize our code by moving the DisplayNameMemberConverter class to its own file and creating a separate file for the roast functionality. This will make the code more modular and maintainable.</p><p>First, create a ‘modules’ folder in your project directory. This folder will store individual Python files for each function or feature, such as the roast command and our DisplayNameMemberConverter class.</p><p>To move the DisplayNameMemberConverter to its own file, create a new Python file called &#39;member_converter.py&#39; within the &#39;modules&#39; folder. Cut the DisplayNameMemberConverter class from your main code and paste it into this new file.</p><p>modules/DisplayNameMemberConverter should now look like this</p><pre>from discord.ext import commands<br><br><br>class DisplayNameMemberConverter(commands.MemberConverter):<br>    async def convert(self, ctx, argument):<br>        for member in ctx.guild.members:<br>            if member.display_name.lower() == argument.lower():<br>                return member<br>        raise commands.MemberNotFound(argument)</pre><p>Next, let’s separate the roast functionality. Create a new Python file called ‘roast.py’ within the ‘modules’ folder. To use the class in our other file we will have to import it. In this file, we’ll create a class called ‘Roast’ that inherits from the commands.Cog class provided by the discord.py library:</p><pre>from discord.ext import commands<br>import openai<br>from modules.membercvtr import DisplayNameMemberConverter<br><br>class Roast(commands.Cog):<br>    def __init__(self, bot):<br>        self.bot = bot</pre><p>Now, transfer the generate_roast() function and the roast() method into the &#39;Roast&#39; class. Ensure you add the @commands.command(name=&#39;roast&#39;) decorator for the roast() method within the class.</p><pre>import discord<br>from discord.ext import commands<br>import openai<br>import datetime<br><br>from modules.membercvtr import DisplayNameMemberConverter<br><br><br>class Roast(commands.Cog):<br>    def __init__(self, bot, openai_api_key):<br>        self.bot = bot<br>        self.openai_api_key = openai_api_key<br>        print(&quot;Roast cog initialized&quot;)<br><br>    async def generate_roast(self, user_name, messages):<br>        prompt = f&quot;Based on these messages from {user_name}, create a funny roast remember to exclude any &quot; \<br>                 f&quot;names mention and focus on topics:\n{messages}\nRoast:&quot;<br><br>        response = openai.Completion.create(<br>            engine=&quot;text-davinci-003&quot;,<br>            prompt=prompt,<br>            max_tokens=150,<br>            n=1,<br>            stop=None,<br>            temperature=0.7,<br>        )<br><br>        joke = response.choices[0].text.strip()<br>        return joke<br><br>    class DisplayNameMemberConverter(commands.MemberConverter):<br>        async def convert(self, ctx, argument):<br>            for member in ctx.guild.members:<br>                if member.display_name.lower() == argument.lower():<br>                    return member<br>            raise commands.MemberNotFound(argument)<br><br>    @commands.command(name=&#39;roast&#39;)<br>    async def roast(self, ctx, *, user_name: str):<br>        try:<br>            # await ctx.send([member.display_name for member in ctx.guild.members])<br>            user = await DisplayNameMemberConverter().convert(ctx, user_name)<br><br>        except commands.MemberNotFound:<br>            await ctx.send(f&quot;User {user_name} not found.&quot;)<br>            return<br><br>        messages = []<br>        async for message in ctx.channel.history(limit=1000):<br>            if message.author == user:<br>                messages.append(message.content)<br><br>        if not messages:<br>            await ctx.send(f&quot;I couldn&#39;t find any messages from {user.mention}.&quot;)<br>            return<br><br>        # Combine last 40 messages or less<br>        messages = &quot;\n&quot;.join(messages[:40])<br><br>        joke = await self.generate_roast(user_name, messages)<br>        await ctx.send(joke)</pre><p>Don’t forget to update any references to the bot, such as bot.command or bot.event, to commands.Cog.command or commands.Cog.event, respectively.</p><p>Lastly, let’s edit the ‘bot.py’ file to import the ‘Roast’ cog and add it to the bot. First, add the following import statement at the top of the ‘bot.py’ file:</p><pre>from modules.roast import Roast</pre><p>Then, add the following line after initializing the bot instance to add the ‘Roast’ cog:</p><pre>bot.add_cog(Roast(bot))</pre><p>bot.py should now look like this:</p><pre>import openai<br>import discord<br>from modules.summary import Summary<br>from discord.ext import commands<br>from modules.nickname import Nickname<br>from modules.visualize import Visualize<br>from modules.roast import Roast<br>from modules.help import Help<br>import yaml<br><br># Read config.yaml and get the openai_key and bot_token<br>with open(&quot;config.yaml&quot;, &quot;r&quot;) as file:<br>    config_data = yaml.safe_load(file)<br><br># Set OpenAI API key<br>openai.api_key = config_data.get(&quot;openai_key&quot;)<br>bot_token = config_data.get(&quot;bot_token&quot;)<br><br>intents = discord.Intents.default()<br>intents.messages = True<br>intents.message_content = True<br>intents.members = True<br><br>bot = commands.Bot(command_prefix=&quot;!!&quot;, intents=intents, help_command=None)<br><br>@bot.event<br>async def on_ready():<br>    print(f&quot;{bot.user.name} is online.&quot;)<br>    await bot.add_cog(Summary(bot, openai.api_key))<br>    <br><br>bot.run(bot_token)</pre><p>This was a lot of explaining but if you got this far you should be able to repeat this process for whatever other functionality you might want. And you can repeat this to make as many functions as you want by adding more cogs in the same way.</p><h3>Part 2 — How to download and use the bot.</h3><p>Lets start off by taking a look at what the bot can currently do</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*YzkGldVYXufvpGG2PmgIUg.png" /></figure><p>Remember that the quality of its roast depends greatly on your previous messages, also gpt3 gets confused when seeing names in messages i’ve gotten it to roast itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*8bgfmxu758GY2mKZfhbYYQ.png" /></figure><p>it ignored it here but thats because my last 40 is what is being used so if I spam it enough…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*wCBhUfgrCniKzDyRb5ZtnQ.png" /></figure><p>It actually didn’t do it here but you can see how the quality of the joke is much worse. Since this post already went on longer then I thought and I think its unnecessary to do this for every function I have Im just gonna show off some of the other functions I made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*iuSzFhTw4U37EOAjqtOaZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2n3VfCeXXBVSUbcqlBYznw.png" /></figure><p>If you want to use this bot on your own server I encourage you to remember this bot takes uses messages people have sent in discord and many may view prompts generated that include names or events as creepy and/or a breach of privacy. Also remember that using openai isn&#39;t free, If someone just spams the visualize function they could rack up a large bill quickly. I set a monthly limit of 5 dollars personally. Finally gpt filters content that&#39;s against openai’s code of conduct but sometimes it still produces a roast that goes pretty far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vb_mGO1lQ7U32dh8.png" /></figure><p>Try to use this with people you know that will find it funny. Understanbly some people do not take kindly to a bot reading their messages to make jokes about them.</p><p>To download this bot you can go to github and clone my repo:</p><p><a href="https://github.com/AmirMEdris/Discordbot">GitHub - AmirMEdris/Discordbot</a></p><p>As of right now you need python installed and the discord.py, openai, PyYAML libraries installed.</p><p>Once you cloned the repo make a file called config.yaml in the main folder. Edit as text put your keys in it like so</p><pre>bot_token: &quot;YOUR_DISCORD_BOT_TOKEN&quot;<br>openai_api_key: &quot;YOUR_OPENAI_API_KEY&quot;</pre><p>Replace your keys and save it.</p><p>Finally run the bot.py file in python and while that file runs any server that you have your bot in should go online and be responsive. If you generate text or images against openai guidelines you will get an error from python and the bot will keep running.</p><p>If you don&#39;t have a discord bot token I talked about how to get one at the beginning of Part 1 and you can follow these steps if you don&#39;t have an OpenAi key.</p><p>Go to the OpenAI website: <a href="https://www.openai.com/">https://www.openai.com/</a></p><ul><li>Click on “Sign Up” in the top right corner of the page, and create an account using your email address, a password, and agreeing to the terms of service.</li><li>Once you have signed up and logged in, navigate to the OpenAI Dashboard: <a href="https://platform.openai.com/signup">https://platform.openai.com/signup</a></li><li>In the dashboard, you may see different API plans available. Select the appropriate plan for your needs (Free trial, Pay-as-you-go, or a custom plan for enterprises).</li><li>After subscribing to a plan, you will receive an API key. You can access your API key anytime from your dashboard under the “API Keys” section.</li></ul><p>After that you should be good to go. If you got this far I hope you either learned something or got a good laugh from one of your friends. Like I said I plan on adding more features so if you enjoyed please follow me on medium. Finally let me know if you have any ideas or notice any problems.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0c6c4b80ce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Promises and Perils of Artificial General Intelligence (AGI)]]></title>
            <link>https://amiredris25.medium.com/exploring-the-promises-and-perils-of-artificial-general-intelligence-agi-c7f0949cc454?source=rss-ff4ec82091dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7f0949cc454</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[sam-altman]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpt-4]]></category>
            <dc:creator><![CDATA[Amir Edris]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 20:12:24 GMT</pubDate>
            <atom:updated>2023-04-07T20:12:24.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDa2PoksURwsJSF_jKRn8A.jpeg" /></figure><p>After watching an amazing episode of the <a href="https://www.youtube.com/watch?v=L_Guz73e6fw">Lex Fridman Podcast featuring CEO of OpenAI Sam Altman</a>, the thought of AGI being within our lifetimes can&#39;t escape my mind, prompting me to write my first article in a while on the topic of artificial general intelligence (AGI), AI has come a long way in the past few decades, from rule-based expert systems to deep neural networks that can severely outperform humans on tasks such as playing chess, recognizing objects, or translating languages(<a href="https://www.deepmind.com/research/highlighted-research/alphago">take a look at alphaGo</a> or honestly anything deep mind is doing). However, there is still a long way to go before AI can match or surpass human intelligence across multiple domains and contexts, a goal often referred to as AGI. This article will explore AGI&#39;s recent developments and challenges and what they mean for the future of AI and humanity.</p><p>AGI refers to a hypothetical form of AI that can perform any intellectual task that a human can across multiple domains and contexts. Unlike narrow or specialized AI, which can only perform specific tasks within a predefined range of inputs and outputs, AGI is expected to have the capacity for flexible and adaptive learning, reasoning, and communication, as well as self-awareness, creativity, and empathy. AGI is often seen as a necessary condition for achieving strong AI or superintelligence, which refers to AI that can surpass human intelligence in all relevant domains and possibly control or transform the world in ways that are difficult to predict or control.</p><h4>Recent Developments in AGI</h4><p>Some scholars argue that AGI is within reach, given the recent advances in deep learning, natural language processing, and reinforcement learning, among other areas. For example, OpenAI, one of the leading research labs in AI, has developed large language models (LLMs) such as GPT-3 and GPT-4 that can generate coherent and diverse text on a wide range of topics with impressive fluency and creativity.</p><p>These LLMs have sparked excitement and speculation about their potential to achieve AGI within our lifetimes. Some say as soon as <a href="https://mpost.io/agi-will-appear-in-1-5-years-says-david-shapiro/">one and a half years from now</a>. Others say <a href="https://research.aimultiple.com/artificial-general-intelligence-singularity-timing/">2040 — 2060</a>. I previously believed it would be closer to the latter, but after learning of openAis accomplishments with gpt4, I think it could be coming in the next 10–20 years. If progress improves exponentially the way it&#39;s been the last two years, it could be even sooner. However, what that means for the average person ranges from effortless, happy lives to mass unemployment and financial inequality.</p><h4>Challenges and Limitations</h4><p>However, other scholars are more skeptical about the prospects of AGI, pointing out the many challenges and limitations that AI still faces. For example, AGI requires a more general-purpose cognitive architecture that can integrate multiple sources of information, apply numerous forms of reasoning, and learn from diverse experiences. AGI also requires a more flexible and robust form of natural language processing that can handle ambiguity, metaphor, and context, as well as a more sophisticated form of common-sense reasoning that can bridge gaps in knowledge and infer causal relations.</p><h4>Technical, Ethical, and Societal Challenges</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZB2Fb71hluK65eRNCR5zg.png" /></figure><p>Moreover, AGI faces several technical, ethical, and societal challenges that must be addressed before becoming a reality. Some of these challenges include developing new forms of machine learning that can handle complex and dynamic environments, ensuring the safety and reliability of AGI systems, preventing unintended consequences and value misalignments, addressing the potential impact of AGI on employment, education, and inequality, and designing effective governance frameworks that can handle the uncertainty and complexity of AGI development and deployment.</p><h4><strong>The Way Forward</strong></h4><p>The future of AGI is still largely uncertain and controversial, with many unknowns and risks involved. While AGI could have tremendous benefits for humanity, such as solving complex problems, accelerating scientific discovery, and improving human well-being, it could also have significant risks and harms if not adequately aligned with human values and goals. Therefore, it is essential to have a balanced and thoughtful approach to AGI that considers its potential and risks, involving various stakeholders and perspectives.</p><p>As we continue to make strides in AI research and development, it is crucial that we carefully consider the implications of AGI and strive to maximize its benefits while minimizing its potential harms. To achieve this, an interdisciplinary collaboration among researchers, policymakers, ethicists, and other stakeholders is essential. We must also prioritize transparency, robustness, and ethical considerations in AGI development to ensure that these advanced AI systems, as Sam Altman had put it, help not hurt human lives when they get here because then what was the point?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7f0949cc454" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning to get faster performance out in Python using Big O.]]></title>
            <link>https://amiredris25.medium.com/learning-to-get-faster-performance-out-in-python-using-big-o-eb6945dd7681?source=rss-ff4ec82091dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb6945dd7681</guid>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Amir Edris]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 11:23:29 GMT</pubDate>
            <atom:updated>2021-03-20T08:39:39.847Z</atom:updated>
            <content:encoded><![CDATA[<p>When you start to get better at programming and are beginning to do more complicated things with your code, especially in Python you are going to start caring about a lot more things than “did I get this to work.” A few things you might worry about are “Could this be faster?”, “Could this be clearer?”, and “Even if this couldn’t faster, can we make it run faster?”.</p><p>I want to say quickly, I’m not an expert, and I’m just going to get you started and try to point you in the right direction, informing you about what I found was helpful to me.</p><p>Ok, so let’s say I’m feeling nostalgic and want to play a game from my childhood called cookie clicker where you click a cookie repeatedly to earn cookies that you use to buy things to buy more cookies. while playing this game, I quickly realize that I can automate using the library pyautogui and moving to mouse to the x-y coordinates of the cookie and telling Python to click repeatedly at that location for however long we want</p><p>This isn’t actually a good way to go about automating a task like this because if we move the location of the cookie on the screen it will immediately break if you actually wanted to learn how to do this properly you could try using selenium for Python a good tutorial series of which can be found here: <a href="https://www.youtube.com/watch?v=Xjv1sY630Uc">https://www.youtube.com/watch?v=Xjv1sY630Uc</a>.</p><p>Back to telling Python how to click a cookie using pyautogui. Pyautogui is a library for Python that allows users to easily use their mouse and keyboard through Python to interact with gui applications and be able to automate things. So as I said earlier all we are going to do is find the x,y coordinates for the cookie on our screen and move the mouse to that location and start clicking.</p><pre>from pyautogui import moveTo, click</pre><pre>def clickthecookie(times):<br>    moveTo(135, 513)<br>    for i in range(times):<br>        click()</pre><p>Ok so we have our function, it’ll move to the coordinate of the cookie on my screen at the time I made this which was (135,513). When I run this well see that our mouse will click at a consistent rate until it completes the number of “times” I specify. Before we go into making this faster I think this is a good opportunity to learn how to describe how long this function will take to run using Big O Notation.</p><h3>Big O Notation</h3><p>To describe how long our function is going to take all we need to do is ask ourselves, depending on our input, how many lines is this function going to run until it stops. In our case there are three lines total after the initial function declaration, the first being the line that moves our mouse. No matter what happens, the first line will be read and will move our mouse when our function is declared, it is a constant. The next line is a for loop that will loop for however many “times” we put in, in other words every line within the loop will execute n times depending on our input. The last line “click” is similar to our previous one where it is just constant, if it gets read it’ll do its job and the interpreter will move on.</p><p>Big O notation provides us with a simple way to describe the same relationships we observed above with these symbols</p><p>Constant time: O(1): O(1) or constant time means that no matter the input the output will be the same. For example:</p><pre>def sayhi(name):<br>    return &#39;Hi&#39;<br>#this function takes a name as an arguement but it really doesnt #matter because the output is always hi. The computer doesnt really <br>#need to think about whatever name you give it, it will just #constantly say hi.</pre><p>Linear time O(n): O(n) or Linear time means that as the inputs you put in get bigger, the amount of time the function will take will increase at a constant rate.</p><pre>def countTo(number):<br>    for num in range(1,number):<br>    print(number)<br>#the higher the number you give this function the longer the for #loop will run. counting to ten is the same as counting to one ten #times this is a linear relationship</pre><p>Quadratic time O(n²): Quadratic time is what happens when you do x things every time you do x thing.</p><pre>def countToxxtimes(x):<br>    for num in range(x):<br>        for number in range(x):<br>             print(number)<br>#this function is the same as the previous counting function except<br>#it counts to x x times for example if I pass in 10 it will count to #10 10 times where as in the countTo function if I pass in ten it is #only going to count to ten once meaning this function would take #ten times longer than the other one if we counted how long each #took to compute ten. If the first for loop will be read 5 times so #will the for loop within it meaning the lines within the second #loop will be read 5*5 times</pre><p>Logarithmic time O(Log n): logarithmic time occurs when you are constantly dividing something or are incrementing exponentially over the input. For these functions as the input gets bigger your operating time will increase than start to stay the same.</p><pre>def amountofsquareswithinx(x):</pre><pre>n =2<br>     while n is &lt;= x:<br>         n=n^2<br>     return n<br>#as xgrows we the amount of time it will take to reach x will start #to decay because of the rate at which n will start to grow.</pre><p>Linearithmic time O(n*Log n): Linearithmic algorithms are ones where you perform a logarithmic algorithm more times as you input gets bigger</p><p>Exponential time O(2^n ): As your input increases the operating time increases exponentially. ie calculating the number of unique pairings between x items. As the number of items to check increases, the number of pairings will begin to grow exponentially.</p><p>Factorial time O(n!): pretty much trying to brute force your way to an answer. The growth rate for O(n!) is ridiculous and unsustainable at high inputs as it could literally take you hundreds of years at a certain point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TSc8a1xa4h6oY4xz.jpeg" /></figure><p>Using what we learned from big O notation we can now look back at out cookie clicking function and break it down using the notation</p><pre>def clickthecookie(times):#O(1)<br>    moveTo(Cookie)#O(1)<br>    for i in range(times):#O(n)<br>        click()#O(1)<br># using big o we can determine that for n input this funciton will take<br>#O(n)+O(1)+O(1)+O(1)</pre><p>As mentioned in the comments of the code block above, we can calculate that the above function will take O(n)+O(1)+O(1)+O(1). Then you are looking at your functions operating complexity you are looking for the worst-case scenario meaning you should just look at the fastest growing term in your code as that’s the best indicator of what the longest times will look like. Keeping this in mind we will drop the constants and take O(n). But how accurate is this actually?</p><p>If we count to 100 and run our function with our current number for every number while timing it we can make a graph and see how well it matches up with our theory.</p><pre>import matplotlib.pyplot as plt</pre><pre>timestocompute = []<br>inputs = []<br>for i in range(100):<br>    start=t()<br>    pc.clickthecookie(i)<br>    finish = t()-start<br>    timestocompute.append(finish)<br>    inputs.append(i)<br>plt.scatter(inputs,timestocompute)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*dI6D5rMM8mxMt-r2hFWZ6Q.png" /></figure><p>And we were right as our input(0–100 on the x-axis) increases so does the operating time(seconds on the y-axis). Knowing this you should now be able to at least identify the problem parts of beefy code you make/encounter. But what if you broke it down and you cant find a way to further increase the performance of your work? I’m planning on making posts on these as well but I would look into Cython and/or threading/multiprocessing.</p><p>I hope you found this helpful and would love some feedback on why it may not have been. Thanks for reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb6945dd7681" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Reinforcement Learning]]></title>
            <link>https://medium.com/swlh/understanding-reinforcement-learning-b90b0bff71b?source=rss-ff4ec82091dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b90b0bff71b</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[q-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Amir Edris]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 06:28:52 GMT</pubDate>
            <atom:updated>2020-10-14T18:56:32.756Z</atom:updated>
            <content:encoded><![CDATA[<p>Reinforcement learning refers to machine learning focused on algorithms that learn how to interact with an environment. An example of such an algorithm is called Q-learning. Although it is closer to a brute force approach, Q-learning is probably the most popular reinforcement learning method. Before we get into Q-learning, let&#39;s first discuss why we don&#39;t use an unsupervised or supervised learning approach.</p><p>In a supervised learning approach, you give the algorithm rows of data, and each row has an answer that the algorithm will try to fit. It’s the equivalent of providing the algorithm pictures of dogs and cats, and every time our algorithm gives the wrong answer for a photo, tell it to make adjustments to itself so that the next time it sees a similar observation, it is closer to getting it right. We then hope that, after tons of rows of data or in this case, images of dogs or cats, our algorithm “understood” enough about the question “Is this an image of a dog or cat?” to do well in the testing phase consistently.</p><p>If you want to know why I said evaluation metric instead of accuracy, you can read more about evaluating classification models here: <a href="https://towardsdatascience.com/common-classification-model-evaluation-metrics-2ba0a7a7436e">https://towardsdatascience.com/common-classification-model-evaluation-metrics-2ba0a7a7436e</a>.</p><p>The other machine learning method is Unsupervised learning. Unlike supervised learning, unsupervised learning is an approach where the dataset might isn’t labeled, or you have a dataset where you suspect there to be a relationship between observations, but it isn&#39;t obvious or is too complicated to understand. Well, an unsupervised learning model will identify relationships that allow it to different group observations. It is unsupervised because instead of giving the computer an answer to fit to repeatedly until it gets it, we just ask the computer to tell us what patterns it sees that we might be missing there&#39;s no right or wrong answer for the computer.</p><p>If you wanted to make a model to play a video game of the two previous methods, you might think supervised learning looks promising because you can feed it instances of the game and have the answer be the correct move to make. This method has some problems; the model is learning to imitate the person who originally played the game. Also, this model wouldn&#39;t have any end game in mind, it only knows what’s going on one step at a time, and at every step, it will try to do the thing closest to what the original player was doing.</p><h4>What is Reinforcement Learning</h4><p>Reinforcement learning is where the model plays the game and decides which actions get it closer to its end goal. This is a much better approach than the one before in most cases because now we are training our algorithm by learning how to play the game. Before the algorithms playstyle would be affected by that of the person from whom the observations were taken from, the majority of our say comes from the magnitude of the reward we set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*8ouE9Y3DJS2k1fpX" /></figure><p>The figure above represents a random picture I took off of google search for q tables. Ok so every row is a state of the game and every column is the actions that the agent can take. Every point is a Q-value. Assuming we aren&#39;t taking any random actions at state zero, the agent will take action 4 because that maximizes the reward since all the other columns are -1. At every row, the agent will pick the action of the highest q and will then adjust that value based on how successful it was which we will go into in a bit.</p><p>That probably doesn&#39;t sound very easy to implement and from my experience, and it is for higher-tier models, on the bright side, this is why Q-learning is the first step for most people as it can be expanded upon with neural networks and is a way to get an understanding of the different terms that you will see thrown around a lot in explanations down the road.</p><h4>Implementing this on our own</h4><p>To get a game for our reinforcement learning model to learn simply pip install gym and import it. Gym is a python library made by open ai to help people test and learn reinforcement learning. It allows us to easily get information that our model will need from the game.</p><pre>pip install gym</pre><h4>Keywords</h4><p>Now there are some keywords we should go over.</p><p>Action: action is the decision the model takes based on its location</p><p>State: State is an instance of the game in which the model will take an action given that the current state didn&#39;t end the game.</p><p>Reward: Score given to our model to help it understand what the important things to do in order to beat the game are.</p><p>Policy: Policy is the model’s current overall strategy to reach its goal.</p><p>Agent: the name we use to refer to a reinforcement learning model.</p><p>Q-function: The Q-function is the function that returns a score representing how good taking a specific action at a state will be.</p><h4>Formula</h4><p>For our model to complete the game it needs to correctly estimate which actions will have the highest Qs so that it consistently selects the right actions to take. If our model learns this its policy or strategy will start to get results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xL75UPUSTy-JsLQzl2p2fA.png" /></figure><p>Now that might not be friendly to look at but this is how we are gonna determine our new q values.</p><p>The two functions on the right in the “temporal difference” portion represent our current actions q value and we subtract that from the maxQ which is the highest q value in the next position. For the sake of this example, let&#39;s call the result NextMoveScore.</p><p>To the left is the sum of our reward and discount factor for the action we just took. Let’s call this our ScoringFactor.</p><p>we have two more variables left. on the far left is our old value and to the right of that is our learning rate or the size of the improvement that we want to make to our current Q value.</p><p>so with our shorter version, we can say:</p><p>The new Q is equal to the old Q plus the learning rate times the ScoringFactor multiplied by NextMoveScore.</p><p>One more thing we need to understand is exploring vs exploiting actions. Exploring is basically taking random actions so that our agent can experiment with moves that it would not otherwise take and evaluate how good their q scores are to see if it needs to change policy. Exploiting means that the Agent is taking the best action that it knows at every state.</p><p>When training your model it needs to explore a bit to be able to get a feel for what it&#39;s supposed to do so we give the model an epsilon factor which starts at 1 and slowly decreases to zero every turn. At the beginning of every turn we draw a random decimal number from 0–1 if it’s bigger than epsilon the ai decides where to go if it isn&#39;t the ai takes a random action over time the ai will take less and less random numbers because of epsilons decay.</p><p>I hope that all this made sense to you now I&#39;m going to quickly go through the code for this which originally came from <a href="https://pythonprogramming.net/q-learning-algorithm-reinforcement-learning-python-tutorial/">https://pythonprogramming.net/q-learning-algorithm-reinforcement-learning-python-tutorial/</a>. I just changed the map and made it object-oriented.</p><p>The first few things we’ll get out the way are our imports, ie: gym and numpy, telling gym what environment we are going to train on, in our case we are using “Acrobot-v1”, and making the agent class that will be used to instantiate agents.</p><pre>import gym<br>import numpy as np<br><br>env = gym.make(&#39;Acrobot-v1&#39;)<br><br><br>class Ai:<br>    def __init__(self,env):<br><br>        self.DiscreteSize = [10,10,10,10,50, 100]<br>        self.bins = (env.observation_space.high - env.observation_space.low) / self.DiscreteSize<br>        self.LearningRate = 0.1<br>        self.Discount = 0.95<br>        self.Episodes = 50<br>        self.epsilon = 1<br>        self.startepsilondecay = 1<br>        self.endepsilondecay = self.Episodes // 2<br>        self.epsilondecayvalue = self.epsilon / (self.endepsilondecay - self.startepsilondecay)<br>        self.q_table = np.random.uniform(low=-2, high=0, size=(self.DiscreteSize + [env.action_space.n]))</pre><p>Under the __init__ method we basically truncate our states to make them discrete because some of these points have too many unique values and we cant make our computer make a row for each because it will take too long. Episodes refer to the number of times you want the agent to play the game. We also initialize the Qtable so that at each instance each action has a reward of -2.</p><pre>def get_discrete_state(self,state):<br><br>        discrete_state = (state - env.observation_space.low) / self.bins<br>        discrete_state= tuple(discrete_state.astype(np.int))<br>        return discrete_state</pre><p>This is a function to make the non-discrete-continuous states into discrete ones.</p><pre>def move(self):<br><br>        if np.random.random() &gt; self.epsilon:<br>            self.action = np.argmax(self.q_table[self.discrete_state])<br>        else:<br>            self.action = np.random.randint(0, env.action_space.n)<br>        self.new_state, self.reward, done, _ = env.step(self.action)<br>        self.new_discrete_state = self.get_discrete_state(self.new_state)<br>        return done</pre><p>This is the move function. The first part of the if-else is the normal move for when the random number draw is greater than epsilon so the agent moves normally. The else is for the case where the random number drawn is less than epsilon so the agent moves randomly. We then save the new state information and make it discrete. We return done so the while loop, later on, that runs our episodes knows if an episode has been completed.</p><pre>def newq(self):<br><br>        self.max_future_q = np.max(self.q_table[self.new_discrete_state])<br>        self.current_q = self.q_table[self.discrete_state + (self.action,)]<br>        self.new_q = (1 - self.LearningRate) * self.current_q + self.LearningRate * (self.reward + self.Discount * self.max_future_q)<br>        self.q_table[self.discrete_state + (self.action,)] = self.new_q<br><br>        self.discrete_state = self.new_discrete_state</pre><p>The newQ is used to well, calculate the new q. it follows the same formula we talked about before just broken up into pieces</p><pre>def epsilondecay(self):<br>        if self.endepsilondecay &gt;= episode &gt;= self.startepsilondecay:<br>            self.epsilon -= self.epsilondecayvalue</pre><p>Finally, the last method for our Ai class is the epsilon decay method. remember everything above this line was in one class ai.</p><pre>qlearner = Ai(env)<br>qlearner.discrete_state = qlearner.get_discrete_state(env.reset())<br>done = False<br>showEvery = 1</pre><p>So now we can call our Ai class and pass in the environment we instantiated before under our imports. env.reset() starts the environment over and we made sure to use the get discrete state method on that.</p><pre>for episode in range(qlearner.Episodes):<br>    qlearner.discrete_state= qlearner.get_discrete_state(env.reset())</pre><pre>    done = False<br><br>    if episode % showEvery == 0:<br>        render = True<br>    <br>    else:<br>        render = False<br>    <br>    <br>    while not done:<br>        done = qlearner.move()<br>        if render == True:<br>            env.render()<br>        if not done:<br>            qlearner.newq()<br><br>    qlearner.epsilondecay()<br><br>env.close()<br>print(&#39;final:&#39;,qlearner.score)#action to take in each state</pre><p>This block runs the training of the Agent. The first for loop starts an episode the if-else after that is to either render or not render the graphical representation of the game, it&#39;s faster to set this to zero but you probably want to see how your agent is doing. The while loop basically says while the game is not done make another move and update the Q-table. After each episode, we decay epsilon a bit to shift our agent from exploring to exploiting ever so slightly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b90b0bff71b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/understanding-reinforcement-learning-b90b0bff71b">Understanding Reinforcement Learning</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quickly Compile Python in C using Cython]]></title>
            <link>https://amiredris25.medium.com/quickly-compile-python-in-c-using-cython-65a739937abd?source=rss-ff4ec82091dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/65a739937abd</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Amir Edris]]></dc:creator>
            <pubDate>Tue, 29 Sep 2020 15:02:28 GMT</pubDate>
            <atom:updated>2021-01-12T18:10:21.654Z</atom:updated>
            <content:encoded><![CDATA[<p>a lot of people use Cython to compile their python code in C for performance gains. It’s petty easy to do and might be something that you want to take advantage of.</p><p>Make sure you pip install Cython first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*abUGWILIoYe9gMpv.png" /></figure><p>The overall process goes like this.</p><ul><li>Bring the parts of your code you want to convert to c into a separate file</li><li>Give type information and let Cython know what you want to use in Python and what you don’t.</li><li>compile the separate file using a setup.py file</li></ul><p>For this example, let’s say we want to compile this function into C</p><pre>def AddToTen():<br>    x = 0</pre><pre>for i in range(1,11):<br>        x+=i<br>    return x</pre><p>The first thing we need to do is move this from a .py file into a .pyx file, which is what Cython uses. Now we are going to give type information to our variables</p><blockquote><em>Want to read this story later? </em><a href="http://usejournal.com/app/signup?save_link=https://medium.com/amiredris25/quickly-compile-python-in-c-using-cython-65a739937abd"><em>Save it in Journal.</em></a></blockquote><p>in Cython, there are three def statements</p><ul><li>cdef: declaring something that is only going to be used in c(like the variables inside our function)</li><li>pdef: declaring something that is only going to be used in Python</li><li>cpdef: declaring something this going to be used in both</li></ul><pre>cpdef int AddToTen():<br>    cdef int x = 0<br>    cdef int i</pre><pre>for i in range(1,11):<br>        x+=i<br>    return x</pre><p>Since I’m not going to call the variables inside our function in Python, I used cdef, but for the function itself, I used cpdef</p><p>Also, notice we typed the I in the for loop and the function since it returns an int.</p><p>Now we have to compile our .pyx. In a separate file (mine is named setup.py), write the following code.</p><pre>from distutils.core import setup<br>from Cython.Build import cythonize</pre><pre>setup(ext_modules = cythonize(&#39;The_Name_Of_Your_Pyx_Here.pyx&#39;))</pre><p>Finally, in terminal(make sure you are in the same folder), run the line</p><pre>python setup.py build_ext --inplace</pre><p>This should’ve compiled your pyx, and you should see a file of the same name with the extension .c instead of pyx</p><p>You can now import your c functions into local python files, given that you used cpdef, just by import’ name of your file’. IDEs tend to give me import errors even though they imported fine. You can also import python libraries into the pyx file, but in my experience, it performs the same as it would in Python.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65a739937abd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Random Number Generation in Python]]></title>
            <link>https://amiredris25.medium.com/intro-to-random-number-generation-in-python-f1fc8977f63e?source=rss-ff4ec82091dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1fc8977f63e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[random-numbers]]></category>
            <category><![CDATA[programming-beginner]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Amir Edris]]></dc:creator>
            <pubDate>Tue, 25 Aug 2020 06:08:39 GMT</pubDate>
            <atom:updated>2020-08-25T17:21:35.179Z</atom:updated>
            <content:encoded><![CDATA[<p>I think that a cool thing to learn as a beginner in python is how to produce random numbers. Random number generation is an interesting topic to get into learn simply because of its applications. This post will go over surface-level concepts of random number generation and the different ways we can go about using them with examples.</p><p>Computers are deterministic, meaning that if you put an input you will get the same output no matter how many times you try. This is because computers take inputs then follow sets of instructions the give you your output. So how do you get a computer to make random numbers? Computers generate something that is called a pseudo-random number or a number that emulates a random number but is produced predictably from algorithms and an input number or as they are called in this case a “Seed number.”</p><p>An early example of a pseudo-random number generation algorithm was known as the middle square method. The middle square method would start with any number, square it and remove the middle digits and use that sequence as your random number string. We have come a long way from algorithms like these used in the mid 20th century. What you really need to know is that these algorithms take in a seed and from that, generate a random number table which can then be used for simulations</p><p>What is a seed? If you have ever played Minecraft, you have experience using seeds even if you weren’t aware of it. In Minecraft, random worlds are generated using an input seed that users can put in themselves to make their “randomly generated world” reproducible. Let’s say you play and randomly made a world that you want other people to be able to produce precisely the same all you would have to do is provide the sequence of numbers used to create that world. In programming, if you make a script and want the results to be reproducible while also needing random numbers, you would specify what seed you are using at the start of the program so that the random numbers used are going to be the same every time.</p><p>Random number generators, sets of algorithms made to produce pseudo-random numbers, are deterministic. That means that random number generators will always give you the same output given the input seed. The algorithm will take the seed and use it to produce the set of random numbers, so if the seed is the same, the output will always be the same.</p><p>Now that we have a little understanding of how random number generation works, let’s go over the ways to use them in python. Python has a built in module called random which, believe it or not, is used for random numbers.</p><p>Python uses a Mersenne Twister Core Generator implemented in the c language for efficiency. The Mersenne Twister is one of the most popular algorithms for random number generation currently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5R98MTRQpG6ahEFYysSyYg.png" /></figure><pre>import random<br>random_number = random.random()<br>print(random_number)</pre><p>random.randint(low, high) will give you an integer, or whole number, between the “low” and “high” that you give it.</p><pre>import random<br>random_int = random.randint(1,10)<br>print(random_int)</pre><p>random.randrange(start, stop, step) will give you a random number within the range(start, stop) that you give it. The step portion lets it know what numbers to look at, for example, random.randrange(1, 20, 3) will look at every three digits in the range 1–20 and give you one of those at random.</p><pre>import random<br>random_number = random.randrange(1,20,3)<br>print(random_number)</pre><p>random.choice(sequence) will make a selection from a list that you pass in at random</p><pre>import random<br>names = [&#39;Steph&#39;,&#39;Klay&#39;,&#39;Kyrie&#39;,&#39;LeBron&#39;]</pre><pre>random.choice(names)</pre><p>There are plenty more in the python docs that you can look at:<a href="https://docs.python.org/3/library/random.html">https://docs.python.org/3/library/random.html</a>.</p><p>Since we got that out the way, let’s use the python random module to make a coinflip function. We want to be able to pass times as the argument and get x coinflips. If any of the explanations are confusing, id, recommend looking over the code and playing around with it.</p><p>code:<a href="https://github.com/AmirMEdris/Blog/blob/master/Examples%20of%20different%20random%20functions.ipynb">https://github.com/AmirMEdris/Blog/blob/master/Examples%20of%20different%20random%20functions.ipynb</a></p><pre>import random<br><strong>def</strong> seed_warning(seed):<br>    <strong>if</strong> seed == <strong>None</strong>:<br>        print(&#39;WARNING:there is no seed a random one will be used&#39;)<br>    <strong>else</strong>:<br>        print(&#39;using seed <strong>{}</strong>&#39;.format(seed))</pre><pre>def coinflip(times): # Declare function name and arguement<br>    for flip in range(0,times):<br>        coin = random.random()<br>        <strong>if</strong> coin &lt; 0.5:<br>            print(&#39;Flip #&#39;,flip+1,&#39;: Tails&#39;)<br>        <strong>else</strong>:<br>            print(&#39;Flip #&#39;,flip+1,&#39;: Heads&#39;)<br>coinflip(5)</pre><p>We made two functions here. You can ignore seed_warning for now. Running coinflip(5) should give an output that looks like this.</p><pre>Flip # 1 : Tails<br>Flip # 2 : Heads<br>Flip # 3 : Heads<br>Flip # 4 : Tails<br>Flip # 5 : Tails</pre><p>Now we can use the random.seed() function with our coinflip function so we have consistent results. The seed warning function we made will tell us at the beginning of our function that we either did or didn’t use a seed.</p><pre><strong>def</strong> coinflip(times,seed=<strong>None</strong>):<br>    seed_warning(seed)<br>    random.seed(seed)<br>    <strong>for</strong> flip <strong>in</strong> range(0,times):<br>        coin = random.random()<br>        <strong>if</strong> coin &lt; 0.5:<br>            print(&#39;Flip #&#39;,flip+1,&#39;: Tails&#39;)<br>        <strong>else</strong>:<br>            print(&#39;Flip #&#39;,flip+1,&#39;: Heads&#39;)</pre><p>In our functions arguments, we added ‘seed’ = None, which means that when we use coinflip if we only specify times and not seed, the default seed is None. Now let’s run this.</p><pre>coinflip(5,seed = 1)</pre><p>Set the seed to 1, and we should both get</p><pre>using seed 1<br>Flip # 1 : Tails<br>Flip # 2 : Heads<br>Flip # 3 : Heads<br>Flip # 4 : Tails<br>Flip # 5 : Tails</pre><p>the first line came from our seed warning function. If you also used seed 1 and flipped 5 or more coins, our first five results should be the same here.</p><p>Now let’s use random.seed to make every coinflip the same</p><pre><strong>def</strong> unfaircoinflip(times,seed=<strong>None</strong>):<br>    seed_warning(seed)<br>    <strong>for</strong> flip <strong>in</strong> range(0,times):<br>        random.seed(seed)<br>        coin = random.random()<br>        <strong>if</strong> coin &lt; 0.5:<br>            print(&#39;Flip #&#39;,flip+1,&#39;: Tails&#39;)<br>        <strong>else</strong>:<br>            print(&#39;Flip #&#39;,flip+1,&#39;: Heads&#39;)</pre><pre>unfaircoinflip(6,seed=1)</pre><p>and run it.</p><pre>using seed 1 <br>Flip # 1 : Tails <br>Flip # 2 : Tails <br>Flip # 3 : Tails <br>Flip # 4 : Tails <br>Flip # 5 : Tails <br>Flip # 6 : Tails</pre><p>So what changed? The two functions we made are nearly identical but in the second one, we are setting the seed in the first line of the loop so every iteration resets the random number generator so every answer will be equal to the first answer.</p><p>Finally, let’s use the random.choice() method to make a sequence of DNA.</p><pre><strong>def</strong> random_gene(length, seed = <strong>None</strong>):<br>    seed_warning(seed)<br>    random.seed(seed)<br>    Bases = &#39;TCAG&#39;<br>    seq = &#39;&#39;<br>    <strong>for</strong> bases <strong>in</strong> range(0,length):<br>        choice = random.choice(Bases)<br>        seq+= choice<br>    print(seq)<br>random_gene(50, seed =1)</pre><p>The overall structure is that we first declare our string of bases, “Bases”, then we make an empty string seq. For the number of values that we need in our sequence, we make a random choice from bases and add them to our sequence.</p><p>Running that should look like</p><pre>using seed 1 <br>CTATGGGGCTGTGGTGACTATTTTGCGTCGGCACCGATGTCATAGCAAGG</pre><p>……………………………………..</p><p>np.random.rand(arrays, array_length), makes an n-dimensional array of random floats between 0 and 1. what that means is that it will give us multiple arrays, of length array_length, with random values between 0 and 1 in each slot. Remaking our coinflip using np.random.rand() looks like:</p><pre><strong>def</strong> NpFlip(trials, amount,seed = <strong>None</strong>):<br>    seed_warning(seed)<br>    np.random.seed(seed)<br>    random_numbers = np.random.rand(trials, amount)<br>    coinflips=[]<br>    <strong>for</strong> trial <strong>in</strong> random_numbers:<br>        trial_results = []<br>        <strong>for</strong> flip <strong>in</strong> trial:<br>            <strong>if</strong> flip &lt; 0.5:<br>                trial_results.append(&#39;Tails&#39;)<br>            <strong>else</strong>:<br>                trial_results.append(&#39;Heads&#39;)<br>        coinflips.append(trial_results)<br>    print(coinflips)<br>NpFlip(2, 6)</pre><p>since we are now going to get multiple arrays back instead of one value at a time, when we generate our random numbers, we can go through each array using a for loop and go through each item within that array with a nested for loop and for every value add either heads or tails to a list and print it in the end.</p><pre>WARNING:there is no seed a random one will be used<br>[[&#39;Tails&#39;, &#39;Tails&#39;, &#39;Tails&#39;, &#39;Heads&#39;, &#39;Heads&#39;, &#39;Heads&#39;], [&#39;Tails&#39;, &#39;Tails&#39;, &#39;Heads&#39;, &#39;Tails&#39;, &#39;Tails&#39;, &#39;Heads&#39;]]</pre><p>Ok, so numpy may have complicated our coinflip function a bit, but it depends on how and when you use it. For our gene function, numpy makes it look much cleaner.</p><pre><strong>def</strong> np_short_random_gene(length,seed = <strong>None</strong>):<br>    seed_warning(seed)<br>    np.random.seed(seed)<br>    Bases = [&#39;T&#39;,&#39;C&#39;,&#39;A&#39;,&#39;G&#39;]<br>    seq = np.random.choice(Bases,length,replace = <strong>True</strong>)<br>    print(&#39;&#39;.join(seq))</pre><p>np.random.choice(seq, choices) makes a random choice on the sequence you give it for however many options you ask for. The replace argument will make it so that the result list can have duplicates if true.</p><p>Just to conceptualize, you can use the few things here you just learned to make a pokemon style fight with random choices operating as the ai. I’m gonna try to make every part of it into a function so that its easier to understand all the moving parts.</p><p>The first thing we’ll do is make a function that will roll 1–100 for both players and find out who goes first</p><pre>def goes_first(namea,nameb):<br>    aroll = random.randint(1,100)<br>    broll = random.randint(1,100)<br>    if aroll &lt;= broll:<br>        first = nameb<br>    else:<br>        first = namea<br>    return first</pre><p>Next, we are gonna make a function that will randomly return 4 moves from a list of pokemon moves. We are gonna use this to keep the games fresh and randomly assign each player 4 moves.</p><pre>def player_moves():<br>    pokemon_moves = [&#39;absorb&#39;, &#39;volt-tackle&#39;, &#39;accelerock&#39;, <br>                     &#39;acid&#39;, &#39;acrobatics&#39;, &#39;watergun&#39;, &#39;squirt&#39;,<br>                    &#39;tackle&#39;, &#39;cut&#39;,&#39;splash&#39;, &#39;shock&#39;, &#39;hyper-beam&#39;]<br>    move_list = np.random.choice(pokemon_moves,4)<br>    return move_list</pre><p>We’ll need a function that takes player moves and assigns them random values for damage.</p><pre>def player_stats(moves):<br>    moves_stats = []<br>    for move in moves:<br>        move_stat = random.randint(1,20)<br>        moves_stats.append((move,move_stat))<br>    return moves_stats</pre><p>For simplicity, we are gonna make a function that does the last two functions together.</p><pre>def player_setup():<br>    moves = player_moves()<br>    moves = player_stats(moves)<br>    return moves</pre><p>Now we are going to make two functions, one for the ais move and one for the player’s move. The ai’s move is just going to be a random selection from the 4 moves it has using random.choice(). The player is going to have his options printed to the console and be able to read his abilities then pick one to use.</p><pre>def ai_move(move_stats):<br>    move = random.choice(move_stats)<br>    return move<br>def player_move(move_stats):<br>    x = 0<br>    print(&#39;_____PLAYER ATTACK_____&#39;)<br>    for i in move_stats:<br>        x+=1<br>        print(&#39;move#{} You have {} which does around {}        damage&#39;.format(x,i[0],i[1]))<br>    print(&#39;-----------------------------------------&#39;)<br>    move_key = int(input(&#39;Type the move number of the move youd like to use:&#39;))<br>    move = move_stats[move_key-1]<br>    print(&#39;-----------------------------------------&#39;)<br>    return move</pre><p>Now that we have ways for both the player and ai to express what they want to do we need to make a function that actually carries out their attacks.</p><pre>def player_turn(player1,player2,moves,enemy_hp):<br>    attack = player_move(moves)<br>    enemy_hp -= attack[1]<br>    print(&quot;{} used {} it did {} damage to {}&quot;.format(player1, attack[0],<br>                                                       attack[1],player2))<br>    return enemy_hp<br>def ai_turn(player1,player2,moves,enemy_hp):<br>    print(&#39;______ENEMY_ATTACK_____&#39;)<br>    attack = ai_move(moves)<br>    enemy_hp -= attack[1]<br>    print(&quot;{} used {} it did {} damage to {}&quot;.format(player1, attack[0],<br>                                                       attack[1],player2))<br>    return enemy_hp</pre><p>the above functions just take in the names of player1 and player2, the set of moves that the attacking player has, and the enemies hp. It subtracts the damage from the attack and prints what happened to the user.</p><p>Almost done, we need a function to let us know what turn we are on and who is going first.</p><pre>def print_turn(turn,first):<br>    print(&#39;-----------------------------------------&#39;)<br>    print(&#39;Turn #&#39;,turn)<br>    print(&#39;-----------------------------------------&#39;)<br>    if turn == 1:<br>        print(&#39;first is {}&#39;.format(first))</pre><p>In our game, we want whoever’s first to attack then print the damage done then the second player attacks and print the damage done then print hp. We are going to make two functions that do just that for both cases of if the player goes first and if the ai goes first.</p><pre>def player_first_move(first,second,first_moves,second_moves,ai_hp,    player_hp):<br>    ai_hp = player_turn(first,second,first_moves,ai_hp)<br>    player_hp = ai_turn(second,first,second_moves,player_hp)<br>    print(&#39;You have {} hp, Your opponent has {} hp&#39;.format(player_hp,ai_hp))<br>    return ai_hp, player_hp</pre><pre>def ai_first_move(first,second,first_moves,second_moves,ai_hp,player_hp):<br>    player_hp = ai_turn(second,first,second_moves,player_hp)<br>    ai_hp = player_turn(first,second,first_moves,ai_hp)<br>    print(&#39;You have {} hp, Your opponent has {} hp&#39;.format(player_hp,ai_hp))<br>    return ai_hp, player_hp</pre><p>Now one last function to check who won</p><pre>def win_check(player_hp):<br>    if player_hp &lt;=0:<br>        print(&#39;you lost&#39;)<br>    else:<br>        print(&#39;you won&#39;)</pre><p>And we can finally put it all together</p><pre>def pokemon_fight(a,b,seed = None):<br>    <br>    seed_warning(seed)<br>    player_hp = 100<br>    ai_hp = 100<br>    first = goes_first(a,b)<br>    second = b if first == a else a<br>    first_moves = player_setup()<br>    second_moves = player_setup()<br>    turn = 1<br>    <br>    while player_hp &gt; 0 and ai_hp &gt; 0:<br>        print_turn(turn,first)<br>        if first == a:<br>            ai_hp,player_hp = player_first_move(first,second,first_moves,second_moves,ai_hp,player_hp)<br>        else:<br>            ai_hp,player_hp = ai_first_move(first,second,first_moves,second_moves,ai_hp,player_hp)<br>        turn+=1<br>        <br>    win_check(player_hp)</pre><p>We now have a function pokemon_fight(player1,player2,seed=x) that will run our game.</p><p>As mentioned before playing around with the code: <a href="https://github.com/AmirMEdris/Blog/blob/master/Examples%20of%20different%20random%20functions.ipynb">https://github.com/AmirMEdris/Blog/blob/master/Examples%20of%20different%20random%20functions.ipynb</a>. will probably be helpful if you my explanations didn’t make sense to you.</p><p>I hope this was helpful to someone thank you for reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1fc8977f63e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>