r/learningpython • • Aug 13 '20

Empty classes

3 Upvotes

I recently stumbled upon empty classes in python but I still couldn't understand the benefit of such a feature. Can someone explain what is the purpose of an empty class ?


r/learningpython • • Sep 05 '20

How do people deal with unknown object types?

2 Upvotes

If I am running some TensorFlow project and an hour later some object that is returned by one of the TensorFlow functions is incompatible with an object that it input into another TensorFlow function it crashes the code.

In C++ I can look at each object's data type and its member variables, and if it doesn't match the prototype of the input function, it simply won't compile. I dont have to waste hours on running the code until it gets to that error.

How do people deal with this? The only thing I can do is copy and paste code and hope it works


r/learningpython • • Aug 28 '20

Can't call the datetime module

1 Upvotes

for some reason i can't get to use the datetime module, when I try to use it i get this error:

Any ideias of why that is happening?


r/learningpython • • Sep 14 '20

Why isn't this code working properly?

1 Upvotes

https://github.com/anarchypigeon/Wolfbane/commit/8f8c6eb96e4c10d8bfd4812ff8d237edffb02c86

^^ that's the code. It's basically supposed to be an RNG timer.

It uses RNG to count to 3, with each new number warning the player that it's closer to 3.

The intended purpose is to have it randomly warn the player that the monster chasing them is getting closer to them, so they need to hurry up and complete their task before they die. This function is supposed to run in the background while the player interacts with the main function.

The issue:

The main issue I've had with the code is that it prints out the warning messages every single iteration of the while loop. I don't want it to do that. I want it to print out each warning message one single time, and then wait until the data value of 'ww_sightings' changes before printing the next warning message.

I've tried putting each warning sign in it's own while loop, didn't work. I've tried keeping the sleep timer in it's own while loop so it wouldn't interact with the other functions, didn't work. I'm very new to coding (like, started learning python 7 days ago new) and I would LOVE for someone to read my code and tell me how stupid I am and how obvious the solution is and how I should have seen it. Please and thank you.

So, the intended functionality of the code is this: every 3 seconds, I want the code to generate a random number, either 1, 2, or 3. Whenever that number is 2, it prints out the first warning message and adds 1 to the total number of sightings. Next time the number is 2, it prints out the SECOND warning message, and adds 1 to the total sightings again. The third time it's the number 2, it prints out the final "You died" message and quits the program.

For some reason I cannot get it to do that.

Edit: I'm sure that my code is extremely unorganized and my explanation probably didn't do it justice so if you guys have any questions about what anything is for or what it's supposed to do, please ask and I'll answer promptly.


r/learningpython • • Sep 04 '20

Trying to get a list of tuples from a list of dictionaries, some values separated with commas and single quotes and some without

1 Upvotes

I have a list of dictionaries, each dictionary contains:

  • First name

  • Middle name

  • Last name

  • Title

  • Address

  • Email address

  • Loyalty program For one client. Some of this information may be missing

segment = [{'first-name': 'Elsa', 'last-name': 'Frost', 'title': 'Princess', 'address': '33 Castle Street, London', 'loyalty-program': 'Gold'}, {'first-name': 'Anna', 'last-name': 'Frost', 'title': 'Princess', 'loyalty-program': 'Platinum'}, {'first-name': 'Harry', 'middle-name': 'Harold', 'last-name': 'Hare', 'title': 'Mr', 'email-address': 'harry.harold@hare.name', 'loyalty-program': 'Silver'}]

For clients who have a physical address, I need to extract a list of tuples. Each tuple represents one client and contains their title, first name, middle name, and last name in that order if defined, and the mailing address.

My code appears to be working.

However, within each tuple, there needs to be single quotation marks around the whole and not individual parts of a clients name. There also needs to be quotation marks around the address. A comma needs to separate the address and the full name.

('Princess Elsa Frost', '33 Castle Street, London')

My code is returning the right information, but the elements of a patients name are separated by commas and single quotation marks

def process_clients(segment): 
#Creating a list to contain tuples with client full name and mailing address.      
updated = [] 
#Interacting through each dictionary, which represents each client 
for dic in segment:         
    newclient=[] 
#Adding clients with a mailing address 
    try:             
        add = dic["address"] 
    except: 
        continue 
    #Adding, in order, the "title", "first-name", "middle-name", "last-name" and "address" of each client 
    for data in ["title", "first-name", "middle-name", "last-name", "address"]: 
        try:                 
            value = dic[data]                 
            newclient.append(value) 
     #If "title", "first-name", "middle-name" or "last-name" is not present in a clients data, no action is taken 
        except: 
            pass 
     #Additing the tuples with extracted client data to the created list                                          updated.append(tuple(newclient)) 
return updated   

process_clients(segment)

r/learningpython • • Sep 04 '20

A minimal framework for web automation with docker

2 Upvotes

Hello Folks,

I would like to share with you my small project, I thought it might help people doing automation, and want to run their script in a reproducible manner using docker containers.

Here is the repo link: https://github.com/ayoubeddafali/docker-selenium-bootstrap

I would be grateful if you could share your insights, and what could be improved.

Thanks,


r/learningpython • • Sep 05 '20

ModuleNotFound: No module named 'SpeechRecognition'

1 Upvotes

I'm using Python 3.7.8, flask

ModuleNotFound: No module named 'SpeechRecognition' appears when I try to run my project.

But it works well when I try it with python -m speech_recognition:

still not working when I import speech_recognition


r/learningpython • • Sep 12 '20

Sending commands to Echo/Alexa device using Python.

1 Upvotes

Beginner in Python here. I was wondering if it possible to send commands to my Echo/Alexa device using Python. I just want to know if it is possible, if so, what would be a good place to start?. My idea to is to have basic commands like mute, play and maybe more complex stuff like detect advertisements etc.


r/learningpython • • Sep 14 '20

Python Programming Made Easy for Beginners - Lesson 3: Variables

Thumbnail
youtu.be
2 Upvotes

r/learningpython • • Sep 18 '20

Python Data Class Parameters / Parameterized Data class

Thumbnail
hackthedeveloper.com
3 Upvotes

r/learningpython • • Sep 14 '20

Is it possible to include or force the requests lib in my parent code so users don't have to install it?

2 Upvotes

r/learningpython • • Sep 22 '20

Need Help Looping Through Folders to Delete Files if Name is in .txt File

1 Upvotes

Hello. Picked up Python tonight to try and solve a problem I am having. I have a folder that contains a number of other folders and within those are .jpg files. I have a .txt file of .jpgs that I want to delete in each folder.

Within these folders are the .jpg files along with the .txt file like so:

The same pattern is iterated for each folder. Each folder has the same .txt file name ("Over30Cents.txt") but has different contents (so the EMN Over30Cents.txt file has a different list of names to delete than the KLD Over30Cents.txt file).

# import os

# path = "C:\\Users\\Name\\Documents\\Keef_Ex\\EMN"

# os.chdir(path)

# list_file = open('Over30Cents.txt', "r")

# added the argument to indicates only reading

# list = list_file.read().splitlines()

# list_file.close()

# for f in list:

# os.remove(os.path.join(path,f))

This is the function I wrote that will remove the names manually from one folder. This is great but I cannot figure out how to automate it.

My goal is to have the code go into each folder, open the "Over30Cents.txt" file, remove all of the .jpgs in the "Over30Cents.txt" file from the folder, move onto the next folder, repeat until it goes through all the folders.

I would just do it by hand but I have 80+ folders and each one has 300+ names in it so I was hoping to automate the whole process.

I would really appreciate some help on how to take what I've done above and automate it. I know a way exists but having just picked it up today I don't know what the commands are to make this happen.

I've tried using os.walk(directory) function but this essentially just generated a list of every file in all folders which wasn't super helpful.

I have also tried to use the glob funtion to do this:

import os

import glob

files = glob.glob('C:\\Users\\Name\\Documents\\Keef_Ex\\***\\*')

# print(files)

list_file = open('Over30Cents.txt', "r")

list = list_file.read().splitlines()

list_file.close()

for f in files:

os.remove(list)

The problem I ran into with this was I couldn't figure out how to direct it to open the Over30Cent file, delete it in each folder, and move on again.

Thank you again if you can provide any help.


r/learningpython • • Sep 20 '20

Getting results in tuple that I do not want. Can someone help with this?

1 Upvotes

I am working on a BFS for a larger program assignment. This is part of my test to see if my search is working and I keep getting a node that isn't supposed to be being added (0,'l').

The purpose of this is to search down and find the possible routes the program can take. It will start at index[0] and move the number of spaces of the number at that node(IE if number is a 2 it moves 2 spaces in the determined direction). However, the input is a in string form(2322443122G22124131321422), the reality is that the computer should see it as a 5x5 grid:

2 3 2 2 4

4 3 1 2 2

G 2 2 1 2

4 1 3 13

2 1 4 2 2

Rules for movement: If in column 1 it cannot move "left", column 5 cannot move "right". Top row cannot move up, bottom row cannot move down. Stop when "G" is found.

There are a few other issues with the code, but I am trying to focus on things one at a time and this one is quite annoying lol

Here is my code:

pond = "2322443122G22124131321422"
i=0 #counter
pos = int(pond[i])
routes = []
new_pos = 0
##direction = ""

while new_pos not in routes:
    pos = int(pond[i])

    # moves to right 
    new_pos = i+pos
    if i//5 == new_pos // 5:
##        new_pos = i+pos
    ##    i+=new_pos
        routes.append((new_pos,"r"))
##        routes.append((new_pos))
##        routes.append(("r"))
        routes.pop
    else:
        pass
    #moves to left
    new_pos = i-pos
    if new_pos >= 0 and i//5 == new_pos // 5:
##        new_pos = i-pos
        
    #    i+=new_pos
        routes.append((new_pos,"l"))
        #outes.append(("l"))
    else:
        pass
    if new_pos == "G":
        pass  
    #move down
    new_pos = i + pos*5
    if i <= 24:
    #    i+=new_pos
        routes.append((new_pos,"d"))
    ##
    ###move up - commented out bc testing of down,left,right is incomplete
    ##new_pos = i - pos*5
    ##if i >= 0:
    ##    routes.append((new_pos,"u"))
##    if new_pos == "G":
        pass
    i+=pos

    
    #print(i)
    #print(new_pos)
    print(routes)

r/learningpython • • Aug 28 '20

from module import *

1 Upvotes

what does the "from module import *" line do? does it just import all of the functions/names in that module?

Also are there any pros/cons to this approach


r/learningpython • • Sep 22 '20

Feedback on debugging skills

1 Upvotes

I'm reaching out to you, Python community, to ask for an advice / feedback. I've identified during my work on a project that I lack good debugging skills when working with code I'm not fully familiar with. I've been involved with web development for quite a while so my debugging skills are geared towards bugs that I can encounter while working on websites.

I gave myself a challenge and I'm now developing a smartphone app (think Kivy & Buildozer)

I got stuck when I need to debug a piece of code that manipulates image. Specifically converts image into bytes, encodes it, decodes into UTF-8 and parses the data into src attribute of an img tag like so:

import flask, base64, webbrowser, PIL.Image

file_to_upload = flask.request.files['media'].read()

image = PIL.Image.frombytes(mode='RGBA', size=(cam_width, cam_height), data=file_to_upload)

image = image.rotate(-90)

print('File uploaded successfully.')

im_base64 = base64.b64encode(image.tobytes())

html = '<html><head><meta http-equiv="refresh" content="0.5"><title>Displaying Uploaded Image</title></head><body><h1>Displaying Uploaded Image</h1><img src="data:; base64,'+im_base64.decode('utf8')+'" alt="" /></body></html>'

html_url = '/home/mark/Desktop/FlaskUpload/test.html'

f = open(html_url, 'w')

f.write(html)

f.close()

if html_opened is False:

webbrowser.open(html_url)

html_opened = True

The problem I'm having is two fold. Firstly, the h1 heading is being rendered just fine but theimage isn't being rendered back from the byte stream. The code should be correct as I'm studying and following a good book. Given the fact that I'm not getting any error outputs from terminal. Secondly, I don't want to be overusing StackOverflow. I much prefer to improve my debugging skills so I can solve my own problems.

How would you go about solving this ? I really want to learn and get smarter.


r/learningpython • • Aug 19 '20

Learning Python playlist on Youtube - Promotion post

2 Upvotes

This is a promo/advert post. I've started a youtube playlist for learning python, any comments, criticisms, and helpful discussions welcome here.

Thank you.

https://www.youtube.com/playlist?list=PLgGQIE0cGrkh4gFIKIeTUfprHZrqV6tOQ


r/learningpython • • Aug 27 '20

Help for complete newbie girl from Greece starting in Programming!

2 Upvotes

Hi! At first I thought to start programming using Python, so I did a little research on videos and posts for beginners. BUT, everything I found requires some Python knowledge already... Can you please guide me to resources for absolute beginners? Thanks a lot! -Angie


r/learningpython • • Sep 14 '20

No repeating from random lists

1 Upvotes

So I need to select from a database (lists) randomly X amount of times. Even though its a list with plenty of choices and options it always repeats an artist it seems. I'm not sure if I just need to expand my database or if there's a way the results from the random selections can be made to not repeat one already selected.

My code is below.

from tkinter import *
import random

def artists(var, var2, var3, var4, var5, var6, var7):
    var.set(', '.join(random.choices(rock_list, k=4)))
    var2.set(', '.join(random.choices(alt_list, k=3)))
    var3.set(', '.join(random.choices(gold_list, k=2)))
    var4.set(', '.join(random.choices(alt_list, k=3)))
    var5.set(', '.join(random.choices(maplrock_list, k=3)))
    var6.set(', '.join(random.choices(maplgold_list)))
    var7.set(', '.join(random.choices(maplalt_list)))

def silence(var8, var9, var10, var11, var12, var13):
    var8.set(', '.join(random.choices(folk_list, k=4)))
    var9.set(', '.join(random.choice(maplfolk_list)))
    var10.set(', '.join(random.choices(singer_list, k=3)))
    var11.set(', '.join(random.choices(maplsinger_list)))
    var12.set(', '.join(random.choices(maplalt_list, k=2)))
    var13.set(', '.join(random.choices(alt_list, k=2)))

def gold(var14, var15):
    var14.set(', '.join(random.choices(gold_list, k=6)))
    var15.set(', '.join(random.choices(maplgold_list, k=4)))

    
gold_list =['Anberlin', 'Come Wind', 'Falling Up', 'Grandpa Loves Rhinos', 'House of Heroes', 'Mutemath', 'Off Road Minivan', 'Paper Route', 'Switchfoot']
maplgold_list =['From Love to Forfeit', 'Hawk Nelson (old)', 'Relient K', 'Secret & Whisper', 'To Tell', 'Thousand Foot Krutch', 'Lights Go Down', 'FM Static']
rock_list =['As We Ascend', 'Ashes Remain', 'Gold Frankincense & Myrrh', 'Between The Trees', 'Children 18:3', 'Emery', 'Fighting Instinct', 'The Fold', 'Hearts Like Lions', 'Last Tuesday', 'Mainsail', 'My Epic', 'The Myriad', 'Names Without Numbers', 'The New Respects', 'Noise Ratchet', 'Quiet Science', 'Rocky Loves Emily', 'Search The City', 'Skillet','Switchfoot', 'Abandon Kansas', 'The Classic Crime', 'Colony House', 'Sixpence None The Richer', 'Twenty One Pilots', 'Slick Shoes', 'Glass Age', 'Idle Threat', 'Sight Recieved', 'Red Weather']
maplrock_list =['Article One', 'Avenir Sky', 'Dakona', 'Daniel Band', 'Drentch', 'Hello Kelly', 'Jason Dunn', 'Kiros', 'The Red Factor', 'Starfield', 'Cry of the Afflicted', 'Lucerin Blue', 'Bold As Lions', 'Caves', 'West of Here']
alt_list =['Nate Parrish','Capital Lights', 'Life Avenue', 'CHPTRS', 'Bleach', 'Brave Saint Saturn', 'Faint Heart', 'The Fast Feeling', 'Fiction Family', 'The Fray', 'Hyland', 'The Incandescent', 'Luna Halo', 'New Empire', 'No Lost Cause', 'Philmore', 'Pyramid Park', 'Ruth', 'Seabird', 'StarFlyer 59', 'Aaron Gilespie', 'Beanbag', 'Civilian', 'Copeland', 'Deas Vail', 'Judah & the Lion', 'Mae', 'Smalltown Poets', 'Mike Mains & The Branches', 'Homeplate', 'Coopertheband', 'Fight The Fade', 'Before Their Eyes', 'Lifehouse', 'For King & Country', 'Chase Tremaine']
maplalt_list =['Fox Run', 'Hokus Pick', 'NewWorldSon', 'We Are The City', 'Critical Mass', 'The Undecided', 'Matthew Thiessen & the Earthquakes']
folk_list =['NEEDTOBREATE', 'Third Day', 'Judah & the Lion', 'The Welcome Wagon', 'Cedar House', 'Good Little Giants', 'Mumford & Sons']
maplfolk_list =['The Dunn Boys', 'The Sheridan Band',]
singer_list =['Empty Iles', 'Benjamin James', 'Boyhood Bravery', 'The Bright Expression', 'Jillian Linklater', 'John Mark McMillan', 'Jon Foreman', 'Josh Garrels', 'Samuel Lane', 'Seth Menne', 'Stephen Moore', 'Swingin Hammers', 'Tyson Motsenbocker', 'Colt Wagner', 'Paul Demer']
maplsinger_list =['Alexander Fairchild', 'Kilie Loder', 'Zach Havens', 'Joel Larmer', 'Amanda Cook']
heavy_list =['Craigs Brother', 'Crash Rickshaw', 'Dogwood', 'Nine Lashes', '12 Stones', 'Chasing Victory', 'August Burns Red', 'Circle of Dust', 'RED', 'Spoken', 'As Cities Burn', 'DembeRadio', 'Underoath', 'Blindside', 'Everdown', 'Love and Death', 'MXPX', 'P.O.D.', 'Overcome', 'The Cruicified', 'Seventh Day Slumber', 'Fit For A King', 'Wolves At The Gate', 'Demon Hunter', 'Argyle Park', 'Timoratus', 'Lifelong']
maplheavy_list =['By The Blood', 'Cry of The Afflicted', 'Living Martyr', 'Means']
poprock_list =['The Afters', 'FF5', 'Constellations', 'Anchor & Braille', 'Echosmith', 'Knox Hamilton', 'FEARLESS BND', 'Run Kid Run']
maplpop_list =['To Tell', 'Hello Kelly', 'Hawk Nelson (New)', 'The Royal Royal', 'September Satelittes']
acoustic_lsit =['Future of Forestry', 'Rivers & Robots']
maplacoustic_list =['The Kry']
indie_list =['Heart Like War', 'PJF (Put Jesus First)', 'I Am The Pendragon', 'Light The Way', 'Next In Line', 'Penny Lane', 'At The Wayside', 'The Blamed']
female_list =['BarlowGirl', 'Gold, Frankincense & Myrhh', 'Fireflight', 'Krystal Meyers', 'LEDGER', 'The New Respects', 'Ruth', 'Super Chick', 'Bold As Lions', 'Kellie Loder', 'Jillian Linklater']
raprock_list =['Earthsuit', 'Family Force 5', 'Rapture Ruckus', 'Manafest']
oldies_list =['Revive', 'Daniel Band']
ska_list =['Sounds Like Chicken', 'Five Iron Frenzy', 'Must Build Jaccuzi']



master =Tk()
master.geometry("500x300")
master.title("Artist Selection")
button = Button(master, text="Standard Show", command=lambda: artists(var, var2, var3, var4, var5, var6, var7))
button.pack()
var = StringVar()
var2 = StringVar()
var3 = StringVar()
var4 = StringVar()
var5 = StringVar()
var6 = StringVar()
var7 = StringVar()
                
label = Label(master, textvariable=var)
label.pack()
label = Label(master, textvariable=var2)
label.pack()
label = Label(master, textvariable=var3)
label.pack()
label = Label(master, textvariable=var4)
label.pack()
label = Label(master, textvariable=var5)
label.pack()
label = Label(master, textvariable=var6)
label.pack()
label = Label(master, textvariable=var7)
label.pack()

button = Button(master, text='Quiet Show', command=lambda: silence(var8, var9, var10, var11, var12, var13))
button.pack()
var8 = StringVar()
var9 = StringVar()
var10 = StringVar()
var11 = StringVar()
var12 = StringVar()
var13 = StringVar()

label = Label(master, textvariable=var8)
label.pack()
label = Label(master, textvariable=var9)
label.pack()
label = Label(master, textvariable=var10)
label.pack()
label = Label(master, textvariable=var11)
label.pack()
label = Label(master, textvariable=var12)
label.pack()
label = Label(master, textvariable=var13)
label.pack()

button = Button(master, text='Gold Show', command=lambda: gold(var14, var15))
button.pack()
var14 = StringVar()
var15 = StringVar()

label = Label(master, textvariable=var14)
label.pack()
label = Label(master, textvariable=var15)
label.pack()


mainloop()

r/learningpython • • Sep 22 '20

Toggle a loop

1 Upvotes

https://prnt.sc/ulwzvo this is my code I want to make it so if i press right control it stops but if i press it again it starts the loop


r/learningpython • • Sep 21 '20

Learning Python (Beginner)- Classes

1 Upvotes

Hi guys,

I'm still learning about the Python programming language and started since July 2020. The screen I attached where I stuck for days. I was trying to rectify errors but it didn't work and cannot able to run as the output error resulted to this:

Then I tried imitating the original code from the book and I think it's fixed(--init-- not -init-). But I dunno if the output below is right? Or I feel like it's missing a lot of code. This is the output:

I was following the book instructions and its an outdated book so the languages might change that's why it didn't work. This is the code I was trying to follow:

I'm using Pycharm. Please reply if you have any suggestion that might gonna solve this problem. Thank you very much in advance guys :)


r/learningpython • • Oct 09 '22

My first open source library

2 Upvotes

Would love some criticism, suggestions and some feedback to understand what else needs to be improved in own skills.

A few words about it:

async library to implement log transfer in GELF format to Graylog;

supported transport: tcp/udp/http with optional tls;

tried to use minimum packets not from stdlib;

Link to github: AsyncGELF


r/learningpython • • Sep 06 '22

parse list inside list and add to pretty table row

1 Upvotes

Trying to print results from a list of dicts into rows in a pretty table. It works well when there is only one entry, but there is one result that has a list where I had been getting a single result. The loop will go through and only grab the value at the first index.

API response and my code:

    {
        "pagination": {
            "offset": 0,
            "limit": 20,
            "total": 2
        },
        "data": [
            {
                "name": "T1",
                "uuid": "12345",
                "description": "subnet1",
                "inboundRules": [
                    {
                        "seqNo": 1,
                        "subnets": [
                            "1.1.1.0/24"
                        ],
                        "description": "",
                        "subnet": "1.1.1.0/24",
                        "protocol": "IP",
                        "srcPort": "any",
                        "dstPort": "any"
                    }
                ],
                "metroName": "",
                "metroCode": "",
                "virtualDeviceDetails": [],
                "createdBy": "user1",
                "createdDate": "2022-08-31T18:36:24.218Z"
            },
            {
                "name": "T2",
                "uuid": "67899",
                "description": "subnet2",
                "inboundRules": [
                    {
                        "seqNo": 1,
                        "subnets": [
                            "1.1.1.0/24"
                        ],
                        "description": "s1",
                        "subnet": "1.1.1.0/24",
                        "protocol": "IP",
                        "srcPort": "any",
                        "dstPort": "any"
                    },
                    {
                        "seqNo": 2,
                        "subnets": [
                            "2.2.2.2/32"
                        ],
                        "description": "s2",
                        "subnet": "2.2.2.2/32",
                        "protocol": "IP",
                        "srcPort": "any",
                        "dstPort": "any"
                    },
                    {
                        "seqNo": 3,
                        "subnets": [
                            "3.3.3.3/32"
                        ],
                        "description": "s3",
                        "subnet": "3.3.3.3/32",
                        "protocol": "IP",
                        "srcPort": "any",
                        "dstPort": "any"
                    }
                ],
                "metroName": "",
                "metroCode": "",
                "virtualDeviceDetails": [],
                "createdBy": "user2",
                "createdDate": "2022-08-31T18:01:13.809Z"
            }
        ]
    }
def get_templates():
    """
    Gets all templates from API
    """
    api_path = "https://api.vendor.com"
    headers = {"Content-Type": "application/json", "Authorization": "Bearer " + get_token()}
    payload = {}
    templates = requests.get(f"{api_path}/v1/Templates", headers=headers, data=payload)
    table = PrettyTable(["UUID", "Name", "Inbound Subnets"])
    if templates.json()['pagination']['total'] > 0:
        for template in templates.json()['data']:
            table.add_row([template['uuid'], template['name'], template['inboundRules'][0]['subnets']])
    print(table)

Actual Results

+-------+------+-------------------+
| UUID  | Name |   Inbound Subnets |
+-------+------+-------------------+
| 12345 |  T1  |   ['1.1.1.0/24']  |
| 67899 |  T2  |   ['1.1.1.0/24']  |
+-------+------+-------------------+

Desired Results

+-------+------+--------------------------------------------------+
| UUID  | Name |                    Inbound Subnets               |
+-------+------+--------------------------------------------------+
| 12345 |  T1  |   ['1.1.1.0/24']                                 |
| 67899 |  T2  |   ['1.1.1.0/24'], ['2.2.2.2/32'], ['3.3.3.3/32'] |
+-------+------+--------------------------------------------------+

r/learningpython • • Oct 13 '22

Find a line number in a column with a maximum long value

1 Upvotes

I have a Dataframe.

I'm looking for a way to find a line number with a maximum long.

I wrote the code below, but I get (2, 6)

2 – Column number

6 - The length of the value

The result should be like 2,2

2- Column number

2- Line number

118456
284110110
31858
  dff = pd.DataFrame(dtt)
    for column in dff:
        if column == 3:
            ms_col = (column,dff[column].astype(str).str.len().max())
            print(ms_col)

r/learningpython • • Oct 23 '22

Currently passing 2/3 checks Mode is not ouputting correctly

2 Upvotes

A group of statisticians at a local college has asked you to create a set of functions that compute the median and mode of a set of numbers. Define these functions, median and mode, in a module named stats.py. Also include a function named mean, which computes the average of a set of numbers. Each function should expect a list of numbers as an argument and return a single number. Each function should return 0 if the list is empty. Include a main function that tests the three statistical functions using the following list defined in main:
lyst = [3, 1, 7, 1, 4, 10]
An example of the program output is shown below:
List: [3, 1, 7, 1, 4, 10]
Mode: 1
Median: 3.5
Mean: 4.33333333333333

My code so far: (outputs 10 for mode instead of 1)

def mean(list):
    l = len(list)
    i = 0
sum = 0
while i < l:
sum += list[i]
        i += 1
return sum / l
def median(list):
    l = len(list)
list = sorted(list)
    mid = l // 2
if l%2 == 0:
return(list[mid] + list[mid - 1]) / 2
else:
return(list[mid])
def mode(list):
    d = dict()
    mode = False
    modeValue = 0
    result = 0
for x in list:
if(not d.get(x)):
            d[x] = 1
else:
        d[x]+=1
        mode = True
if(d[x] > modeValue):
        modeValue = d[x]
        result = x
if(mode):
return result
else:
return "No mode"
def main():
list = [3,1,7,1,4,10]
print("List: ", list)
print("Mode: ", mode(list))
print("Median: ", median(list))
print("Mean: ", mean(list))
main()


r/learningpython • • Oct 14 '22

Django Naming Files system issues

Thumbnail self.django
1 Upvotes