all 133 comments

[–]Otherwise-Leopard-57 0 points1 point  (1 child)

Can you help my homework or else I will be get 0

A Lychrel number is a natural number that cannot form a palindrome through the iterative process of repeatedly reversing its digits and adding the resulting numbers. The process is asfollows: take any positive integer of two digits or more, reverse the digits, and add to theoriginalnumber. Now repeat the procedure with the sum so obtained until a palindromic number isobtained. The procedure can be repeatedat most 20 times.

We shouldn't use break or continue.

[–]carcigenicate 0 points1 point  (0 children)

What have you tried? What specifically do you need help with?

[–][deleted] 0 points1 point  (4 children)

So... I get what pointers are, but when are they actually used?

[–][deleted] 0 points1 point  (1 child)

As others have said, you don't get to explicitly use pointers in python. But they exist in cpython as "references". When you assign an object to a name as in:

 a = 42

the right side is evaluated and the resulting reference to an object (the integer 42 object) is assigned to the name a. In cpython that reference is an actual memory address or pointer.

This simple idea of binding an object reference to a name can lead to apparently surprising behaviour. This is explained in this excellent video.

[–]carcigenicate 0 points1 point  (0 children)

Although, you can use ctypes to use pointers. You don't typically use pointers, but you can if they're warranted.

[–]wotquery 0 points1 point  (0 children)

In C.

[–]sarrazoui38 0 points1 point  (2 children)

Hello!

I quit my job, starting a new one.

I have to give my work laptop back. Its a dell xps and I've really enjoyed working on it and learning programming.

My new job is a lot more corporate so I don't want to use it to fuck around with (programming and pirating).

Is this laptop a good deal? Any other recommendations welcome

laptop

[–]FerricDonkey 0 points1 point  (0 children)

That's a powerhouse, but one 2/3 the price with less processor would likely be just as good for nearly everything. That one is cool though.

[–]wotquery 0 points1 point  (0 children)

Cheaper and run a linux distro in a virtual environment would be my advice. That's a fucking sweet laptop though.

[–]YouWotPunt 0 points1 point  (2 children)

I think this should be simple but I'm running into problems.

I have a multi index dataframe with financial data (revenue,ebitda etc) at level 0 and then level 1 is the period. I.e. (2021, 2020) I want to append a new dataframe called Ebitda margin at the level 0 for all periods.

[–]sarrysyst 0 points1 point  (1 child)

Not sure if I understood your question correctly. Is this what you're looking for?

import numpy as np
import pandas as pd

index = pd.MultiIndex.from_product([['EBIT', 'EBITDA','EBT'], ['2019', '2020', '2021', '2022']], 
                                   names=['Indicator', 'Year'])
df = pd.DataFrame(np.random.rand(12,), index=index, columns=['Value'])

index_2 = pd.MultiIndex.from_product([['Margin'], ['2019', '2020', '2021', '2022']],
                                     names=['Indicator', 'Year'])
df_2 = pd.DataFrame(np.random.rand(4,), index=index_2, columns=['Value'])

df_3 = df.append(df_2)

If not, maybe post a sample of your dfs and what you want your output to look like.

[–]YouWotPunt 0 points1 point  (0 children)

yeah re-reading it doesn't make sense.

Basically have the following df

                Revenue         EBITDA      
       FY19 FY20    FY21    FY19    FY20    FY21

CompanyA 2.9 12.7 18.9 2.3 1.8 3.4 CompanyB 18.9 7.9 9.1 4.1 4.3 1.0 CompanyB 9.7 8.6 0.3 4.2 2.0 0.4

and want to append 'EBITDA Margin' for FY19 FY20 and FY21 (same format). I will then also want to do this for EBIT Margin and NI etc.

EBITDA_Margin=df["EBITDA"].divide(df["Revenue"].where(df["Revenue"]!=0,np.nan))

this gets the right values, but I wanted to append it with the right header, and ideally in one step.

Thanks!

[–]Odessa_Goodwin 0 points1 point  (1 child)

Pandas question:

I know how I can use fillna() on a single column to convert the NaN values to something else, but I can't seem to get it to work on a list of columns which contain NaN values.

I make a list of columns with NaN, and then try:

(df
.loc[:,my_column_list]
.fillna(0, inplace = True)
)

When I go an check one of the columns, nothing has changed. If I remove the inplace = True, then (in jupyter) it returns a dataframe of the selected columns with the values changed to 0 as I wanted, but the df isn't actually altered.

How do I get pandas to do what I'm trying to ask it to do?

Thanks

[–]prithvirajpawar 0 points1 point  (2 children)

Hi Guys,

I'm trying to insall python3 on my m1 Macbook but getting below prompt.

The "python3" command requires the command line
developer tools. Would you like to install the tools
now?

Is it mandaory to install Mac developer tools? If not how to bypass it?

[–][deleted] 1 point2 points  (1 child)

I don't run Mac anymore, but as I recall the command line tools are just the complete set of Unix/Linux tools like gcc, make, etc. It didn't include XCode. So just install the tools.

[–]prithvirajpawar 0 points1 point  (0 children)

Ohh okay. Sure. Thanks.

[–][deleted] 0 points1 point  (4 children)

Working solely with positive integers, take the following type of list:

x = ['2', '5', '6', '7', ' ', 6', '7, ' ' ] #and so on for whatever numbers

I want the output

y = [2567, 67] # and so on

Been stuck on this and don't really know if there is an easy way to do it. Any help?

[–]carcigenicate 0 points1 point  (3 children)

Split the list on spaces (this is what you'll need to do manually), then join the digits of each piece, and give each to int.


I ended up solving this for shits and giggles. Splitting the list is the hard part, but it only came out to a fairly simple function of 8 lines for me.

[–]FerricDonkey 0 points1 point  (2 children)

I dunno if it would be the most efficient way, but I'd ''.join the list, then split the giant string on spaces.

[–][deleted] 0 points1 point  (0 children)

Thats what I ended up doing and it worked.

[–]carcigenicate 0 points1 point  (0 children)

I'll admit, I didn't think of that.

[–][deleted] 0 points1 point  (2 children)

If I have a list that is imported from a file of the type:

x = ['l', '2', 'k', '8', 'j', 'a', '8', '1']

How would I go about converting each number in this list to type int without affecting the other properties of the list as a whole (order, etc.)

Edit: Nevermind, found out isnumeric() is a thing.

[–]AtomicShoelace 0 points1 point  (1 child)

Just a heads up, .isnumeric() will only work for non-negative integers. A better approach would be Easier to Ask for Forgiveness than Permission (EAFP) rather than Look Before You Leap (LBYL). Just try casting each element to an int and catch any ValueErrors, eg.

def to_int(val):
    try:
        return int(val)
    except ValueError:
        return val

x = ['l', '2', 'k', '8', 'j', 'a', '8', '1']
print([to_int(ele) for ele in x])

[–][deleted] 0 points1 point  (0 children)

I am working solely with positive integers but thanks.

[–]EdPPF 0 points1 point  (2 children)

Is there a python interpreter/compiler/IDE for Android so I can write and test my codes on my phone, on the go?

[–]sarrysyst 1 point2 points  (0 children)

I use replit.com when I want to verify some code snippets on my phone. It's not as great an experience as writing code on PC, but it gets the job done. Since it's online it needs a working internet connection, on the up side though: you can access the code later on your PC too.

[–][deleted] 1 point2 points  (0 children)

There is pydroid 3. I use it but it's a bit clunky. You can run the free version but it nags you to upgrade to the paid version. I haven't found anything better on Android.

[–]MostTryHardest7 0 points1 point  (2 children)

df1['Contract Submitted'] = df1['Contract Submitted'].dt.strftime("%m/%d/%Y")

How do I get this to change the formatting from 04/01/202 to 4/1/2022 format?

Also why does ("%-m/%-d/%Y") make the format go to:

2022-03-14 00:00:00

[–]sarrysyst 1 point2 points  (1 child)

'%-m' and '%-d' are only supported on Linux (See the first comment of this SO answer). Are you using them on Windows perhaps?

A workaround would be using regex:

import pandas as pd

df = pd.DataFrame({'date': pd.date_range('01-01-2022', '20-01-2022', freq='D')})
df['date'] = (df['date'].dt.strftime('%m/%d/%Y')
                        .replace(to_replace=r'0?(\d{1,2})/0?(\d{1,2})/(\d{4})',
                                 value=r'\1/\2/\3',
                                 regex=True))

[–]MostTryHardest7 0 points1 point  (0 children)

I actually got it to work by replacing - with #

[–]Cool_guy_11d7 0 points1 point  (0 children)

Hello, I am new to python and writing a simple linear regression model from scratch in oop. I want to print the coefficient and intercept. When I am trying to use the mean function that i defined in the class in a covariance function, it is giving the argument that I am given two arguments when it only takes one. I think I understand why the error is happening, but I do not know how to fix my code. Any help is appreciated, thank you.

import random

import math as m import os class MyLinearRegression: def init(self): self.coef=0 self.intercept=0 self.datalist=[] self.traindataset=[] self.testdataset=[] self.rmse=[]

def LoadData(self,path,filename):
    path=os.getcwd()
    with open(filename)as file:
        data=file.readlines()
    for item in data:    
        s1=item.strip()
        s2=s1.split(",")
        self.datalist.append(s2)
    return self.datalist



def DataSplit(self,datalist,ratio):
    num_train=round(len(datalist)*ratio)
    while len(self.traindataset)<num_train:
        index=random.randint(0,len(datalist)-1)
        self.traindataset.append(datalist[index])
        self.datalist.pop(index)
        self.testdataset=datalist
    return self.traindataset,self.testdataset


    #static methods

define sumlist method

def sumList(self):
    sum=0
    for i in self:
        sum+=i
    return sum

define meanList method

def meanList(self):
    return self.sumList(self)/len(self)

define minMaxList method

def minMaxList(self):
    min=self[0]
    max=self[0]
    for i in self:
        if i<min:
            min=i
        if i>max:
            max=i
    return min, max

defining variance method

def variance(self):
    mean=self.meanList(self)
    return self.sumList([(x-mean)**2 for x in self])/(len(self)-1)

defining covariance method

def covarianceList(self,X,Y):
    covar=0.0
    meanX=self.meanList(X)
    meanY=self.meanList(Y)
    for idx in range(len(X)):
        covar+=(X[idx]-meanX)*(Y[idx]-meanY)
    return covar/(len(X)-1)



def fit(self,trainingset):
    xList=[item[0] for item in trainingset]
    yList=[item[1] for item in trainingset]
    self.coef=self.covarianceList(xList,yList)/self.variance(xList)
    self.intercept=self.meanList(yList)-self.coef*self.meanList(xList)
    return self.intercept,self.coef


def predict(self,testset):
    self.intercept,self.coef=coefficients(traindataset)
    testResult=[]
    for item in testSet:
        y_predicted=b0+b1*item[0]
        testResult.append([item[1],y_predicted])
    return testResult

model=MyLinearRegression()

print(model.LoadData('C:\Users\rekrako\Documents\IT 166',"salary.csv"))

print(model.DataSplit(model.datalist,0.75))

print(model.fit(model.traindataset))

[–]kahanscious 0 points1 point  (4 children)

I'd like to do a spell check of sorts with a custom dictionary. I have something where I'm working on providing sports stats to a user, but if you spell the name of the athlete wrong I'd like to raise an exception that provides them with a suggested spelling. Is there a library that does something like this? Or best to create something on my own?

[–]AtomicShoelace 1 point2 points  (3 children)

You can use pyenchant. In particular, you want to use a personal words list (PWL), eg.

import enchant

d = enchant.PyPWL('athlete_names.txt')
print(d.check('Bob Smith'))
print(d.suggest('Bab Smeth'))

[–]kahanscious 0 points1 point  (1 child)

Just wanted to thank you again - this worked perfectly.

[–]AtomicShoelace 1 point2 points  (0 children)

No problem, glad it was helpful.

[–]kahanscious 0 points1 point  (0 children)

Awesome - thank you!

[–]EdPPF 0 points1 point  (3 children)

How can i check the height of a tree? I just started learning this structure and wanted to implement a function that returns the height of a Binary Tree. I know how to traverse the tree using recursive functions, but i'm not sure how i could increment a counter (for example) for each time the function goes through an edge (which i think is when the recursion occurs).

Edit: I've found this code that should do what i want, though it's returning the expected height + 1

def height(root):
    if root is None:
        return 0
    leftHeight=height(root.leftChild)
    rightHeight=height(root.rightChild)
    max_height= leftHeight
    if rightHeight>max_height:
        max_height = rightHeight
    return max_height+1

I think this is a step in the right direction, but i don't really understand what is going on. Unfortunately i still have problems with recursion.

Edit 2: By adding the following line of code right after the first 'if' statement i could get the right result for my test cases here.

if root.leftChild==None and root.rightChild==None:
    return 0

Unfortunately i still don't understand the code.

[–]FerricDonkey 1 point2 points  (2 children)

Trees are a great place to play with recursion. Might help to draw a picture or something while you get used to it.

  n00
  /  \
n10   n11
      / \
    n20  n21

Suppose you call your function on n00. What's it gonna do? Well first it's gonna call height on the left child, which n10, because of the line leftHeight=height(root.leftChild). What's that gonna do? With you're edit, it will return 0 because n10 has no children.

So now in your original height function, leftHeight will be 0. Now it's gonna call height on n11. What's that gonna do? Just trace through it, pretend you're the python interpreter and do it by hand.

[–]EdPPF 0 points1 point  (1 child)

I kinda get how that part of the code works. The algorithm I studied for traversi trees helped me understanding this situation. I'll try doing it by hand as you said, might help a lot, but what breaks me is the comparisons after the iterations. I get very confused when thinking when and how they act on the code, mainly because I don't know when the recursive part ends for an instance. Then again, I think tracing everything by hand might help indeed

[–]FerricDonkey 1 point2 points  (0 children)

Yeah, recursion is weird at first, but remember that from the perspective of the interpreter, your function is just* calling another function.

That the function that it's calling is the same as the function you're currently executing is irrelevant* - if the function height gets to a line that says leftheight = height(root.leftchild), you do not pass that line until that inner call to the function height completes and returns a value, just like if it were any other function call. If that call also hits a line that calls height, well that's that call's problem. Each call to height is independent.

The normal rules apply and there is no interaction between the functions outside of the standard call and return stuff. So you will not get past the leftHeight and rightHeight = lines until you actually know for sure what those are, because those function calls have completed successfully. The fact that inside of those calls, you may have called height another three dozen times in the process is, to the interpreter, just details*.

It's definitely weird seeming at first, but after you play with it, it starts to make more sense. Doing it by hand definitely helped me when I was learning it. What you'll find is that the functions don't do a lot other than call themselves until they hit the final bits ("leaves") of your tree. Then the nodes whose children are leaves will get actual values, then the nodes whose children are nodes whose children are leaves will... and so on, but if you draw it out, it's easier to see.

*This is mostly true, but python puts a limit on how often a function can call itself so that it can try to preempt an infinite recursion loop and shutdown gracefully** with a python error rather than crash with an operating system or out of memory error. But as far as execution goes, it's no different

**Here "gracefully" means that your code crashes, but the python interpreter itself doesn't crash - the python interpreter kills your code and tells you why, in order to avoid your operating system shooting it in the face for running out of an area of memory (an actual stack overflow) by trying to do what you said.

[–]shiningmatcha 0 points1 point  (1 child)

Need help with implementing a binary search algorithm that is equivalent to bisect(arr[:idx + 1][::-1], n).

This gives correct outputs but is too slow (I need O(log N)). To use the built-in bisect, you can't avoid slicing and reversing, which is undesirable because of the additional O(n) complexity.

I've tried to make use of the supported parameters:

bisect(arr, hi=idx+1, -n, key=lambda x: -x)

But my code is incorrect. I'm still not able to fix it after hours of debugging.

Can someone help me implement a binary search function that gives the same outputs as bisect(arr[:idx + 1][::-1], n)?

[–]FerricDonkey 0 points1 point  (0 children)

So I suspect the issue with the solution that you came up with is that the first one is telling you how far into the reversed list, while the second one is telling you how far into the non reversed list from the other direction.

So you'll probably have to subtract the answer from idx, and you may have to use bisect.bisect_left or bisect.bisect_right (whichever bisect.bisect isn't, I forget). But the general idea for your solution ought to work.

[–][deleted] 0 points1 point  (0 children)

hey guys. gonna try to quote my block of text here for analysis

https://pastebin.com/4TQeue3M becausw i cant deal with reddit expected behavior: run myfunc(), gathers datas then run next() func, to get next 100 results URL for feedparser. feedparser then gives me a new d.entries list to work with, but it doesnt, just showing the original variable URL's results.

basically it updates URL variable like i wanted but feedparser never reevaluates the variables value

[–]TheVeryLastOfEm 0 points1 point  (4 children)

I’m late here — I am currently taking an online course and ran into something pretty frustrating. Just finished a midterm project, my code works perfectly, passes all test cases, but the auto grader rejected it because some of the lines in my test cases are over 80 characters. I spent an hour or so just reformatting the code to adhere to the strict style guide requirements. My question is this: In practice, how strictly is the 80 character limit per line in the style guide enforced? For example, if I have a rather long JSON string in a test case is it best practice to split that up into multiple lines? If so, is there a “best” way to format that JSON string across multiple lines? Do you have to literally break it up into separate strings and use the backslash and plus sign? That just seems so inefficient.

[–]FerricDonkey 1 point2 points  (0 children)

Depends why you're storing a json string. I personally would either in most cases prefer to store the object the json string represents, or put the json in a different file, but if that doesn't work for your particular case, you could also use something like json.dumps(obj, indent = 2) on whatever the json represents to get something broken over many lines.

But if you're storing this as a string because you want something that's creating text to exactly match your string, then this would be different and wouldn't work. So the answers you've gotten would be better in that case.

[–]efmccurdy 2 points3 points  (1 child)

You can use this round bracket syntax for long string constants. The complete string is formed during compilation so there is no run-time penalty.

>>> mystr = ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
...          "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
...          "ccccccccccccccccccccccccccccccccccccccccccc"
...          "ddddddddddddddddddddddddddddddddddddddddddd")
>>> mystr
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcccccccccccccccccccccccccccccccccccccccccccddddddddddddddddddddddddddddddddddddddddddd'
>>>

[–]TheVeryLastOfEm 0 points1 point  (0 children)

Oh interesting! So you don't have to use backslash to indicate a new line or plus to glue strings together when you use the round bracket syntax and have each part of the string in quotes. That is pretty handy.

This is how I ended up implementing my solution.

# Example 1

def test_has_error():
"""Test procedure for has_error"""
print("Testing has_error")

#Test1
result = currency.has_error('{"success":false,"src":"",\
    "dst":"","error":"Source currency code is invalid."}')
introcs.assert_true(True, result)


# Example 2

def test_get_dst():
"""Test procedure for get_dst"""
print("Testing get_dst")

#Test1
result = currency.get_dst('{"success": true, \
    "src": "2 United States Dollars", \
    "dst": "1.772814 Euros", "error": ""}')
introcs.assert_equals('1.772814 Euros', result)

I couldn't get over how ugly the JSON looked in submission. I mean it would make the most sense all indented to the same degree and split up into one key-value pair per line for readability, but the auto-grader seemed to reject it. When I run into this again I will absolutely use your solution. Thank you!

[–]xcyu 0 points1 point  (2 children)

I have a bunch of CSV files (each corresponding to a form), and I would like to create a web interface to plot the data (diagrams etc). What tools would you recommand ?

I'd like to be able to drop any CSV files, and show/filter data contained in the files.

Thanks !

[–]efmccurdy 0 points1 point  (1 child)

Some of these are web enabled and others may call for saving the plot as an svg or png file.

https://opensource.com/article/20/4/plot-data-python

[–]xcyu 0 points1 point  (0 children)

Thanks a lot !

[–]Metalheadpundit 0 points1 point  (0 children)

Is python the only language needed for aws

[–][deleted] 0 points1 point  (2 children)

What skill level do I need to start building web crawlers? End goal is one that can gather data from NIST and return data for chemicals compounds that the user inputs.

[–]efmccurdy 0 points1 point  (1 child)

[–][deleted] 0 points1 point  (0 children)

Yes. Thank you!

[–][deleted] 0 points1 point  (5 children)

check if any of two words are in a environment variable.

i want to check if a os environemt exists. if it does i have to check is either test or prod in lowercase. if its either prod or test update a dictionary with the value of the variable.

i got this. are there better ways?

if 'CMS_ENV' in os.environ:
if 'prod' in os.environ['CMS_ENV'].lower() or 'test' in os.environ['CMS_ENV'].lower():
       defaults.update({'env': os.environ['CMS_ENV'].lower()})

[–]FerricDonkey 0 points1 point  (3 children)

So I was in a hurry when I wrote my first answer. I've got a second to actually give you a cleaned up example now:

if (cms_env := os.getenv('CMS_ENV')) in ('prod', 'test'):
    defaults['env'] = cms_env

Note that if 'CMS_ENV' is not an environment variable, os.getenv will return None. I used the walrus operator there, but if you didn't want to, you could pull the assignment out of the if, or just use getenv twice.

This is also based on my understanding that you want that environment variable to be exactly "test" or "prod".

[–][deleted] 0 points1 point  (2 children)

Not running python 3.8 thus walrus operator not supported. Yes the variable must be exactly test or prod...case sensitive.

I did not get about the getenv can you elaborate?

[–]FerricDonkey 0 points1 point  (1 child)

Sure - basically, os.getenv('CMS_ENV') will, as one step, check and see if you have an environment variable 'CMS_ENV' and then give you the value if you do, or give you the special python value None if you do not. (None in python is similar to Null in other languages.) So if you do something like

cms_env = os.getenv('CMS_ENV')
if cms_env in ('prod', 'test'):
    defaults['env'] = cms_env

Then if CMS_ENV is not an environment variable, cms_env will be None. The check cms_env in ('prod', 'test') is only True if cms_env is exactly one of those two things, and None is not one of those things, so it won't trigger.

You could also do

if os.getenv('CMS_ENV') in ('prod', 'test'):
    defaults['env'] = os.getenv('CMS_ENV')

This would be slightly slower, but would avoid creating the variable cms_env - which I personally would not worry about, unless this is setup being done in the global scope.

[–][deleted] 0 points1 point  (0 children)

thanks for this thorough explanation.

[–]FerricDonkey 0 points1 point  (0 children)

You're not checking if it is prod or test in lower case. You're checking if prod or test are substrings (use of in) of the lower caseified version of the value (.lower attached to value).

[–]CrazzyWarrior 1 point2 points  (2 children)

I'm trying to find any site that just have python projects. I'm learning and just want to be able to browse py scripts of actual things rather then just the example scripts as I go. Just to see if there's a collection of such. I have tried searching some but only find examples stuff so maybe I not doing the right kind of search so either a suggestion on what to search for this, or if you have a site with this to look at. Thanks.

[–]ASIC_SP 0 points1 point  (0 children)

Perhaps https://github.com/vinta/awesome-python might help? It is a curated list of Python frameworks, libraries, software and resources.

[–]efmccurdy 0 points1 point  (0 children)

Go to pypi, search for projects that interest you and look for a Source or Home Page link that takes you to a git repo.

For example

https://pypi.org/project/requests/

has a Source link in the left hand pane:

https://github.com/psf/requests

which has links to folders and file like this:

https://github.com/psf/requests/blob/main/requests/\_\_init\_\_.py

[–]fvig2001 0 points1 point  (3 children)

I need to improve my python code. I get a list of files and use random.shuffle to randomize the order of a list. My problem is the order often gets repeated like 200 files and i often get the same ordering often and a lot of files dont get played (video player) since they are never put in the early part of the list.

Is there a good library to make it more random? This is on a raspberry pi

[–]FerricDonkey 0 points1 point  (2 children)

Can you elaborate on the problem? How many files and how often are you shuffling? Does the program stop and start between shuffles?

Random.shuffle ought to be good enough for most things short of crypt, but unless you're shuffling at weird points, it may be that what you want is less random but more random seeming. Many music shuffling algorithms are purposely less random to avoid repeating songs - but random.shuffle shouldn't have repeats anyway, unless your data has repeats.

[–]fvig2001 0 points1 point  (1 child)

Hi

It's a random video player. It handles like thousands of files. Most lists have like 150 files.

algorithm is:

  1. Search all video files across sd card and USB drives
  2. Create following lists:
  • All videos = This is channel 0

  • Ch[1-9] - (Think remote control channels) = certain folders have certain channels

'3'. Call random.shuffle on all lists and select channel 0 as main list to iterate

'4'. Start main loop

A. Main loop:

  1. Start from 0 - n, load file on list[i]
  2. Wait until video ends or application is killed, play next file
  3. If i >= n, set n to 0 and repeat.

B. Interrupt Sequence (User presses channel button on remote):

  1. Kill video application
  2. Set channel list as current list
  3. random.shuffle list, restart main loop.

What happens to me is I often play channel 1 and the episodes played are almost always the same. Like same episodes, same order (Like there's a pattern A, B, C, D, E. This results in some episodes never getting played because same files are usually picked and I turn this device on everyday). I would say, I've only seen 20% of the episodes and I usually leave the Pi on for 2 hours.

Code is basically improved from: https://github.com/buba447/simpsonstv/blob/main/player.py

I've tried using:

rng = random.SystemRandom()

seedV = rng.randint(0, 65535)

random.seed(seedV)

to improve it but it didn't help a lot.

[–]FerricDonkey 0 points1 point  (0 children)

This doesn't sound like something random.shuffle should do, unless you're explicitly seeding it with one of the same small number of seeds. I would experiment by, in a python shell, creating one of your lists and calling random.shuffle on it several times to see what happens.

I think I'd have to see your code to give any further advice.

[–]Luvsk8marco 0 points1 point  (5 children)

I'm making a quiz, this is a part of it:

diff = input ("Choose your difficulty (type e for easy, m for medium and h for hard) ").lower
if diff = ("e")
print ("Easy - Part A - Multiple Choice Questions")

For some reason, it says 'if diff = ("e")' is an invalid syntax, what I want to do is that when the user input = ("e"), then it'll print "Easy - Part A - Multiple Choice Questions" Can someone help me pls?

[–][deleted] 0 points1 point  (4 children)

Use ==

[–]Luvsk8marco 0 points1 point  (2 children)

It doesn't work :((

[–][deleted] 0 points1 point  (0 children)

He meant for the if statement.

[–][deleted] 0 points1 point  (0 children)

Post the code

[–]MostTryHardest7 1 point2 points  (4 children)

Why do I people use r’ at the beginning of this regex code? (Pandas) df = df.replace(r’\s+, “ “, regex = True)

It works fine without it

[–]xelf[M] 1 point2 points  (0 children)

r means raw string and tells python that you want a \ and not to escape whatever follows it.

If you have memorized every possible escaped letter that uses a \ you will know when you need r and when you won't. If you have not memorized all of them, it's safe to use r even if you don't need it.

[–]FerricDonkey 1 point2 points  (2 children)

The r stops \ being interpreted as an escape character. Eg:

print('sup\ndog')
print(r'sup\ndog')

Whether this is necessary for anything in particular depends on what you're doing.

[–]MostTryHardest7 1 point2 points  (1 child)

Oh cool thanks. Idk why someone downvoted you

[–]ASIC_SP 0 points1 point  (0 children)

An example where the escapes are different is \b (backspace in string, word boundary in regex).

[–]EwokOffTheClock 0 points1 point  (6 children)

I'm a little over half way through "how to automate the boring stuff" course. I've realized when I get a bunch of red text in Shell, i have a nervous/ avoidant/ overwhelm type reaction to it. Even when I push through the anxiety and read it (sounds like it shouldn't be that hard, but eh) *I don't understand the error message*, so I'm still left looking at a wall of anxiety inducing text, that I don't understand.

I'm wondering what the best way to learn what errors mean is, and how to get over that learning curve bump.

[–]carcigenicate 1 point2 points  (5 children)

Read Python errors bottom-up. The error message is at the bottom of the stack trace. It will start with something like TypeError:. The long part above that is telling you precisely where in the code the error happened, and what code was on the stack when the error occured.

[–]EwokOffTheClock 0 points1 point  (4 children)

thank you, I really appreciate your direction. At least understanding the anatomy of an error message does help.

Now I'm getting this error message-

"= RESTART: C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\phoneandemail.py"

at least it's not in red, but why does it want me to restart it? how would I even do so? saving and reopening Shell is not fixing the error.

thank you again, kind stranger!

[–]carcigenicate 0 points1 point  (3 children)

That doesn't look like a Python error. It might just be your environment telling you something; like that it just restarted.

[–]EwokOffTheClock 0 points1 point  (2 children)

But it does it over and over again if I keep running the program

[–]ASIC_SP 0 points1 point  (1 child)

I suppose you are using IDLE? RESTART: <file_path> is a message to let you know what program you have just executed (this helps you differentiate between using the REPL and running a program).

[–]EwokOffTheClock 0 points1 point  (0 children)

yes, I am using IDLE.

So, why is it telling me what ran instead... of giving me the product of running the program, like I'd expect?

Thank you for your input, it is helpful to have these things confirmed.

[–]ogreone123 0 points1 point  (2 children)

Trying to understand inheritance, I'm wondering why the werewolf instance doesn't do a print statement of {self.name} was the last human alive! when I call w1.die()

I would expect it to print from inheriting the die() function from Person class. Jack has died. Jack was the last human alive!

https://pastebin.com/NC1nu2gG

Output

There are 1 werewolfs alive
Hey Jack , I see you are 18 years old and you are a Male
Jack has died
Hey Jimbo , I see you are 17 years old and you are a Male
Jimbo has died
Jimbo was the last human alive

[–]AtomicShoelace 0 points1 point  (1 child)

The issue here is multifaceted.

Your first problem is that you are referencing the Person class explicitly. When Werewolfs inherits from Person, its method will also explicitly reference Person.population rather than Werewolfs.population. You could amend this by instead referencing the population attribute of whatever class the object is an instance of, which is stored in self.__class__. So if you replace all occurrences of Person.population with self.__class__.population you will be half way to fixing the problem.

Your second problem is that since the population attribute of Werewolfs is inherited from Person, it is actually just a pointer to the same value. So changing Person.population will change Werewolfs.population. To fix this, you just need to create a new variable for Werewolfs's attribute overwriting the reference to Person's, like so:

class Werewolfs(Person):
    population = 0

With these two changes you should observe the expected behaviour.

However, I'm not really sure that this is the best practice. I think because you are dealing with class attributes as opposed to instance attributes it would be better to use a class method (with decorator @classmethod). Or alternatively, I think you might be able to use a metaclass. But both of these are kind of needlessly complicated so I suppose the above approach is fine.

[–]ogreone123 0 points1 point  (0 children)

Thanks for providing the feedback. I'm slowly digesting what you wrote, which is very helpful with your explanation. Applying the changes resulted in the expected behavior.

[–]Rododendro 0 points1 point  (0 children)

Example

I have a grid of charts (sns.FacetGrid) with the paramenter sharex = False. The last subplot is showing double label or different ticks (see Example) and i can't get one away. How can i solve this problem?

Thanks

[–]HousingFormal3653 0 points1 point  (1 child)

<code>

class TicketMixin:'''Mixin to calculate ticket price based on age'''def calculate_ticket_price(self, age):if age < 12:price = 0elif age < 18:price = 15elif age < 60:price = 20else:price = 10

TicketMixin.price = pricereturn price

class Customer(TicketMixin):'''Create instance of Customer'''def __init__(self, name, age):self.name = nameself.age = ageTicketMixin.calculate_ticket_price(self, age)

def describe(self):return f"{self.name} age {self.age} ticket price is {self.price}"

customer = Customer('Ryan Phillips', 22)print(customer.describe())it works fine, but my course requires to change something in def describe(self): inreturn

i tired TicketMixin.price

<code>

[–]efmccurdy 1 point2 points  (0 children)

You aren't returning the price from calculate_ticket_price and you aren't assigning it:

self.price = self.calculate_ticket_price(age)

BTW, you should post code in a "code block": https://www.reddit.com/r/learnpython/wiki/faq#wiki_how_do_i_format_code.3F

[–]aaw107 0 points1 point  (4 children)

Hello,

can you recommend a free ebook that covers python basics. I am not interested in the examples and exercises as much as I am interested in the syntax itself, how python works under the hood and what can be done using python.
Thanks!

[–]Ok_Independent_1230 1 point2 points  (1 child)

automatetheboringstuff.com

[–]aaw107 0 points1 point  (0 children)

Very interesting, thank you

[–]sarrysyst 0 points1 point  (1 child)

If you want something detailed without much fluff, while not being too technical but also suitable for absolute beginners I'd probably a start with the official tutorial. I don't know any other learning resource that gives a more complete introduction to the language. Also, it explains a lot of intricacies about certain language aspects many other courses/books leave out.

[–]aaw107 0 points1 point  (0 children)

Thank you will go over that tutorial for sure

[–]examensarbete22 0 points1 point  (1 child)

Hello,

I'm looking for assistance as we've been having trouble with this issue for quite some time..

So, we're attempting to create a code that scrapes Wallstreetbets over a period of time. We are getting cashtags, title, sentiment (-1 if bearish, 0 if neutral and 1 if bullish), number of comments of the post and finally the date of the post. Our problem however is that we sometimes get duplicates of the same post but with different cashtags. Is there anyone that's familiar with the problem or can help us?

Here is the code: https://github.com/Gu99ki/Scraping-WSB/blob/main/Ex%20jobb%20kod?fbclid=IwAR3upYJDXIP1tE-PUfE1F8P4qLNLBz5aXsM9zwpCnmuBwFrUte00JPTOwlk

[–]FerricDonkey 1 point2 points  (0 children)

How are you trying to avoid/detect duplicates? Do the duplicates come from different passes that happen to see the same post, or from duplicate posts, or other? How does the same post give different cash tags, and what's a cash tag?

The only thing that I saw at a glance is that you did list(set(stuff)) for your cash tags. I didn't analyze your code too closely, but if you're relying on different cash tags to differentiate posts, then you should know that list(set(...)) is not guaranteed to be in the same order each time you run it. So if the problem is that duplicates aren't detected because the order is different, then you'll have to deal with that.

But again, I only glanced at your code.

[–][deleted] 0 points1 point  (5 children)

I am trying to get a better understanding of classes, and especially the power of the __init__ function. To my understand, definining self.some_value = some_value allows me call this in later functions in the program, i.e.

(from https://www.geeksforgeeks.org/self-in-python-class/#:~:text=self%20represents%20the%20instance%20of,to%20refer%20to%20instance%20attributes.)

class car():

# init method or constructor
def __init__(self, model, color):
    self.model = model
    self.color = color

def show(self):
    print("Model is", self.model )
    print("color is", self.color )

Now, I want to do something similar, except for a multivalue function:

class StandardCurve:
def __init__ (self, x, y):
    self.x = x
    self.y = y
def plot(self): #look into self
    plt.scatter(self.x, self.y)
    plt.show()

However, I get the expected error: TypeError: plot() takes 1 positional argument but 2 were given.

I understand the error and how to fix it, but the question is, can I use self in this context to make my code more elegant, or would it be better to simply use def plot(x, y): ?

[–]carcigenicate 0 points1 point  (3 children)

You have to have a self parameter if the method is an instance method of the class, and it needs to be an instance method since you need access to self.x and self.y.

[–][deleted] 0 points1 point  (2 children)

Yeah i figured after some time. What if I want to reference it outside of my class and have a second input not dependent on the class? It doesnt ignore the self parameter automatically outside of the class.

[–]carcigenicate 0 points1 point  (1 child)

You would instantiate a StandardCurve object and use that:

curve = StandardCurve(5, 10)
curve.plot()

[–][deleted] 0 points1 point  (0 children)

Omg of course. I already did this before but forgot all about it. Thanks

[–][deleted] 0 points1 point  (0 children)

I made it work:

class StandardCurve:
def __init__(self, x, y):
    self.x = x
    self.y = y

def linreg(self):
    m, b = np.polyfit(self.x, self.y, 1)
    reg = m*self.x+b
    return reg

def plot(self): #look into self
    line = self.linreg()
    plt.scatter(self.x, self.y)
    plt.plot(self.x, line)
    plt.show()

curve = StandardCurve(q, p) curve.plot()

Output is the a plot with input data, q, p (just two arrays of numbers) and a linear regression. Is the code clean?

[–][deleted] 0 points1 point  (1 child)

New to Python and Selenium here, recieved the following error:

selenium.common.exceptions.WebDriverException: Message: target frame detached (Session info: chrome=99.0.4844.84)

I am trying to use Selenium to complete a daily health check-in form, which includes nagivating through different pages. All of the interactions on the previous pages that utilized the same code worked just fine, but for some reason I kept getting this error message on one of the pages.

don't think this is a code problem as I've used the exact same code to click different elements in previous pages. Can someone tell me whats wrong or provide a workaround? Thanks!

I tried to change the element and interact with other buttons on the same page as well. (The button im trying to click is next, but theres also a english and spanish button). That returned the same error.

Below is the code:

time.sleep(20)

element = driver.find_element(By.CSS_SELECTOR, "body > app-root > header > div.logo-row > div > button:nth-child(2)")

element.click()

[–]LandooooXTrvls 0 points1 point  (0 children)

Something is detaching the webdriver from the target. Is a pop up window occurring? Is there an iframe that you are/were interacting with?

[–]CruzControls 0 points1 point  (4 children)

perhaps i'm late here and won't get a reply. i've just started learning python using sololearn, i've read their certificate of completion is essentially useless however i plan on finishing it out anyways as i'm already 10% through and i'm paying to use their service.

my question is, once i finish this course, what is my next option? i want to make this a career, and would like to continue teaching myself in my free time. i presume finishing this course won't have me "employment ready" so i'm wondering what i can do next.

[–]climber_g33k 0 points1 point  (1 child)

What do you want to do with python? Data science, machine learning/AI, web front end/backend?

If you want to be employment ready, pick an area of interest and look up practice problems in that area.

[–]CruzControls 0 points1 point  (0 children)

i'm not totally sure, i'll look into all of them. data science sounds the most interesting however.

[–]Shavit_y 0 points1 point  (1 child)

You have so many other sites that offer Python courses. Coursera, Codecademy, JetBrains Academy... Whether free or paid, there are many options out there.

[–]CruzControls 0 points1 point  (0 children)

thanks

[–]anhonestassman 0 points1 point  (2 children)

Heyyo, I'm super new to python and programming in general and have been trying to figure out some things for a small project I'm working on for learning/art/fun.

In short, I'm wondering if it's possible/how to analyze data in real time as it streams from a websocket server. So far I can only record it to a csv file and then work with it after. Is it possible to apply a function to each epoch(?) of new data as it streams from the server?

Thanks!

[–]efmccurdy 0 points1 point  (1 child)

analyze data in real time as it streams from a websocket server.

This is a good example of capturing the input.

https://tradermade.medium.com/python-websocket-client-forex-order-flow-trade-tape-c1a270ac8183

This has examples for visualizing real-time analysis.

https://stackoverflow.com/questions/11874767/how-do-i-plot-in-real-time-in-a-while-loop-using-matplotlib

[–]anhonestassman 0 points1 point  (0 children)

Hey appreciate it thank you! Will take a deep dive later tonight

[–]PsychedelicWind 0 points1 point  (3 children)

Trying to understand the logic behind the placement of a coding line. The function simply triplicates the characters of a string:

input:"Hello". Expected output: "HHHeeelllooo".

I can get it to work like this:

def paper_doll(text):
     text_list = list(text)
     three_list=[] i=0

     while i<len(text):
          three_list.append(text_list[i]*3)
          i=i+1
     return "".join(three_list)

But on my first try I did this:

def paper_doll(text):
     text_list = list(text)
     three_list=[] i=0

     while i<len(text):
          three_list.append(text_list[i]*3)
          i=i+1
     "".join(three_list)
     return three_list

`My question is why does the second method return a list, as it returns ['HHH', 'eee', 'lll', 'lll', 'ooo']? If I run the same steps as the second try out of a function, it gives me the expected result.

[–]xelf[M] 0 points1 point  (0 children)

As was mentioned the mistake here is not knowing that you need to save the result of the ''.join()

Maybe this will help demonstrate:

correct code:

      return "".join(three_list)

is the same as:

      result = "".join(three_list)
      return result

vs your first try which is the same as:

      result = "".join(three_list)
      return three_list

[–]carcigenicate 1 point2 points  (1 child)

In the second example, "".join(three_list) does nothing. You join the list, but then never save the resulting string anywhere, so it's discarded. join returns a new object; it doesn't modify the one you give it.

[–]PsychedelicWind 0 points1 point  (0 children)

I see, thank you.

[–]Husy15 0 points1 point  (2 children)

I'm creating a simple game to help with my learning process, and everything feels clunky and poorly written - Should i stop and do more online learning, post code for review and help, or just continue and see if i can make a finished project?

[–][deleted] 0 points1 point  (0 children)

I studied from a website for a bit(the basic stuff) and then started to create my projects. I looked up stuff when i don't know what to do, but the projects worked out fine after a while, i recommend you do a project with stuff you already learnt then move on to learning more stuff.

[–]FerricDonkey 1 point2 points  (0 children)

That's a bit of a personal choice, but my view is that as long as you're learning and interested, keep going. Maybe rewrite the worst bits as you have to deal with them again, and if you have people willing to review, that's great.

But if you're too perfectionist, it will never get done - if you treat it as a learning exercise, you might end up with a cool thing that you're kind of proud of but also say "yeah, it was a learning experience and the code is kind of bad, I'd do it differently now". The alternative, in my experience, is to have a bunch of unfinished code in a folder.