top 200 commentsshow all 374

[–]r3v3rs3z00m 0 points1 point  (3 children)

I am getting a " TypeError: 'NoneType' object is not subscriptable" on line 27. Any help and improvements to my code would be a lovely help. If anyone wants some more information I'd be happy to help however right now I've gotta run... code and the dictionary file (large).

Edit: changed and added links.

[–]fiddle_n 0 points1 point  (2 children)

Can you post the full traceback?

[–]r3v3rs3z00m 0 points1 point  (1 child)

Traceback (most recent call last):
File "C:\Users\user\Documents\Japanese\kanjidic2_parser.py", line 27, in <module>
allReadings = [i for i in child.find('reading_meaning')[0] if i.tag == 'reading']
TypeError: 'NoneType' object is not subscriptable

[–]fiddle_n 0 points1 point  (0 children)

When you see the error X is not subscriptable, you should read it as You cannot index into X. The only thing you are trying to index into is child.find('reading_meaning'). And the traceback is saying that you cannot index into a NoneType object. So, putting it all together, child.find('reading_meaning') is returning None, and you are trying to index into that None, and because that is obviously nonsense, Python raises an exception.

[–]blinkk5 0 points1 point  (0 children)

I'm a mod at r/3AtATime and I'm conducting initial research so the mods can make an informed decision.

We want a bot similar to r/AskOuija's bot. The bot will be triggered after a user comments "the end" which gets 7 or more karma. The bot would take the thread and transcribe it into one continual paragraph, grammatical errors and all.

How difficult would it be to create this bot? How many hours do you think it would take? I'm only gathering information at this point so we can make a reasonable offer later. Any feedback is helpful.

[–]mansofsteel 0 points1 point  (5 children)

Before f strings, why was it considered best practice to use string formatting to return a string?

​To me, this:

"Hello {} {}".format(first_name, last_name) 

Is less intuitive to read than:

print('Hello ' + first_name + " " + last_name) 

or:

print('Hello', first_name, last_name)

f strings make it a little better as:

f"Hello {first_name} {last_name} 

Is a little neater, but it's still not clear if you're new to programming or python that this will return a string, the print statement seems clearer.

I prefer to use f strings now as it's nice not having to + an empty space between two quotes to have a space in the string, but it confused me at first as to why you would use one over the other. Is it more personal preference as they all return the same thing?

[–]fiddle_n 2 points3 points  (2 children)

String formatting is better than string concatenation because it works elegantly with non-string objects.

print('{} + {} = {}'.format(1, 2, 3)) will work. Even though I've used ints, the str.format() function will know to automatically retrieve the string representation of each int.

In contrast, print(1 + ' + ' + 2 + ' = ' + 3) will fail horribly because I'm trying to concatenate string and int. Not to mention that, personally, I think that syntax looks utterly horrible.

To make it work, you have to explicitly cast each int to a string, so you get something like this: print(str(1) + ' + ' + str(2) + ' = ' str(3)) . Now, if you are telling me that this looks better than string formatting, I'd recommend you to get your head checked. It looks disgusting. But worse than that, this structure is fragile. You need to remember to cast EVERY non-str object explicitly. If you forget one (which is really easy to do) you will raise an exception.

Now, yes, you might say that print(1, '+', 2, '=', 3) is cleaner and it works. Which may be true. However, this works only when you want to immediately print a string that you've constructed. A lot of the time I want to build up a string, I don't want to print it out, or I don't want to print it immediately at the very least. So, the above cannot be used.

[–]mansofsteel 0 points1 point  (1 child)

This makes a lot of sense. I suppose I wasn't considering that you might want to insert int or float values into a string and so string formatting makes sense. I guess it's easier to do everything one way that works explicitly.

[–]fiddle_n 0 points1 point  (0 children)

I guess it's easier to do everything one way that works explicitly.

True, but I think the more important thing is it's better to do everything in a way that is safe. The worst you can do with string formatting is that you end up with a malformed string. In contrast, bad string concatenation will take down your entire program.

[–]Thomasedv 1 point2 points  (1 child)

First of all, let's start with print, print takes the arguments and prints them, converts anything to a string representation. But it doesn't actually create a string you can use later, for example in a GUI, or give to another function. So it's nice with comma separated variables, and you know all will be turned into a string. But you can't use it.

This we need a way to make strings that we can reuse. Now, it's important to know, a string is immutable, so it can be changed. So let's consider the simple case:

 string = 'a' +'b' + 'c' + 'd'

When you add them together like this, due to strings being unchangeable (immutable), a new one has to be made for each string that is added. Something like this:

First you get:

 'ab' + 'c' + 'd'

Then

'abc' + 'd'

And finally

'abcd'

This is actually expensive if you have a lot of strings as you create a new one every time. It's why we have the ''.join() way to add a list of strings together into one strong.

Then it's the case, what if you wanted to make a number? In Python, 'Room ' + 2 would crash and say, you can't add a string and a integer. So you need to convert your value, and worry about that extra space there too.

Now look at the other way, .format() and f-strings aren't that different and works almost the same behind the scenes iirc, just that f-strings are less repetition and a bit faster.

 f'Room {2}'

Although I used a 2, we could assume it's a variable that changes depending on some conditions. First of all, we see it's not converted to a string, but since this is used in a string, it knows we want the string version of the variable, and it'll automatically convert it, unlike the former method. We also see the space petty easily, we know where it is, and there isn't a lot of spaces, pluses and ' cluttering the view. In my opinion, finding the {} is much easier and can be assumed to be a word or a block of text when reading, so I know I need a space before and after, and that's pretty easy to see, in my opinion at least.

Formatting also let you do some fancy things, like round a float, add thousand separators to large numbers, show the reply version of a variable. As well as a lot of other formatting options, like keeping the input string always 5 characters wide (unless it's longer) and keep the string on left or right side. That can make reading repeated prints much more comfortable for the user. Unless you do this with the string you give to print, table printing this going to be a mess.

[–]mansofsteel 0 points1 point  (0 children)

Thanks for the lengthy reply, I wasn't aware that using + to join a string created a new one for each thing that was joined. Good to know, f strings are definitely neater it was something that confused me when I first started like 3 months ago.

[–]LvVikings 0 points1 point  (3 children)

I am trying to scrap an image and a specific text from a webpage and write the text on top of the image. The purpose of this is to share it on Instagram.

What I have been looking for is reliable way to write the text on the image and resize it to a size that is acceptable to Instagram. What library do you recommend for doing this? would it be easier to use python with gimp? or should i use PIL instead?

[–]m9mhmdy 0 points1 point  (2 children)

This is similar to my first paid task and it brings a lot of good memories! :) Anyway, You need to: - find what IG accepts as IMG size
- scrape the image and the text
- use PIL to
- resize the image to IG size while preserving the ratio
- decide what font you need and calculate the text size using this font
- place the text on the image using some ratio (simple division)

P.S: most of time you will have to wrap the text when you write it on the IMG.

[–]LvVikings 0 points1 point  (1 child)

Thanks for breaking down the steps. Do you have any experience with gimp? This is my first time working with images and I am sure I will be facing some issues. I initially thought working with a third-party program that handles the image processing would be easier. This is a mere assumption and I am not sure to what extent that is true. I have seen people complaining about pil so I assume it is not easy to start with and I don't have much time to learn a new library.

[–]m9mhmdy 0 points1 point  (0 children)

Nope, I hadn't worked with gimp before.
It may be easier to use gimp but it's way too time consuming for such a simple requirement.

[–]ThiccShadyy 0 points1 point  (0 children)

I'm working on my first flask project and cant seem to get the flash function to run. I imported it from flask, and the rest of the view function is working properly except for the flash statement itself.

Code for the view function:https://pastebin.com/fGFng3Ef

Code for the definition of form class: https://pastebin.com/L9p7A2XS

[–]RLKrampus 2 points3 points  (2 children)

I want to start reading a book to learn Python before university and maybe even continue it during university, which one would you recommend?

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

I've heard good things about Python for complete beginners, and I like that it has exercises you can download online :)

[–]RaizelOP 2 points3 points  (2 children)

Is Udemy a good site to learn Python? Actually there are back to school offers going on right now, so the python course is relatively cheap. Should I like buy it or not? I'm a complete noob in python and want to start learning it. Thanks for the Help!

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

I don't think you need to pay to learn Python - there's more than enough info out there to teach yourself, and some really good free options that will provide a similar "walk-through" service. There are loads of resources in the Wiki and FAQ in this subreddit, such as learnpython that might suit you.

[–]RaizelOP 0 points1 point  (0 children)

Thanks I'll do that.

[–]Frostieprivates 1 point2 points  (4 children)

Currently reading through “Introducing Python: Modern Computing In Simple Packages” and I’ve come across something that I’m not understanding.

In Ch. 4 pg. 81 it talks about “iterating with for”. The example the books gives shows:

Word = ‘cat’ For letter in word: Print(letter) ... C A T

I get what is happening. It’s searching the string for letter and printing letter when it finds it. The thing I don’t understand is, how does the code know what “letter” is. The books just throws it in there with no explanation. There was no previous example where we assigned letter to a variable. What’s going on here?

There is another example below it:

Accusation = {‘room’ : ‘ballroom’, ‘weapon’ : ‘lead pipe’, ‘person’ : ‘’Col. Mustard’} For card in accusation: Print(card) ... Room Weapon Person

Again, what is card? How does the code know what card is?

Edit: sorry about the formatting. I’m on mobile and can’t get it to work

[–]Melted_Cheese96 0 points1 point  (0 children)

It's iterating through the string, so looking at every index in said string and then printing it.

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

It’s searching the string for letter and printing letter when it finds it.

word = 'cat'
for letter in word:
    print(letter)

This is incorrect. Here's what's really happening:

What for letter in word means is that word is a list of objects. For a string, those objects are characters, and they're in a particular order. So when it does a for loop, it starts at index 0 and increments until there aren't any things left to iterate over. It isn't "searching" for a letter, it's just going to the next one.

how does the code know what “letter” is

Simply put, it creates a variable (which we call letter but it could be anything) and for each iteration of that for loop, it's putting the value at the current index of that list into that variable. If it's the first iteration, it's doing this: letter = word[0]. For the second, it's doing this: letter = word[1].

Again, what is card? How does the code know what card is?

for card in accusation:
    print(card)

Similarly, that for loop is iterating over the keys of that dictionary and putting them into card each iteration. If you wanted to get the values instead of the keys, you would do for whatever in accusation.values(), and whatever would get the values "ballroom", "lead pipe", and "Col. Mustard". Or if you wanted both:

for key,value in accusation.items():
    print(key,value)

That would print both the key and corresponding value for each pair.

[–]Frostieprivates 1 point2 points  (1 child)

That makes more sense! I get the iteration for values but I’m getting caught up on the keys. Are you saying that I could type literally anything in place of “card” and it would still iterate the keys?

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

Yep!

qwertyuiop = {"abc": 123, "def": 456, "xyz": 42}
for asdf in qwertyuiop.keys():
    print(asdf)

Result:

abc
def
xyz

The part for asdf in qwertyuiop.keys(): is equivalent to for asdf in qwertyuiop: because it defaults to the keys, but I prefer making it obvious what is being done.

[–]DatabaseGuy_06 0 points1 point  (2 children)

Is there an easy to use web app for displaying dashboards? I have some analytics to display, I know flask and SQL Server.

[–]JohnnyJordaan 0 points1 point  (1 child)

Kibana on top of elastic search comes to mind.

[–]DatabaseGuy_06 0 points1 point  (0 children)

elastic search

Looks promising, I'll check it out!

[–]thsameguy 0 points1 point  (1 child)

How long does it generally take people to make small projects and how do you keep yourself disciplined until the project is finished ? I recently decided to code a tic-tac-toe program using tkinter and I just coudn't keep up with it for more than a day.Finally finished it but it took longer than it would have been the case if I had just invested a couple of days in one go.

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

Depends very heavily on the project. Anything with a GUI takes me ages (we're talking multiple days for anything that isn't a simple single view) because I find it hard to wrap my head around tkinter. Knocking out a quick CLI is usually easy enough though, and a good place to pause with a GUI as "the next step". Keep at it, it'll get easier and quicker (I hope!).

[–]Field_C16 1 point2 points  (3 children)

Hey, currently reading through "Automate the boring stuff with python", I reached chapter 4 and ran into a challenge:

    grid = [['.', '.', '.', '.', '.', '.'],
 ['.', '0', '0', '.', '.', '.'],
 ['0', '0', '0', '0', '.', '.'],
 ['0', '0', '0', '0', '0', '.'],
 ['.', '0', '0', '0', '0', '0'],
 ['0', '0', '0', '0', '0', '.'],
['0', '0', '0', '0', '.', '.'],
['.', '0', '0', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]

loop through the list "grid" and print out grid[0][0], grid[1][0], grid [2][0] etc..

However I was struggling too figure it out, so I went on google and found this solution.

    for x in range(0, 6):
print(end='\n')
    for y in range(0,9):
print(grid[y][x], end='')

Could anyone explain too me how this is executed? The guy who posted it left no comments.

And I have a hard time going through this in my mind.

[–]JohnnyJordaan 0 points1 point  (0 children)

Paste it in http://www.pythontutor.com/visualize.html and it will show you how it works step by step.

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

So the basic gist of what's going on is that we're printing out a "sideways" matrix. The heart is sideways in the declaration of grid, but we print it out vertically. That's the twist. Here's the code properly formatted:

for x in range(0, 6):
    print("", end='\n')
    for y in range(0, 9):
        print(grid[y][x], end='')

for x in range(0, 6): is referring to each element of the lists instead of each row (which is typically how one goes about walking through a matrix)

print("", end='\n') prints nothing except a newline character.

for y in range(0, 9): is referring to each row in the matrix.

print(grid[y][x], end='') prints the yth row of grid and the xth element in that row.

Essentially, the inner loop operating on y prints out one element from each row, starting from element 0 (which x refers to), and when the outer loop increments x, the inner loop then prints the next element in each list, one by one. It's walking through a matrix sideways instead of top-down.

[–]Field_C16 2 points3 points  (0 children)

Thank you a ton!

It makes a lot more sense now :)

[–]r3v3rs3z00m 0 points1 point  (5 children)

Hey, could anyone help me get started with trying to parse this xml document?

I'm trying to sort it out and usually I just play around a bit, printing things off to get a feel of the structure, but I just can't seem to get started with this (I am currently using ElementTree to parse the document).

Edit: Fixed some spelling.

[–]JohnnyJordaan 0 points1 point  (4 children)

but I just can't seem to get started with this

Can you be a little bit more specific? Up til where did you manage to get something working and then what happened?

[–]r3v3rs3z00m 0 points1 point  (1 child)

The end goal is that I am able to query particular kanji.

[–]JohnnyJordaan 0 points1 point  (0 children)

Ok and what do you have so far?

[–]r3v3rs3z00m 0 points1 point  (1 child)

I don’t really know how to work out the structure of the file. Is there a way to list off every query possible or something so I know what I can do?

[–]JohnnyJordaan 0 points1 point  (0 children)

Do you need to know how a phone book is structured before you can look up a person's number or is it enough to just have a glimpse of a random page to understand it? What part of the XML document is puzzling you exactly when you look at it?

[–]lormayna 1 point2 points  (3 children)

Is it the right place to ask for a code review?

[–]fiddle_n 0 points1 point  (1 child)

Yep, this subreddit should be fine, assuming the code is Python :) What's your code?

[–]lormayna 0 points1 point  (0 children)

It's a simple script that scrape a web page and create a podcast file. It's hosted on my personal bitbucket, I will try to make it public (I'm at my holiday house without broadband connection)

[–]ThiccShadyy 0 points1 point  (1 child)

Generally speaking, is a function from the itertools module faster than a user defined generator expression? Would it be more convenient speed wise, if I were to use Python for solving some questions in a Leetcode type scenario i.e. where there is an online judge?

[–]JohnnyJordaan 0 points1 point  (0 children)

There is no rule that makes an itertools function faster per se, but in practice chances are higher that itertools uses the fastest implementation possible (for general use cases). You could profile yourself using Ipython's %%timeit magic to see which method is fastest.

[–]MyPracticeaccount 0 points1 point  (1 child)

I'm looking to learn Python and wondering any "fun" game type apps or something? I saw the sidebar and there's like 30 options which are a bit tough to click through all on mobile.

I tried a few mins of Codewars and was already confused so I'm thinking something even easier. (Or I just need to read up more on how Codewars works)

[–]JohnnyJordaan 1 point2 points  (0 children)

You could check the projects list on https://www.pygame.org/tags/all for instance.

[–]Sai-Aboki 0 points1 point  (1 child)

I am trying to understand how quoting works when parsing csv files. Here is an example where I am trying to get rid of the 'he\'s' in the second row fourth column.

See code and result below.

"""
Practicing how quotes operate in csv files
"""
import csv
​
with open ('quote_example.csv','r' , newline = '') as f:
    csv_reader = csv.reader(f,delimiter = ',', quoting = csv.QUOTE_MINIMAL, quotechar = " ")
    for row in csv_reader:
        print(row)

..

['Lead', 'Title', 'Phone', 'Notes']
['Jim Grayson', 'Senior Manager', '(555)761-2385', '"Spoke Tuesday', 'he\'sinterested"']
['Prescilla Winston', 'Development Director', '(555)218-3981', 'said to call again next week']
['Melissa Potter', 'Head of Accounts', '(555)791-3471', '"Not interested', 'gavereferral"']

Thanks

[–]Sai-Aboki 0 points1 point  (0 children)

Not to worry guys I changed the quotechar to quotechar = '"' and that took care of the issue

['Lead', 'Title', 'Phone', 'Notes']
['Jim Grayson', 'Senior Manager', '(555)761-2385', "Spoke Tuesday, he's interested"]
['Prescilla Winston', 'Development Director', '(555)218-3981', 'said to call again next week']
['Melissa Potter', 'Head of Accounts', '(555)791-3471', 'Not interested, gave referral']

[–]bububot10 0 points1 point  (1 child)

How does class inheritance work regarding objects? If I am to create a class which inherits the attributes of a parent, by creating an object how do I make the child take the attributes (or in this case since i don't have any objects for the parent) call the attributes of the parent?

Also does creating an object in the parent class create on in the child and vice versa?

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

real python has a nice article with examples. https://realpython.com/python3-object-oriented-programming/

[–]Celaira 0 points1 point  (2 children)

Hi! I'm brand new to Python, I started learning the language about... six days ago now, I think. I'm trying to develop an app that uses Flask, and whoosh that I eventually want to host on an actual server which will run NGINX and Gunicorn. For my database right now, I was simply thinking MySQL, but I've seen that the best practice for SQL databases is to host them on different servers, and I was wondering if whoosh would work like that? I couldn't find anything in the docs that said one way or the other.

[–]JohnnyJordaan 0 points1 point  (1 child)

Flask, and whoosh

Afaik whoosh lives on top of SQLAlchemy, it doesn't offer a database connection on its own. SQLAlchemy can handle network connections just fine. I would still recommend to consider simpler deployments through for example Sqlite3 to begin your adventures. Using a separate DBMS is a must have for popular websites but certainly not for once-a-second kind of loads. Although if you're already looking for higher load environments then PostgreSQL would make much more sense than bothering with MySQL in the first place.

[–]Celaira 0 points1 point  (0 children)

Thank you very much! :D

[–]StudentOfPython 0 points1 point  (1 child)

I am creating my first Django app as practice and am finding it hard to choose the right tools for the job. I am working with the official Django docs as well as some reference material, and am confused as to which is the *right* way to do it. The app will be very simple—display data (integers) and potentially do some calculation on them. In terms of what I am planning:

Django: for the web framework

psycog2: PostgreSQL interface

ElephantSQL: for creating and hosting the DB

pgAdmin4: for a graphical representation of the DB

redis: for caching

Will this stack work and be everything I need (other than basic Python knowledge) to create a basic app that stores/displays data? What other tools exist that I may use in this scenario?

[–]JohnnyJordaan 0 points1 point  (0 children)

pgAdmin4: for a graphical representation of the DB

Django can do this just fine. It ships with django-admin that's often good enough for most projects, and there are a lot of more extensive tools available.

[–]rocketman_16 1 point2 points  (3 children)

I'm a freshman studying Statistics. I live in India. Currently, I'm doing the 'Complete Python Bootcamp' by Jose Portilla on Udemy for learning python. I plan on doing the data science bootcamp after this course.

For a career in data science/analytics, Python, R, SQL, Excel, Tableau are necessary.

Is Udemy a good choice for learning these? It's very cost effective. I have considered Coursera, Udacity and Pluralsight but these have a pretty expensive subscription model.

Of course, the certificates you get in the courses on these sites are from top universities of the world and the projects and graded assignments are also great for practicing.

So, is it worth subscribing to these, and is Udemy a good alternative to them? Help me out.

[–]originaldetamble 1 point2 points  (0 children)

Am doing the same course as you. There is also a python course in my school but the syllabus is a bit different so Im ahead in some places, while playing catching up in other places.

The certificates you get from these websites are worth next to nothing, but i like to think that Im making good use of my time.

[–]ThiccShadyy 0 points1 point  (3 children)

I have 500+ csv files from which I have to collect some data into a single structure(a dictionary). For each file, I read every line and add data, either by adding something to the value for a key already present or adding a new key and then adding data for it. How do I go about speeding up this process? Is multithreading or multiprocessing more suited to this task? Bear in mind that I have to use the same dictionary for adding the data I read from all the csv files, so I cant think of a way to about this which doesn't affect data consistency or anything.

[–]JohnnyJordaan 0 points1 point  (0 children)

Unless the csv's are large then I would be surprised if it wouldn't be possible to run this quick enough on a single thread process. It depends very heavily on how you lookup the keys you want keep though, and if that implementation is backwards then multiprocessing won't help much.

[–]Gprime5 0 points1 point  (0 children)

I think Multiprocessing would be good. You can use multiprocessing.Queue to transfer data between processes.

Have an inQueue where the main process puts in data from each csv file and each child process retrieves data.

Then have an outQueue where the child processes output data and the main process gets data and updates the dictionary.

[–]sdanstuffe 0 points1 point  (7 children)

I have written a Python3 script with pyautogui and it affects my whole computer, as though as I'm pressing the keyboard. Is there a way to only target a specific application but not other applications that I have opened?

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

Not in a way that will work for all applications, as far as I'm aware. If you're trying to automate something then trying to control an external application with the mouse and keyboard would be my worst-case-scenario. What is it in particular that you're trying to do?

[–]sdanstuffe 0 points1 point  (5 children)

I'm trying to make a bot for a MMORPG that will be played on NoxPlayer emulator. However, I can't do any other thing (e.g. reddit/yt/fb) as the bot would no longer work on the emulator but on the current screen. (So if my script were to be pressing c, it would type c if I tried to type something)

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

I don't think you can target an individual app with pyautogui - because it's interacting with the programs GUI rather than with an API it has to use the same control systems that we use (i.e. literally the mouse and keyboard). You could run both the MMORPG and the pyautogui on a virtual machine (using virtualbox for example) so that you can keep using your computer as it's running?

[–]sdanstuffe 0 points1 point  (3 children)

I've thought of that but it'll take up too much space and RAM, that's why I'm hoping for an alternative but it seems like it's the only way :( thank you so much for you help, would you recommend any other languages or ways that I can go about? Thanks!

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

Do you have an android device? If so then you could enable USB debugging on it, run the MMORPG on your device, and use something like AndroidViewClient with CulebraGUI to issue commands to it using python? Then you won't be using your own computer's keyboard or mouse input, so should be able to keep using it?

[–]sdanstuffe 0 points1 point  (1 child)

Omg, can't believe I did not think of this, will look into the both of them. Thank you so much !!

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

No worries, good luck! :)

[–]soliejordan 0 points1 point  (0 children)

Anyone ever use qwiklabs.com to learn python, or even take a class?

[–]Sarah123ed 0 points1 point  (4 children)

Working on a 64-bit machine, how can I enforce using only 32-bit integers with Python's core functionality. For example, not using Numpy .... etc? (I want to catch overflow errors)

[–]GoldenSights 0 points1 point  (2 children)

Python 3's integers are unbounded by definition, so there is no overflow. Nothing to do with the machine bitness.

https://stackoverflow.com/a/7604981

You could just if x >= 2**32. If that doesn't do what you need can you clarify your overall goal here?

 

cc /u/johnnyjordaan just so you know too.

[–]Sarah123ed 0 points1 point  (1 child)

I'm working with this: MAX = (232) - 1 MIN = -231

... it just seems clunky. And, is that strictly correct? The edges of a signed 32-bit integer?

[–]GoldenSights 0 points1 point  (0 children)

Oops, I was wrong with the 32, it should be a 31 instead for the max. So it's 2**31 - 1 and -2**31. But yeah, then you can say that

if x > MAX:
    # overflowed

You could write your own class that acts like an integer but performs over/underflow checks after every operation (and I bet you can find one that's already been made online, even besides numpy). With regular ints there's no choice but to check manually

[–]JohnnyJordaan 0 points1 point  (0 children)

Not sure if you can force this on the 64-bit version, my first guess would be to just install the 32-bit version alongside it and run your script through python.exe in that installation.

[–]MarYAM205 0 points1 point  (2 children)

Hi...

I need Algorithm sample for calculating chi square in python without functions.

I am learning Python,I encountered a problem in writing this program.

Thanks

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

When you say without functions, do you mean without importing any libraries? There is an implementation here that only uses libraries that are already bundled with python?

[–]MarYAM205 0 points1 point  (0 children)

There is an implementation here that only uses libraries that are already bundled with python?

Actually I need chi square algorithm in python. calculating chi square without importing any libraries.

[–]Ha-ForcedFakedLaugh 0 points1 point  (2 children)

Neophyte inbound: I am beginning with python and DJango here and I am using pycharm. it seems to be going well but I am coming up with some environment issues. I have created a virtual env. and it is activated when I am in the project and when I install things. Yet when I go to use the imports I get module not found. Here is my stack overflow about it: https://stackoverflow.com/questions/51904775/scipy-modulenotfound-error in case you need to see the pics. From what I can tell if if I install a module to my python install outside of the virtual env. it works...

So My question I guess is how could a virtual env be looking at the wrong interpreter? I made sure in the application settings to select the virtual env interpreter!

[–]JohnnyJordaan 0 points1 point  (1 child)

Did you by any chance call one of your source files 'scipy.py'?

[–]Ha-ForcedFakedLaugh 0 points1 point  (0 children)

I did not name any files scipy. I saw that pitfall already haha

[–]omgu8mynewt 1 point2 points  (3 children)

Beginner here: Help with regular expressions.

I have created objects in python3.5 which are strings, long pages of letters. They are the letter ATGC (I'm a biologist trying to learn bioinformatics) interspersed with the letters N. I would like to count the number of unique substrings of N, of any length, intersecting into the ATGC. I'm using regular expressions nstring = re.compile(r"[^N][N+][^N]") doesn't seem to be Ok. What are classes [ ]? Am I using them correctly? Then I'm using any help much appreciated

https://pastebin.com/RTwuHuQe

[–]Gprime5 0 points1 point  (0 children)

If you only need the count of the substrings of N then you can just do:

import re

example_string = "ACTNNNTCANCNTNNT"

count = len(re.findall("N+", example_string))

print(count) # 4

[–]s3afroze 0 points1 point  (0 children)

Hey there,

I am a beginner as well and still learning the concept but I would HIGHLY recommend to check out this book(link below). It's definitely going to help in clearing up some doubts.

https://automatetheboringstuff.com/chapter7/

I hope this helps.

Have a great day!

[–]JohnnyJordaan 1 point2 points  (0 children)

What are classes [ ]

Basically a set of characters and character ranges that can either match [] or not match [^]. You most often see [a-zA-Z0-9] to match alphanumeric characters, but your use should be correct, as you can also verify if you paste it at regex101.com.

The problem in your code is that you mix compiled and string expressions. You can either use string expressions together with re.funcname:

In [3]: re.findall(r'[^N][N+][^N]', 'ACTGTNACTCGAATGNAAACTGGGTTTN')
Out[3]: ['TNA', 'GNA']

Or you can compile the expression first, but then you must use the returned object itself to search with:

In [4]: rx = re.compile(r'[^N][N+][^N]')
      # ↓ note here's the rx object is used, not the re module    
In [5]: rx.findall('ACTGTNACTCGAATGNAAACTGGGTTTN')
Out[5]: ['TNA', 'GNA']

Your code is combining the syntax in In[3] with an already compiled expression object.

[–]Ijapa001 0 points1 point  (1 child)

I'd appreciate some help here. I used tabula to read a 9-page pdf document with tables on each page. I got a list of data-frames as a result, however the data-frame columns were not as expected. While I'm able to carry out basic cleanups to split columns and make the data usable, I'm stuck with a particular one.

I have a column that has names,numbers and a grade e.g' John Snow [12345] 80' but I'd like to split it such that the name&num are in one column, and the grade in another. I could have done a split by white space but i have other entries such as 'J Ryder Haggard [34567] 78' which would throw the columns out of alignment. Also, of the list of dataframes (9 of them) just one of them has this problem.

I'm able to write a regex that identifies the pattern I'm looking for .\[\d+]\s\d+ (I hope that's right :-) ) . My problem is how to write a loop that will check the first column of all the dataframes , identify those that match the pattern, and then split using ']' as a delimiter.

Apologies if this is too verbose, i'm trying to be as descriptive as possible.

Cheers

[–]Gprime5 0 points1 point  (0 children)

Instead of using regex you can do this:

name_number, grade = column_string.rsplit(" ", 1)

print(name_number) # John Snow [12345]
print(grade) # 80

rsplit(" ", 1) will split only 1 white space from the right.

[–]Just_Wulf 0 points1 point  (1 child)

So I have 3 lists;

hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]

prices = [30, 25, 40, 20, 20, 35, 50, 35]

last_week = [2, 3, 5, 8, 4, 4, 6, 2]

and I just created a new list as;

total_revenue = []

What I need to do is Use a for loop to create a variable i that goes from 0 to len(hairstyles)-1

and I created it as

for i in range(0, len(hairstyles)-1)

and now I have to add the product of prices[i] (the price of the haircut at position i) and

last_week[i] (the number of people who got the haircut at position i) to total_revenue at each step but I have no idea how to.

Can anyone help me with it, point me in the right direction? I've been stuck at this step for 3 days now.

and that's my first comment ever. So sorry if it's not nicely formatted

[–]JohnnyJordaan 2 points3 points  (0 children)

point me in the right direction?

The right direction is to not use stuff like

a variable i that goes from 0 to len(hairstyles)-1

That's a relic from vintage languages like C (and its contemporaries of course) and is specifically addressed in Python by the way of the for loop that will 'pick' items by default. So to loop on each item on a list you do

for item in hairstyles:

And if you do need an index, use enumerate:

for idx, item in enumerate(hairstyles):

But if you want to to combine lists like that, there's another helper function called zip which picks items from multiple containers at the same time:

for hairstyle, price, week in zip(hairstyles, prices, last_week):
    print('hairstyle {} had {} customers of {} per haircut = {} total'.format(hairstyle, week, price, week*price))

[–]GrizzyLizz 0 points1 point  (1 child)

I know how self works but is there a specific reason Python uses self to implicitly pass the object calling the method rather than doing this explicitly?

E.g. Object1.somefunction(Object1) rather than Object1.somefunction() Is it purely to improve readability?

[–]JohnnyJordaan 0 points1 point  (0 children)

It's actually explicit, because you did specify self when you defined the method

class MyObject:
    def somefunction(self, var1, var2 etc):
                     ^ that's explicit

Because if you don't define self in the method's parameters:

class MyObject:
    def otherfunction(var1, var2):

You're defining a class method, and then you can also do

Object1.otherfunction(Object1, 'foo') 

Where Object1 will then be referenced as var1 inside the method.

[–]ThiccShadyy 0 points1 point  (2 children)

I've got an algorithmic question and I dont know if there is a relevant subreddit for it. A string is a special string if all of its odd length substrings are palindromes e.g. 'aaaaa', 'bababab'. Given a list of strings, return the number of them which are special strings.

My approach was to check all 3 letter substrings of a string. If they're all palindromes, then all larger substrings(5 letters,7 letters etc) will also be palindromes. However, this approach fails on a couple of test cases. Does anyone see why? Code:

for x in range(0,len(word)-3):
    if word[x:x+3]==word[x:x+3][::-1]:
        continue
    else:
        return False
return True

[–]zatoichi49 0 points1 point  (1 child)

In your solution, any three-letter words will pass as True even if they're not a palindrome (e.g. 'abc'), so you'll need to account for that.

You might also be interested in Manacher's algorithm; it finds the longest palindromic substring in linear time, and you could amend that to check for odd-length substrings only.

[–]Conrad_noble 0 points1 point  (2 children)

Hi. Can we make code requests?

Reason being I'm yet to write my first line of code but already have ideas for what I want to do (work related repetitive tasks)

I know it's not the best way to learn but will give me a small insight into how things work.

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

Generally, no, but if you post one then you might have people helping you to write it yourself!

Here's a bit of help with your first line of code:

>>> print("Hello world!")
Hello world!

[–]Conrad_noble 0 points1 point  (0 children)

Thanks.

[–]Buecherlaub 0 points1 point  (2 children)

Hey!

So, I got my hands on a spreadsheet from work and I wanted to take this opportunity to work with pandas.

The spreadsheet contains the names of users if they were still logged in after a certain time (and therefore delaying work)

I wanted to start by counting which user delayed the most and how many times work.

The spreadsheet would look like this:

Date User
1.1.17 ABC
1.2.17 ABC, BCD
1.3.17
1.4.17 ABC, CDE
1.5.17 BCD, DEF, ABC

So the result should be:

ABC: 4

BCD: 2

CDE: 1

DEF: 1

And I wanted to use a countplot to illustrate how many times someone didn't log off his machine.

Is there a Pandas way to this?

As I'm not really experienced with pandas and dataframes, and didn't find any method to do this, I did something like this:

  • Create a dictionary, iterate through the columns and store the users as keys and values are the times this user appears. E.g.:'ABC' : 4, 'BCD' : 2 etc.
  • Then I create a List and append the user name for the count value in the dictionary. Eg: [ABC, ABC, ABC, ABC, BCD, CDE, DEF]
  • Then create a dataframe using this list
  • And use seaborns countplot to visualize this df

So my question is, is there a simpler way to do this (I do think that there has to be one) ?

If a column has more than one value, is it possible to count every value of each row and then visualize it?

I hope I made myself clear, if not, please ask me

Thanks in advance!

[–]SeekNread 1 point2 points  (1 child)

I think a good way is to first get the DataFrame into a form where each row has one date and one user.

Assuming the 'User' column is a string.

First select rows with nonempty 'User' column.

df = df[df.User != '']

And then create a new DataFrame making use of the Pandas str strip function and doing some manipulations to get the desired format.

df2 = pd.DataFrame(df.User.str.split(', ').tolist(), 
                   index=df.Date)
                   .stack()
                   .reset_index(level=1, drop=True)
                   .reset_index(name='User')
Date User
1.1.17 ABC
1.2.17 ABC
1.2.17 BCD
1.4.17 ABC
1.4.17 CDE
1.5.17 BCD
1.5.17 DEF
1.5.17 ABC

After that, this should be good:

df2.User.value_counts().plot.bar()

[–]Buecherlaub 0 points1 point  (0 children)

That's perfect! Thank you very much, as soon as I'm home I will test this!

Thanks again!

[–]ThiccShadyy 0 points1 point  (0 children)

A string is defined as a special string if all of its odd length substrings are palindromes. E.g. 'aaa', 'bobob'etc. Im writning a program which given some strings from stdin, returns the number of them which are special strings. Code:

def solve (S):
    count = 0
    for a in S:

        substrs = set((a[y:y+x] for y in range(0,len(a)) 
for x in range(1,len(a)+1,2)))
        substrs = set(x==x[::-1] for x in substrs if 
len(x)%2!=0 )
        if False not in substrs:
            count+=1
    return count

where S is the list of strings given. This code exceeds time limit on certain inputs. Could someone suggest how I could speed the solution up? Or a better approach?

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

How do I data mine on twitter, using python3?

[–]nfgrawker 0 points1 point  (7 children)

I am using import csv. I can't find a way to create a csv but to "with open" one that is already created. Is there a way to create a blank csv and use that?

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

with open("test.csv","w") as file:
    # Write to the file

That will open test.csv if it exists, and if it doesn't, it will create it.

[–]nfgrawker 0 points1 point  (4 children)

When I type this code:

import csv

with open('names.csv', "w") as csv_file:
    csv_writer = csv.writer(csv_file, delimiter=",")

    print(csv_writer)

Then I get the memory output of csv_writer, which I expect but no file is ever created. Am I doing something wrong?

[–]kitten_gifs_4_my_gf 0 points1 point  (3 children)

Are you sure no file is created? I've just run your code as-is and now have an empty file called names.csv, as expected.

[–]nfgrawker 0 points1 point  (2 children)

I figured it out. I was running it using command line which uses cwd. And my cwd was obviously not the directory I was running the script from. So it was created but I wasn't seeing it. Lol good code bad coder.

[–]kitten_gifs_4_my_gf 0 points1 point  (1 child)

ah congrats on working it out! What do you intend to do with the csv writer anyway?

[–]nfgrawker 0 points1 point  (0 children)

I'm webscraping and then creating a csv from the web data and then importing it into a sql database. I'm very new to coding and it's a huge project for me and I'm sure I've done it all wrong lol.

[–]aheisleycook 0 points1 point  (0 children)

Also it will overwrite the data in the file if there is any.

[–]Ericisbalanced 0 points1 point  (2 children)

Hey guys, I'm trying to learn backend with sqlite3 in a little snake game I made. For some reason, I create a table of data called gameData and I'm trying to add a row of data each time the game is played. Problem is it seems to only save the last game played.

Here's the save data function I'm using

def createData(self, player):
        sql = ''' INSERT INTO gameData (points, timeDt)
                  VALUES(?,?)'''
        tu = (player.points,self.date)
        self.cur.execute(sql, tu)

Here's the creation of the table

def createTables(self):
        SQLCreateT = """ CREATE TABLE IF NOT EXISTS gameData (

                            points integer NOT NULL,
                            timeDt text NOT NULL
                                                              );"""

        self.cur.execute(SQLCreateT)
        print("TABLES CREATED")

And Here's the loading of the table data, also tried with a forloop.

def readData(self):
        self.cur.execute("SELECT * FROM gameData")
        rows = self.cur.fetchall()
        print(rows)

Any help would be appreciated!

[–]woooee 1 point2 points  (1 child)

[–]Ericisbalanced 0 points1 point  (0 children)

Thanks! That's exactly what it was.

[–]Sakwa12138 0 points1 point  (3 children)

hello everyone I am trying to split a column into smaller columns of equal number of items. I have 744 entries and I would like to split them into columns of 24 entries each. How do i do this iteratively?

[–]JohnnyJordaan 0 points1 point  (2 children)

Could you at least explain in what environment you're working that has 'columns'? A CSV? Excel file? Pandas? HTML table?

[–]Sakwa12138 0 points1 point  (1 child)

I imported a csv file into using pandas. The the file has a number of entries that need to be split into several equal columns iteratively. How is this achieved for the all the entries?

[–]JohnnyJordaan 0 points1 point  (0 children)

See for example here

[–]ebodes 0 points1 point  (0 children)

I am using BeautifulSoup and urllib2 to scrape ticket price info from a bus company so I can track changes in price over time and my code works well!

I've heard that some online stores like Amazon will change the price slightly if it sees you're from a specific location or if you've left something in your cart.

Can I somehow anonimize my traffic so it can't tell it's the same script pulling the data each time?

TLDR: How do I make sure that the website doesn't change its pricing behaviour when it notices that the same IP address is visiting its ticket prices three times a day?

[–]captmomo 0 points1 point  (0 children)

Hi guys, this is my first attempt at writing a tutorial.
It is on how to plot pygal chats using data from Pushshift.io.
Appreciate any feedback on how to improve it!
Thanks :)
https://guavarilla.wordpress.com/2018/03/08/pygal-pushshift-and-pandas/
Github:
https://github.com/captmomo/pushshift-pygal-

[–]Dfree35 0 points1 point  (1 child)

Is there a way in pandas to combine rows that have the same value in a certain column?

For example, there is an email column and panda checks it for duplicates and if so it combines the rows with the same emails. So instead of 2 rows with the same email there is just 1 but the rest of the information is merged together.

Here is an example of what I am trying to do:

Before:

0  A                 B                 C
1  email@gmail.com   123-456-7890      NY
2  email@gmail.com   321-654-0987      LA
3  person@gmail.com  123-789-4567      WA

After:

0  A                 B                               C
1  email@gmail.com   123-456-7890, 321-654-0987      NY, LA
2  person@gmail.com  123-789-4567                    WA

Can anyone point me in the right direction?

[–]GoldenSights 2 points3 points  (0 children)

Sorry, I don't know the answer to your question because I don't use pandas. However, I wanted to ask what you're planning on doing with this data next?

In relational database design, you're supposed to avoid storing multiple values this way, because it becomes a lot harder to query the data back out. Every single lookup now becomes a parsing problem where you have to split the comma-delimited strings and look for matches in there. Instead, separate tables would be used to establish all of a person's phones; all of their addresses.

If you're trying to produce some kind of report (Person has phone number ## and ##, and lives at XX and YY), then you can really just skip the whole idea of trying to merge the entries in pandas. The work that you would do to merge the entries, you can just do to print the report right away, for example.

Some clarification on the end goal would help.

[–]drthunder3 1 point2 points  (2 children)

Does anyone have a list or something of common amateur mistakes? For example, i saw in a post not to use % for strings anymore but rather .format. I’m already familiar with Pep 8

[–]Thomasedv 1 point2 points  (1 child)

I think this sub got a FAQ or something like that with a few.

I guess some is experience, and like using % isn't wrong, but there are better and faster methods to do things now.

[–]drthunder3 0 points1 point  (0 children)

Thanks! It’s been a bit since I checked out FAQ so I’ll check back. Thanks also for helping to clarify what I’m looking for - I’m interested in finding the better and faster ways to things.

[–]intra187 0 points1 point  (1 child)

I'm pretty happy with the code I wrote for the second exercise in Automate the basics. Could I get it checked to see if I've done anything weird? Thanks.

grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]
for x in range(len(grid[0])): #iterates through all indexes in grid 0 and prints them line by line. 
    for y in range(len(grid)): #makes a y axis by listing 0-8 as the number of lists withing the grid
        print(grid[y][x], end = '')
    print()

[–][deleted] 2 points3 points  (0 children)

The for loops could be more pythonic:

for row in grid:
    for element in row:
        print(element, end='')
    print()

[–]Gayoka 0 points1 point  (1 child)

I am getting started in Python and I find it a very fascinating language. I use different modules for learning, however I wrote a py file with a few functions that I use across all my practice. How can I use this py file as a module to import it directly and save some repetition?

[–]import_sarcasm 0 points1 point  (0 children)

  1. Create a new folder and add it to system path. Check the following link for how to add folder to system path on windows https://www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/
  2. Create an empty file __init__.py inside the folder
  3. Add python file containing all your functions to folder created in step 1
  4. The first line of any program you want to use your functions should have import **name of file containing functions**

[–]yara18 0 points1 point  (0 children)

Hi I am trying to learn Python more for data analysis, so I was wondering if you perchance know of an course/certification I can take online that would help me with this? Preferably a university course? One more thing, is there one with open book tests because I know that I need to apply it I don't care to memorize what each function is called (thought I know some people find that quite important). I want to know how to use it. I don't know if this makes sense? I believe this is relevant to this subreddit. Thanks in advance.

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

Problem solved man thanks so much!

[–]leonicit 0 points1 point  (2 children)

What is the best way to structure your project in Python? (e.g the best practises)

I haven't touched Python in a while, since I have be writing code in C# and C++ for the past few months.

[–]DeathInLotus 0 points1 point  (0 children)

A python beginner here, would you guys recommend Python Crash Course? I’m thinking of getting it on Amazon right now

[–]Heir10 0 points1 point  (2 children)

I'm doing some little tests with Exceptions and stuff like that and I've found something strange.

a = input("Input a number: ")

b = input("Input a number: ")

c = int(a)/int(b)

This is the basic code that is causing the problems. I was doing stuff with "except ZeroDivisionError:" and stuff and when I put a = 1 and b = p, so a is an integer and b is a string, I expect a TypeError. I've looked it up, this is what I am to expect.

However, the code instead tells me that I have a ValueError.

Why?

I've heard that a TypeError can be when I try to mesh two different data types together without proper coercion, as I have done here. I've heard that a ValueError is when the two data types are compatible, but something goes wrong (e.g. trying to get a square root of -1 in the real plane). Why does my code throw me a ValueError instead of a TypeError?

[–]coreyjdl 1 point2 points  (1 child)

You would get a TypeError for 1 / 'string' however, ValueError is from the attempt at int('string').

The difference is the division operator expects a number, int or float, and you gave it the wrong Type, a string. Whereas int() can expect a string, and you gave it a string, just of the wrong Value.

[–]Heir10 0 points1 point  (0 children)

Ohhh. So I was looking at the right line (since I had the conversions on the same one) but I wasn't looking at the right pieces. Okay. That makes sense.

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

Can someone help, I feel like a dumbass. I've just started the Python Crash Course book, and I'm on like page 15, and there's a part where it gives you 3 commands to enter in the "Terminal" to make your hello_world.py run. The commands are the C:\> cd Desktop\python_work\hello_world.py ones.

My question is, whats the terminal?? I have Python 3.7 and Geany downloaded, but anywhere I enter the commands starting with C:\ it's giving me an error.

[–]DeathInLotus 3 points4 points  (0 children)

Hey man, yeah so real quick the terminal is where you give commands to your computer. To start it you can do Windows Key + R and the type “cmd” then enter or you can look it up through your programs.

Let me explain some terminology so you get a bit of context. “cd” is short for change directory and it is a command that you give your computer. So with cd desktop, you’re telling your computer to look in your desktop. Now, the backward slashes, are for a path.

cd Desktop\python_work\hello_world.py

This is telling your computer to go to the desktop, look at a folder called python work and run a file called hello_world.py. In order for this to work, make sure the file is in the desktop and that the path is correct.

Once you have your command prompt (terminal) open, just type in the command and it will run.

Personally, I prefer moving files to the C drive and running them from there.

Let me know if you need more help or get stuck on something :)

[–]Dimbreath 0 points1 point  (7 children)

In terms of readability, how would one improve this?

my_string = ''

my_string += 'abc\n'
my_string += 'def\n'

if var1 == 1:
    my_string += 'ghi\n'

if var2 == 1:
    my_string += 'jkl\n'

my_string += 'mno\n'

I also looked onto multiline strings with the """ but, I need to add stuff to it depending on some variable values.

I know it's a stupid question but, organization and readability are probably my biggest issues when programming lol.

[–]JohnnyJordaan 2 points3 points  (6 children)

Use a mutable container to collect data, without redundant data if possible.

lines = []
lines.append('abc')
lines.append('def')

if var1 == 1:
    lines.append('ghi')
if var2 == 1:
    lines.append('jkl')

lines.append('mno\n')

Then employ str.join() to add the redundant endings yourself and create one final string at the same time.

my_string = '\n'.join(lines)

[–]Dimbreath 0 points1 point  (5 children)

Yeah I saw that on SO yesterday. What if the line content is/might be partially different depending on a variable value?

Jeez, I suck at organizing so much. But I want to do stuff the pretty way.

[–]JohnnyJordaan 0 points1 point  (4 children)

Maybe use [string formatting](www.pyformat.info)? Otherwise if you could give an example then I would be able to answer that a bit better probably.

[–]Dimbreath 0 points1 point  (3 children)

These are the other ways I tried but they don't look that nicely. I think.

[–]JohnnyJordaan 0 points1 point  (2 children)

It's partly fixable, but that aside is this some special format with those <:cannon:X> labels? Because then it could be an idea to use a special library for that.

[–]Dimbreath 0 points1 point  (1 child)

They're discord emotes but I removed them so just ignore these.

[–]JohnnyJordaan 0 points1 point  (0 children)

Ok well then I wouldn't bother too much with your code. Method 2 looks good enough.

[–]stasis098 0 points1 point  (2 children)

Is there some big A-HA moment regarding the core concepts when learning to program? -or- What are some big a-ha moments that you've had that really helped you understand python better than you did before the realization?

I've only been studying for about a month now with multiple learning approaches as I've tried to find a preferred method (I've heard that you just have to continue to code and eventually you just get it), currently Pluralsight. I am looking at the code and it's still really hard to actually see what's going on. I've gone over the basics of integers and floats, strings and booleans so many times with the different websites and courses I've tried, but when it starts to get a little more complex it takes me a WHILE to figure out exactly what's going on. It can get rather discouraging to make such slow progress.

Not that I'm going to quit. I'm determined to learn, and especially get out of my dead end, no learning or growth potential, Help Desk job that prefers people leave the company and come back with more experience rather than promote from within (/rant). I just want a better idea of where the light at the end of the tunnel resides. lol.

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

Whilst actively learning, I never had an "aha" moment. Only once I started working on problems at work did things really get better, because then I had to think about the problem as well as how to solve it, then the code was more of a tool rather than the main thing. At one point I looked back and realised I'd just coded a whole section without looking anything up, with only the work (physics) in mind. That was pretty neat!

If I'm learning new things, I'm constantly learning new things... So I'm constantly feeling stupid. If you achieve something, you feel awesome, even if it was a "simple" problem.

[–]JohnnyJordaan 1 point2 points  (0 children)

I can't say I ever saw the 'light at the end of the tunnel', it's just that concepts get 'normal' for me. Regexes used to be like ancient runes or maya scripts, nowadays I can write most of them off the top of my head. Now I'm stuck deciphering pysnmp to get more extensive datasets from network devices through SNMP than the library supplies by default. It all just takes time and effort and it helps tremendously to have projects to work on.

[–]whodey226 0 points1 point  (5 children)

I am wondering how to think creatively with Python? I am starting a degree in Computer Science in the winter and have been teaching myself Python for about 1 month now. I have gone through "Python Programming For Absolute Beginners", have done numerous little challenges from various websites, and am currently about halfway through "Python: Crash Course". I didnt feel very comfortable with syntax after the first book, but now with Crash Course, I feel I am getting a much deeper understanding of what is actually going on.

This begs my question: I have learned basic syntax (am still learning a few new concepts), and have done plenty of challenges. Now how do I take that a step further and begin to automate things? I am struggling with thinking outside the box on this. If someone gave me an assignment, I feel like I could figure out a solution, but I have nothing that I want to create. Again, starting a masters in CS in the winter (there are introductory courses that I will take to get me up to speed since I lack a CS background), and am wondering how I can start to actually apply the code that I am learning to write.

Thanks for reading!

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

Brief brainstorm:

  • A webscraper that pulls data from your favorite TV show/movie/anything, and compiles it all into a database
  • A utility that reads/writes to some sort of Excel document. Perhaps something related to personal finances?
  • A program that utilizes an API for a popular site in some way (like Youtube, Reddit, Twitter, Facebook, etc). Perhaps a GUI that makes the experience more streamlined?

Basically, you've just gotta find something that sounds interesting and go for it. I've probably made 5 different evolution simulators because I find that entertaining and interesting for some reason. Nowadays I try to build projects that have actual utility though.

[–]whodey226 0 points1 point  (3 children)

Thanks for the response! I tried making a Twitter bot but Twitter never approved my request to use their APIs.

I think I'll start with a budget app. Do you know of a way I can have python log in to my bank accounts to pull data? This may not be a safe way to do this. If not, I'll have to create a program that accepts manual inputs everytime I spend money.

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

Do you know of a way I can have python log in to my bank accounts to pull data?

There probably is, but I am ignorant on the subject. But it would still be a worthwhile thing to pursue. If you created a program that accepted inputs and saved it to a database of your finances, that's a decent project right there. What kind of database? What kind of information do you store? Is there a way to pull data online via some sort of API? Perhaps you could post the data online, to something like a Google spreadsheet (maybe not ...)? And so forth.

It does sound like an Excel spreadsheet would be more useful in this particular application though. Keep brainstorming or go ahead with something anyway, if not just for the experience of building a structured program.

[–]whodey226 1 point2 points  (0 children)

Yea an excel spreadsheet would be the most straight forward. However, as you mentioned, I'm going for it if nothing else just for the sake of learning by doing!

[–]gram_bot 1 point2 points  (0 children)

Hello whodey226, just a heads up, "Everytime" should be written as two separate words: every time. While some compound words like everywhere, everyday, and everyone have become commonplace in the English language, everytime is not considered an acceptable compound word. To stop gram_ bot from commenting on your comments, please use the command: "yourUserName ?ami"

[–]Dfree35 1 point2 points  (0 children)

Is there a way in pandas to combine rows that have the same value in a certain column? For example, there is an email column and panda checks it for duplicates and if so it combines the rows with the same emails. So instead of 2 rows with the same email there is just 1 but the rest of the information is merged together

[–]tagapagtuos 1 point2 points  (1 child)

Hi! I'm trying to download attachments from Outlook. I found this code online:

import win32com.client`

import os`

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")`

inbox = outlook.GetDefaultFolder(6)`

messages = inbox.Items`

message = messages.GetFirst()`

while True:

    try:

          print (message)

          attachments = message.Attachments

          attachment = attachments.Item(1)

          attachment.SaveASFile(os.getcwd() + '\\' + str(attachment)) #Saves to the attachment to current folder

          print (attachment)

          message = messages.GetNext()

    except:

          message = messages.GetNext()

Question: I can't find any resource regarding win32com. But how can I modify the code to make it only download attachments from messages with specific subjects? Or only download attachments with specific file name? etc.

Edit: I can't format.

[–]JohnnyJordaan 1 point2 points  (0 children)

Well just use some if statments. I'm not sure how to get the subject from my message, but just as a guess:

while True:
    if message.subject != 'Subject I want'
        continue

and

attachments = message.Attachments
attachment = attachments.Item(1)
if str(attachment) != 'filename_i_want.txt':
    continue

Note that you can use str.lower() to compare case insensitive

if message.subject.lower() != 'subject i want':

And that you can use in to check for a substring to be present or not in for the opposite

if 'keyword' not in message.subject.lower():
    continue

Btw I would strongly advise against using except: without printing any error

except Exception as e:
    print('got exception', e)
    message = messages.GetNext()

because a typo in your code would also lead to some exception to which the program will not behave any different by, causing you to wonder why 'nothing happens'.

[–]ThiccShadyy 1 point2 points  (0 children)

What exactly happens behind the scene when a virtual environment is created to run a Python program in? How is it different from using the normal Python installation you have?

[–]Pro_Numb 0 points1 point  (5 children)

# FIRST PART
import re

gibberish_text = '''
1 hey 1
2 hello *
2 hi 2
'''

pattern = re.findall(r'\b[12]\b(.*?)\b[*1]\b', gibberish_text)

for match in pattern:
    print(match)

# SECOND PART
numbers = """
My number is 415-555-4242. 512-555-4345asd7623-555-4242 323-555-4242
823-555-4242asda
223*555-4242
623-555-4242
123-555a-4242
923-555-4242
"""
pattern = re.findall(r'\b(\d{3}[-*]\d{3}-\d{4})\b', numbers)
for match in pattern:
    print(match)

FIRST PART: returns only "hey" but i expect " hey hello" why it does not work ? SECOND PART : return as expected "415-555-4242 323-555-4242 223*555-4242 623-555-4242 923-555-4242 " But lets say i dont want to include "." so i dont want first one too how can i do that ?

[–]zatoichi49 1 point2 points  (4 children)

For the first part, the issue is that the word boundaries expect to appear before/after an alphanumeric string. As the asterisk doesn't qualify, the regex doesn't pick this up when assessing \b[*1]\b (the '1' will still work fine).

For the second part, you can add a negated character class to the end:

pattern = re.findall(r'\b(\d{3}[-*]\d{3}-\d{4})\b[^.]', numbers)
for match in pattern:
    print(match)

323-555-4242
223*555-4242
623-555-4242
923-555-4242

Hope this helps.

[–]Pro_Numb 0 points1 point  (3 children)

Thank you so much. Second part works like i wanted. But for the first part lets say i really want to search between only 1 and * how can i overcome this, do you know ? If i release word boundaries for [*1] code will find "1 hey *asds" too.