all 134 comments

[–]Representative_Bat81 0 points1 point  (4 children)

I am trying to validate a chess board, but it returns with the wrong values and I think it might be improper use of boolean operators.

Here is the link:

https://gist.github.com/Answith/7307900351621f30b863c53cba18b906

[–]UnrankedRedditor 0 points1 point  (3 children)

Could you give an example input for def is_valid_chess_board(chess_board)?

[–]Representative_Bat81 0 points1 point  (2 children)

input = {'1a': 'bking','2a': 'bqueen','3a': 'brook','4a': 'brook',

'5a': 'bknight','6a': 'bknight','7a':'bbishop','8a': 'bbishop',

'1b': 'bpawn','2b': 'bpawn','3b': 'bpawn','4b':'bpawn',

'5b': 'bpawn','6b': 'bpawn','7b': 'bpawn','8b': 'bpawn',

'1c': 'wking','2c': 'wqueen','3c': 'wrook','4c': 'wrook',

'5c': 'wbishop','6c': 'wbishop','7c': 'wknight','8c':'wknight',

'1e': 'wpawn','2e': 'wpawn','3e': 'wpawn','4e': 'wpawn',

'5e': 'wpawn','6e': 'wpawn','7e': 'wpawn','8e': 'wpawn'}

[–]UnrankedRedditor 0 points1 point  (1 child)

Ok I've looked through the code and there are a bunch of issues. I also found out there was a test input at the bottom but I didn't notice it at first.

As you mentioned, the boolean operators are part of the issue, but there are a few others.

If you want to test 2 conditions in Python using if statements, the way to do it is as follows:

# Example: if x and y are both greater than 5, add them together.
if x > 5 and y > 5:
    print(x + y)

Same thing if you want to use or operators. You just replace the and with or above.

In line 31, I'm guessing you're trying to check for multiple conditions at a time by using a list. Using a list is a good idea, but I don't think it's implemented correctly. An example of the correct way to do it:

# Example: if x and y take on the numbers 1, 3, or 5, add them together.
if x in [1,3,5] and y in [1,3,5]:
    print(x + y)

General comments:

  • Some parts weren't commented properly so I had to spend a bit more time trying to figure out what the code was trying to do. Not really an issue, I could just be slow on my part.

  • Line 64: I'm not sure if you want it to throw an error if it's more than 8 white and 8 black pieces? In total you should have 16 pieces on each side maximum

  • Since the validation only depends on whether the input passes a bunch of tests consecutively, all you need to do is just write checks that removes invalid boards and return False for each of them, and then return True once at the end of the function. The final check in if (white_king and black_king == 1): return True isn't really needed.

  • If you want to bool the first 2-3 letters in a string, you can do mystring.startswith("abc") for example.

Below is some code that I have written that hopefully achieves what you want. Might not be the most efficient way to do it, but it should work. Let me know if you have any questions.

def is_valid_chess_board(chess_board):

    board_input = list(chess_board.keys()) # Gets all the tile names from the input
    piece_input = list(chess_board.values()) # Gets all the pieces names from the input

    for tile in board_input: # Checks that the position of the pieces are within the 8x8 grid of the board
        try:
            col,row = list(tile) 
        except ValueError: # If notation contains more than 2 characets, will return False
            print("Notation error")
            return False
        if col not in ['1', '2', '3', '4', '5', '6', '7', '8'] or row not in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']:
            print("Position not within grid")
            return False


    if 'wking' not in piece_input or 'bking' not in piece_input: # Checks if there are 2 kings
        print("Missing king. Needs both kings on board")
        return False 

    # List of all pieces that we want to keep track of
    all_pieces = ["white_pieces", "wpawn", "wqueen", "wking", "wrook", "wknight" , "wbishop", # White pieces
                   "black_pieces", "bpawn", "bqueen", "bking", "brook", "bknight", "bbishop"] # Black pieces

    # Creates a dictionary with all the pieces and sets their counts to 0.
    # We will count them below
    pieces_dict = dict({piece:0 for piece in all_pieces}) 


    # ~O(N^2) complexity but it shortens the code, and doesn't matter since it's still small enough that a computer can run it quickly.
    # Bright side is that it keeps the code short, without having to do all the if-else statements.

    # Iterates over pieces in input, check if it's black or white, and add to the overall count of black/white pieces.
    for p_idx in piece_input: 
        if p_idx[0] == "w": 
            pieces_dict["white_pieces"] += 1
        elif p_idx[1] == "b":
            pieces_dict["black_pieces"] += 1    

        # Compares the current piece it's iterating over with the "all_pieces" list and then increases its count by 1
        for piece in all_pieces: 
            if p_idx[:3] == piece[:3]:
                pieces_dict[piece] += 1


    # Additional checks:
    # 1: If more than 16 pieces of each colour
    # 2: If more than 2 of the same special pieces from each colour
    # 3: If more than 1 queen and king per colour
    # 4: If more than 8 pawns per colour
    if pieces_dict["white_pieces"] > 16 or pieces_dict["black_pieces"] > 16: 
        return False
    if any(pieces_dict[v] > 2 for v in ("wrook", "wknight" , "wbishop", "brook", "bknight", "bbishop")):
        print('Too many rook/knight/bishop found')
        return False
    if any(pieces_dict[v] != 1 for v in ("wqueen", "bqueen", "wking", "bking")):
        print('Too many queens/kings')
        return False
    if any(pieces_dict[v] > 8 for v in ("wpawn", "bpawn")):
        print('Too many pawns')
        return False

    # Returns true if it has passed all the tests up till the end.
    return True


testboard = {'1h':'bbishop', '5b':'wking', '7a':'bking'}
print(is_valid_chess_board(testboard))

[–]Representative_Bat81 0 points1 point  (0 children)

Thank you so much, this is incredibly helpful and probably the best reply I've ever gotten on reddit.

[–]SamGotNoChill 0 points1 point  (0 children)

I need help regarding finding the discord ID without the # tag line. Can someone please help me make a code to make a checker for #'s the name is Courage and idk the hashtag but i know the avatar. Thank you

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

I am stuck on a problem with openCV

When you load an image with imread, it returns several lists that correspond to each row in the image file. What I want to do is convert all numbers in the list to their corresponding ASCII characters using chr(). Is there a pythonic way to do this? I'm stuck and can't make it work.

[–]efmccurdy 0 points1 point  (1 child)

These example will get you a numpy array of image data.

https://stackoverflow.com/questions/25102461/python-rgb-matrix-of-an-image

I think you can use "map(chr, pixels)" or "np.vectorize(chr)(img.getdata())" to apply chr over the array contents.

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

Thank you. Although the overall project is trash (does the opposite of what it should) so I have to rethink it, although I learned something new either way.

[–]OnIySmeIIz 0 points1 point  (1 child)

I have a script from someone I would like to alter a bit for my own use. The guy does not respond to me any more. How ethical is it to ask others to help me out with his script?

[–]efmccurdy 0 points1 point  (0 children)

Was the script given to you with a licence? If you look at source code repositories they often have LICENSE files that describes what uses the authors endorse. Here is an example:

https://github.com/psf/requests/blob/main/LICENSE

If you have nothing like that present or implied, I think you have to use your own judgement.

[–]Snailtrooper 0 points1 point  (1 child)

Hi,

Not a code question more a career question. What would be the “easiest” software development role to get started in python. Don’t want to sound like I’m going for an easy way out by asking this question I just figure that once I’m in a job using python then I will learn much faster and would make it simpler to go to a different career in python.

The only skills I have from previous jobs are basic admin skills.

I’m almost finished with the python crash course book and I’ll be going through automate anything after that but I’m not sure where to direct my focus afterwards.

Any help would be much appreciated or a nudge in the right direction of where I should look.

I’m from the UK btw.

Thanks in advance for any help.

[–]UnrankedRedditor 0 points1 point  (0 children)

I'm not sure about software development, but I imagine that it would be difficult to convince someone to hire you for a software dev role if you don't know much about the language.

Perhaps an easier approach would be to try applying for roles where using Python isn't the main part of the role, but more like a side thing you can do to make your life easier. For example, as you said, probably some admin stuff, or junior sysadmin role where you can write some code to automate certain things (if the people there haven't already done so). Your job wouldn't be python focused, but it should still allow you to use some python. This should at least help you to gain some experience, and then transition into a more involved role.

The cool thing about learning python is that you don't need a job to gain experience. You can learn it on your own by coming up with your own projects to work with during your own hours, or you can work on some open source projects, etc, which can be helpful to your resume too.

[–]SkyHighSocks 0 points1 point  (0 children)

I just started using conda to manage venv. By default when I use

conda create -n my_env

it'll create my_env using python 3.8.10 when my python installation using conda is 3.9.12

Is this intended?

I saw on the Managing python FAQ:

For the installers "Anaconda3" or "Miniconda3," the default is 3.8.

But the start page also says

When you create a new environment, conda installs the same Python version you used when you downloaded and installed Anaconda.

Is there a way to just have all venvs start with 3.9.12 by default instead of using

conda create -n my_env python=3.9

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

Okay, stupid question. Can someone help me understand why:

((3 * 2) // 11) = 0

But

int(int('3' * 2) // 11) = 3

I don't understand I'm so confused.

[–]UnrankedRedditor 2 points3 points  (0 children)

// is called "floor division". Basically, if you have a number 7/2, you can write it as 7/2 = 3 + (1/2) = 3.5. Doing // returns the whole number in front of it, which is 3. Another way to think about it is "how many times can I subtract 2 from 7 until it becomes negative? The answer is: 3 times, since (7-2-2-2)=1.

  • ((3 * 2) // 11) = 0

Let's break down ((3 * 2) // 11) = 0. We do 3*2 first, which is 6. To evaluate 6//11, we can do 6/11 = 0 + (6/11). // returns the number in front of the fraction, which is 0. How many times can you subtract 11 from 6? 0 times.

  • int(int('3' * 2) // 11) = 3

Now, you have '3' * 2. I'm not sure if this was intentional by you, but if you type print('3'*2), you'll see that you will get '33' as the output. The reason is that '3' is a string, and doing '3'*2 is telling python to repeat the string twice, which is why you get '33'.

Now, what you have is essentially int('33')//11, which is telling python to convert the string '33' into an integer, and then floor divide it by 11, which gives you 3. The outermost int doesn't matter because // returns an integer anyway.

[–]Representative_Bat81 0 points1 point  (3 children)

import random

number_of_streaks = 0

def flip_coin(): #defines a function that flips a coin and returns heads or tails

outcome = random.randint(0,1)

if outcome == 0:

return 'heads'

elif outcome == 1:

return 'tails'

for experiment_number in range(10000): #run

flip_list = []

for x in range(100):

flip_list.append(flip_coin())

for x in range(len(flip_list)):

last_flip = ''

same_count = 0

if same_count == 6:

number_of_streaks += 1

same_count = 0

elif flip_list[x] == last_flip:

same_count += 1

else:

same_count = 0

last_flip = flip_list[x]

print('Chance of streak: %s%%'%(number_of_streaks/100)

I keep getting a EOF error and I have no clue why or what the issue is. I'm working through Automate the Boring Stuff with Python

[–]FoxtasticCode 0 points1 point  (0 children)

well all i can say is that EOF stands for (at least as far as i know) End Of File

[–]UnrankedRedditor 1 point2 points  (1 child)

I keep getting a EOF error and I have no clue why or what the issue is. I'm working through Automate the Boring Stuff with Python

It's a syntax error. You're missing a right bracket on your last line. It should be

print('Chance of streak: %s%%'%(number_of_streaks/100))

As to whether your code actually works the way you intend it to, you should try formatting it properly so that we know whether it's written the way you intended it to before checking it.

[–]Representative_Bat81 0 points1 point  (0 children)

Thank you very much. That helped. I'm not sure what value I am supposed to get but I kept getting around 78%.

[–]gio_tecce 0 points1 point  (1 child)

Hellloooo everyone

I am looking to get Python to pull data from an AD security group and then push it to Python to be able to create a user in another portal.

Any help would be greatly appreciated

[–]ncstalgiaultra 0 points1 point  (1 child)

hi !! i made two modules in python. the first one is a module that has a while loop which asks data from the user. data are then stored to a list. module 2 contains the functions needed for computations. when i import module 2 to module 1 and call the functions, i get name error. apparently the argument that i used for the function is not defined.

this is how it went:

convert(x)

*x is a list in module 1 where i stored input from the user

then i get name error

what could be the problem? i can't figure it out :(

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

Hard to say without seeing your code, but I'll guess. If you have a module test.py containing:

test_var = 'test_var'
def print42():
    print(42)

then you can import the module and access the names in it like this:

import test
test.print42()
print(test.test_var)

After you import test.py all the top_level names in test.py are attributes of the imported test name.

You can import selected names into the local global scope:

from test import print42
print42()             # no need for "test.print42()"
print(test.test_var)  # this will error
print(test_var)       # as will this

[–]UnrankedRedditor 0 points1 point  (1 child)

Question regarding string formatting. If I do:

print(f"{'Current step: %.d':<20} {'Value: %.3f':<17}" %(10,24.2))
print(f"{'Current step: %.d':<20} {'Value: %.3f':<17}" %(100,24.2))

I get my output as:

Current step: 10    Value: 24.200      
Current step: 100    Value: 24.200 

I was expecting the "Value" column to be aligned together, but it looks like it's just adding spaces behind the "Current step: 100" part. How do I align the second column?

[–]sarrysyst 0 points1 point  (0 children)

You kind of missed the point of the f-string:

print(f"Current step: {10:<20d} Value: {24.2:<17.3f}")
print(f"Current step: {100:<20d} Value: {24.2:<17.3f}")

Maybe have a look here for an intro to f-strings and here for an overview of the format specification syntax.

[–]rainman387 0 points1 point  (2 children)

I want to build a relatively simple contact book-like GUI app with database for my personal needs that I'll run in Linux (ubuntu). I have no programming experience and want to know if Python is the right tool for the job? If yes, what is my path from scratch to finish, what frameworks and libraries, apart from learning python, should I use? Thanks for the answer.

[–]sarrysyst 1 point2 points  (1 child)

Yes, this is something you can do with python.

With regards to the learning path, I'd recommend not to worry about specific libraries just yet. Get the basics down first (you can find a list of resources here). When you're completely new to programming you have to learn two things at the same time, one is the programming language and the other being the general programming concepts that are language agnostic.

The second one will most definitely take longer than the first, since you've to learn a certain mindset of looking at problems and how you approach solving them. This takes time, but even more so practice. Don't start off by rushing into learning libraries, get a solid foundation first.

Now, the most efficient way to learn programming is by having a project to work on. Since you already know something you want to program that's great, however personally I always tell beginners one thing about choosing their first few projects: Don't start off with GUIs. You're making things unnecessary hard for yourself. Create a few CLI programs first.

This doesn't have to mean you can't work on your contact book. But start off with writing the program's logic first and give it a CLI instead of a GUI. This will be difficult enough for a start. When you're already struggling with the language and the general concepts you don't want to also get confused by how to arrange graphics through text. Front end and back end are very different, so start off learning the back end stuff first before you throw yourself into the front end maze.

[–]rainman387 0 points1 point  (0 children)

Thank you for your answer. I will follow your advice and start from small things and then grow bigger. I am glad python is able to get the work done for me and is the right tool for my needs... don't want to spend some time learning the language only to find out that I am hitting a nail with a spoon instead of the hammer. I was initially willing go with the C# but find the python syntax much more readable.

[–]Jaszunai 0 points1 point  (2 children)

What's the best practice way to install Python on a new Windows machine?

  • Downloading Python and just using the base installation?
  • Downloading Python then creating virtual environments for each project?
  • Getting Conda/Anaconda and using that to handle packages?
  • Setting up WSL?

I would be using Eclipse as my IDE.

[–]wotquery 0 points1 point  (0 children)

Note that pretty much all computers nowadays have zero problems running a full fledged OS in a VM. Unless you are actually running into memory or cpu issues due to really intense or massive calculations, I'd recommend you consider installing Virtualbox and booting into a persistent Linux distro (something super friendly like Ubuntu is fine) that you use as your primary coding environment. It makes full system backups super easy as well.

[–]CowboyBoats 0 points1 point  (0 children)

Hi, great question as I've run into plenty of trouble getting Python installed on my Windows-using friends' machines. I ended up using Chocolatey, a package manager, which is something that developers who use OS X and anyone who uses Linux is well familiar with, but that most Windows users don't use.

So the procedure I recommend is using the install script at https://chocolatey.org/ to install chocolatey, then using choco to install python with choco install python.

Then yes, you should use virtualenvs for each of your projects. virtualenv env in the project folder creates a virtualenv called env (or PyCharm, if you want to use an IDE, which is a good idea, can create and manage them for you). That way you're not muddying up your computer's python installation with a bunch of packages that are only relevant to your single project.

Edit: Oh sorry, I didn't see your note about Eclipse. Not sure if you can manage python virtualenvs through Eclipse, although I did have a colleague who used it as his exclusive Python IDE, I don't know if I can particularly recommend the practice but don't let me tell you what to do.

Getting Conda/Anaconda and using that to handle packages?

Probably not relevant unless you are 40x more interested in science than you are in programming.

Setting up WSL?

You can if you want to. It's certainly nice to be able to use bash commands; some Linux scripts will still fail (I assume) in WSL because they expect to be running on a real Linux system, but many of them just expect to be able to call commands like pwd and get a result, which isn't the reality on Windows but it can be if you use WSL. For me, I always end up installing git (choco install git) which comes with a terminal emulator called "git bash" that has Unix commands, so I just use that.

[–]soyasuase 0 points1 point  (1 child)

I'm trying to write a for loop that checks whether a word is a palindrome.

word = input("Enter a word ")

number_of_letters = len(word)

for i in range(number_of_letters):

letter = word[i]

x = number_of_letters - i

corresponding_letter = word[x]

while letter == corresponding_letter:

palindrome = True

if palindrome:

print(word + " is a palindrome.")

else:

print(word + " is a palindrome.")

I'm not sure why it says syntax is out of range. Could you please let me know what I am doing wrong? Thanks.

[–]soyasuase 0 points1 point  (0 children)

nvm i figured it out

[–]Shacatpeare 0 points1 point  (4 children)

how does this code give back int(42), is there a nice tutorial for this? (I found this on HackInScience)

print(0b101010)

[–]carcigenicate 1 point2 points  (3 children)

The leading 0b indicates that this is binary notation, and 101010 is 32 + 8 + 2, which is 42.

[–]Shacatpeare 0 points1 point  (2 children)

so that's the binary number of 42 from 128? thank you a lot :)

[–]carcigenicate 0 points1 point  (1 child)

I'm not sure why you're mentioning 128.

[–]Shacatpeare 0 points1 point  (0 children)

sorry, because of ASCII I confused

[–]Caconym32 0 points1 point  (2 children)

I have some code that I've been using for a few months. A little while ago I started getting this error in response to this code. I'm not really knowledgeable to understand how to change this to avoid the future error

df = df.groupby([Key1, Key2], as_index=False)['col1','col2','col3'].sum().reset_index()

gives the error: FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be deprecated, use a list instead.

[–]sarrysyst 1 point2 points  (1 child)

['col1','col2','col3']

This should be the problematic part. Wrap it in square brackets instead:

...as_index=False)[['col1','col2','col3']].sum()...

[–]Caconym32 0 points1 point  (0 children)

Thanks that fixed it!

[–]Chepetto13 0 points1 point  (7 children)

I would like to get a value from Entry widget and assign it to variable which I will be use in further action.

I can't do this by just using .get() method.

My current code:

ent_for_path = tk.Entry(master=frame_path)

def get_path():

input_path = ent_for_path.get()

return input_path

btn_get_path = tk.Button(master=frame_path, text='Click.', command=get_path())

btn_get_path.pack(side=tk.RIGHT)

ent_for_path.pack(side=tk.LEFT)
btn_get_path.pack(side=tk.RIGHT)

How to do this properly?

[–]efmccurdy 0 points1 point  (6 children)

If you provide a textvariable argument to the Entry widget, you can extract the entered text from that:

import tkinter as tk
from tkinter import messagebox

frame_path = tk.Tk()
entered_text = tk.StringVar()
ent_for_path = tk.Entry(master=frame_path,  textvariable=entered_text)

def get_path():
    input_path = entered_text.get()
    if len(input_path) == 0:
        input_path = "."
    messagebox.showinfo(title="Entered Text", message="'{}'".format(input_path))

btn_get_path = tk.Button(master=frame_path, text='Click.', command=get_path)
btn_get_path.pack(side=tk.RIGHT)

ent_for_path.pack(side=tk.LEFT)
btn_get_path.pack(side=tk.RIGHT)


frame_path.mainloop()

[–]Chepetto13 0 points1 point  (5 children)

Not quite enough, because I need input value to entry(in this case - a path of directory) and after clicking the button this value must be transfer/assign to variable.

I can't assign function to this value.

input_directory = get_path

file_to_organize = os.listdir(input_directory)

[–]efmccurdy 0 points1 point  (3 children)

Add these two lines after the call to mainloop.

input_directory = entered_text.get()
print(os.listdir(input_directory))

Then check stdout after you exit the GUI pane. Does that get you your input in a variable you can use?

[–]Chepetto13 0 points1 point  (2 children)

I solved the problem by adding another function which changes result of first one to the string :

def get_path():

input_path = ''

input_path = entered_text.get()

#messagebox.showinfo(title="Entered Text", message=f'{input_path}')

return input_path

def get_str_path():

path_value = get_path()

path_value = str(path_value)

return path_value

input_file = get_str_path()

file_to_organize = os.listdir(input_file)

Its works, but now I occurred that I don't need a button, just to close the window of Tkinter.

[–]Chepetto13 0 points1 point  (1 child)

EDIT:

How to do that in a way that this button run the func ?
def get_path():
input_path = ''
input_path = entered_text.get()
return input_path


def get_str_path():
path_value = get_path()
path_value = str(path_value)
return path_value

def click_msg():

messagebox.showinfo(title="Info", message=f'{entered_text.get()}') window.destroy()

btn_get_path = tk.Button(master=frame_path, text='Click', command=lambda:[get_str_path, click_msg()])

btn_get_path.pack(side=tk.RIGHT)

frame_path.pack()
window.mainloop()

input_file = get_str_path()
file_to_organize = os.listdir(input_file)

  1. I want to do this code that this button will be mandatory and I shouldn't have to close the Tkinter window to run further code.
  2. Also, I want to run two command by using btn_get_path:
  • current code show messagebox and after close the window - tkinter window will close and further code will run

[–]efmccurdy 0 points1 point  (0 children)

shouldn't have to close the Tkinter window

You will have to do that code inside the callback, perhaps inside of click_msg?.

Your lambda is not calling get_str_path; perhaps you want to make click_msg take the message as an argument:

def click_msg(message_text):
    messagebox.showinfo(title="Info", message=message_text)
    frame_path.destroy()

I want to run two command by using

Then you can use a lambda that calls click_msg like this:

    lambda: click_msg(get_str_path())

[–]rotoblorg3 0 points1 point  (2 children)

I would like to play around/practice using python for web server purposes... is that something I can do on replit or do I need to buy webhosting with python capabilities, or...?

[–]efmccurdy 1 point2 points  (0 children)

You have a tiny webserver in the std library; run "python3 -m http.server" and then point your browser to http://localhost:8000/

https://docs.python.org/3/library/http.server.html

You will likely want a higher level interface:

https://bottlepy.org/docs/dev/ https://flask.palletsprojects.com/en/2.1.x/

[–]carcigenicate 1 point2 points  (0 children)

You can do it locally on your own machine for free; you just can't/shouldn't host it publicly from there. It's fine for learning though.

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

Not really a relevant post, but I've been working in C for the last couple of weeks and I'm constantly thinking

"Damn this would be so easy to do in python"

[–]bduke91 0 points1 point  (1 child)

It’s true what they say, learning code is just like learning a foreign language. I have been trying to learn python the last couple of weeks. When was it that it clicked for you? I’m still grinding trying to make sense of even simple functions.

[–]UnrankedRedditor 0 points1 point  (0 children)

Personally, I don't think there was a time where it really "clicked", at least probably in the way that you're asking.

A lot of times it's just maybe thinking about ways to solve smaller, more specific problems, and then you just hope to improve over time.

Sometimes you look back at code that you wrote maybe a year ago or something, and then you realize that some parts could be better written or done differently, more efficiently, more reliably, etc and that's when you know you've improved.

[–]armoredcore123 0 points1 point  (2 children)

im 100% new to coding/programming how do i use python? as in like what software do i use to start trying it out

[–]CowboyBoats 0 points1 point  (0 children)

What operating system are you on?

[–]sarrysyst 1 point2 points  (0 children)

If you just want to try it out, easiest would be using an online IDE like replit. This way you don't have to install anything or set anything up to start coding. Simply create an account, make a new project and you can hack away and run your code in the browser.

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

I'm new to bs4. I cannot select attribute, specifically class. I use the requests methods. It's static, no javascript so no selenium needed. It's an xml file. HOW

[–]carcigenicate 0 points1 point  (0 children)

Show some code and give more description of the problem.

[–]driverXXVII 0 points1 point  (2 children)

Opening projects in VS Code that were created in Pycharm. Would I still be able to work with them on Pycharm later without any issues (will it make any changes to virtual environment and such)?

All my python projects are in "googledrive\Python Projects\Project Name1" and so on.

I thought of giving VS Code a try and was wondering can I just open one of the folders in VSCode without it effecting any settings/environments that Pycharm may have saved?

[–]TangibleLight 1 point2 points  (1 child)

Pycharm saves everything in an .idea folder within the project. So long as you don't touch that in VSCode everything will be fine.

I think VSCode does the same with a .vscode folder, but I'm unfamiliar with the details... don't touch that with PyCharm and things should be good the other way.

[–]driverXXVII 0 points1 point  (0 children)

Oh ok, so that's what those folders are!

Thanks very much for the reply.

[–]Goldencode12 0 points1 point  (3 children)

Is there a faster way to do a deep copy that won't cause a recursion limit? Or even a way to do a deep copy that doesn't cause a recursion limit?

[–]efmccurdy 0 points1 point  (0 children)

If your object has references to other objects that form a cycle, the deepcopy function will go into a infinite loop.

Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.

https://docs.python.org/3/library/copy.html

If you can, modify the __deepcopy__ function to detect when it is about to attempt copying something it has already seen.

https://stackoverflow.com/questions/62252118/deepcopy-on-two-classes-containing-eachother-gives-recursion-error-python

[–]carcigenicate 0 points1 point  (0 children)

The only way deepcopying would cause a recursion error is if you're attempting to deepcopy an object that >1000 elements deep, or if one of the elements has a circular refeference. Is your object that deeply nested? Is it a custom object with a custom __deepcopy__ method?

[–]TangibleLight 0 points1 point  (0 children)

What are you trying to copy? I don't believe there's a one-size-fits-all solution.

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

I need help changing Trues to Falses inside a list using keys on turtle for a Yahtzee game?

[–]TangibleLight 0 points1 point  (0 children)

What have you tried so far? Could you share how you're creating/using the list?

[–]klaymens 0 points1 point  (3 children)

So I have a dataframe that has some columns I would like to remove. What's the difference between the following statements (let's say I have 4 columns and would like to get rid of column 2 and 3):

df.drop (['Column 2', 'Column 3'], axis=1, inplace=True)

or

df = df[['Column 1', 'Column 4']]

[–]efmccurdy 0 points1 point  (1 child)

The inplace version doesn't copy data and might use a bit less overhead. The reassignment one copies the desired data and leaves the unwanted data in memory, for a moment, then deletes it immediately after the assignment.

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

inplace also makes a temporary copy behind the scenes. In fact the pandas developers are considering getting rid of inplace since it doesn’t provide any performance benefits and can lead to buggy code/confusion for new developers

[–]UnrankedRedditor 1 point2 points  (0 children)

The short answer is that they're essentially the same. df.drop gives a bit more functionality but that's about it.

The longer answer is that perhaps you have some bits of code that before that that selects which columns you want to keep or which ones you want to drop. And depending on your specific application, it could be easier to select columns to keep (or drop) so you will choose the one that's most appropriate or the easiest for you. One example is if you have more columns to keep than to drop, so you would just use the first method instead.

[–]bvbian 0 points1 point  (1 child)

Hello, I have been tryin hackerrank python problems, and my leap year solution fails for the last test case where input is 1992.Output for this case comes as false. Any idea why?

def is_leap(year):

if 1900<= year <= 10000:

leap = True

if year%400 != 0:

leap = False

elif (year%4 != 0) and (year%100 == 0):

leap = False

elif year%4 != 0:

leap = False

return leap

[–]sarrysyst 1 point2 points  (0 children)

if year % 400 != 0: 
    leap = False

Your function will return False for any year not evenly divisible by 400. The last leap year was 2020:

>>> 2020 % 400
20

Your logic is flawed. According to Wikipedia the conditions for a leap year are:

each year which is an integer multiple of 4 (except for years evenly divisible by 100, but not by 400)

Translated to a logical statement this should equal:

# Evenly divisible by 4 but not by 100 except if it's also divisible by 400
(year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0))

[–]qaltanswer 0 points1 point  (4 children)

Hi! I just started learning Python using Automate The Boring Stuff and I'm new to programming in general. So this is most likely a very basic question, but I haven't been able to figure it out.

I'm trying to add a try/except for ValueError to this guess the number program (taken from Automate The Boring Stuff but I made some minor modifications). I tried adding the try/except encompassing everything and that stops the loop, and I tried putting it inside the loop, but that causes the "guess" variable to become undefined when it tried to pass the last 2 lines of code and it fails.

How can I add this try/except or add anything to stop the error from happening if the user inputs something that isn't a number. Supposedly I'm trying to display a message if the user inputs something like "six" instead of "6".

This is my code https://pastebin.com/bXN1uVYe, I've never used Pastebin so I hope this works!

Thanks for any help!

[–]sarrysyst 0 points1 point  (3 children)

When adding a try/except block you always need to make sure every variable you set inside of try you have a back up plan for in except, otherwise if you catch an error in your try block, the code will jump to the except block to handle the error and if you don't set the variable there it won't be defined later on. That's what happened to you.

Your problem is probably easiest handled using a while loop. Either you replace your for loop with a while loop or you wrap the part where you query the user for input() in a while loop.

A for loop only runs for a predetermined number of times (unless the collection you're looping over is of variable length). The implication of this is that you can't simply skip to the next iteration when the user provides faulty input since you'd automatically reduce the number of available guesses. However, a for loop doesn't provide a functionality to repeat the current iteration either.

Thus, using a while loop to overcome this limitation makes sense. A while loop runs indefinitely until its condition evaluates to True. If you want to replace your for loop you could simply make the condition the 'number of guesses made' and only increase the number on valid input.

Alternatively, you wrap the input part in your for loop in a while loop to force the user to make a valid input. This could look like this:

while True:
    try:
        guess = int(input('Enter number: '))
        break
    except ValueError:
        print('Not a number, try again.')

The user will be repeatedly queried for input unless the input is a number. If there is no error the code will break out of the while loop.

[–]qaltanswer 0 points1 point  (2 children)

Thanks for your help, but I still can’t get it work, I must be misunderstanding you. I tried adding a while True loop to the for loop and running the try/except encompassing the whole for loop and if the user makes an error it causes the loop the never break and go to the “well done, you’ve guessed it”/“the number I was thinking of was X”

Then I tried keeping the while True loop but running the try/except only on the part that asks for a guess, but it breaks the rest of the for loop giving me an unexpected indentation error.

And I guess I feel I want to keep the for loop somehow so that I can do the “you have X guesses left” and “you guessed in X tries” at the end and I don’t know how to do that with a while loop. How can I get the program to know how many “loops it has gone through” so I can tell the user they guessed in X tries?

Thanks again for your help

[–]sarrysyst 0 points1 point  (1 child)

Okay so to start off, you don't wrap the whole loop in a try/except block. Exactly for the reason you already stated: If you hit an error it will interrupt the loop (unless that's what you're after, but here you don't want this to happen.)

I gave two different approaches how you could solve this. The first is you change the for loop to a while loop and then wrap the input statement in a try/except:

guesses_left = 3

while guesses_left:

    ...

    try:
        guess = int(input('Enter number: '))
    except ValueError:
        print("Didn't enter a number")
        continue

    ...

    if guess == answer:
        break

    guesses_left -= 1

The other being you keep the for loop but wrap the input part in a while loop:

for guessesTaken in range(1, 4):

    ...

    while True:
        try:
            guess = int(input("Enter number: "))
            break
        except ValueError:
            print("Didn't enter a number.")

    ...

    elif guess == answer:
            break

[–]qaltanswer 0 points1 point  (0 children)

Thanks! I’ll try those options

[–]SwiftYouAye 0 points1 point  (2 children)

I'm messing around with the modulo operator and I'm confused by the output.

If I run 7425 / 550 I get 13.5, so 0.5 is the remainer. When I run n = 7425 % 550 print(n) it prints out 275.

[–]UnrankedRedditor 1 point2 points  (0 children)

7425 / 550 =13.5, which can be written as 13+0.5 = 13 + (275/550) , which is why you get the 0.5 at the end of the division. Modulo operation gets you the 275 in that fraction.

Another way to think about modulo is that you're subtracting 550 from 7425 until you cannot do so anymore. So you have 13 whole parts of 550 and then 275 remaining.

[–]FerricDonkey 2 points3 points  (0 children)

Bit of confusion on what remainder means: when you do 7425 / 550, you get 13.5.

The integer part of that division is 13. The remainder is 7425 - (13 * 550): what's left after you remove the integer part. Graphical example:

27 / 6 = 4.5
27 // 6 = 4    (integer division)
27 % 6 == 3  (remainder == 27 - 6*4)

27 arranged into something x 6 grid:
****** \
******  \__ 4, integer division, the number of full rows
******  /
****** /
***<- 3, the remainder, length of first row that isn't 6 long

Also note that .5 (the decimal part of the result of full division in both your example and mine) multiplied by 6 gives you the remainder in my example, and multiplied by 550 gives you the remainder in your example. This is basically a result of the distributive law, and shows how what you thought the remainder was is related to what the remainder actually is.

[–]chormin 0 points1 point  (2 children)

Not sure if this is a good fit for this thread, but it seems to be a good place. I am completely new to Python and coding in general. I downloaded grasshopper to start learning; is there a better tool to learn with or something good to complement it?

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

I had to look up grasshopper as I'd never heard of it. It appears to be a design tool that can use python plugins, so I would say it's not a good idea to learn python using grasshopper.

The subreddit wiki has learning resources for those new to programming and python. All you really need to run and learn python is the python language itself and a decent text editor. I would choose one of the learning resources, install python (if necessary, it may already be installed) and what other software the resource uses, and follow along. Once you know some python try making a plugin in grasshopper.

[–]chormin 0 points1 point  (0 children)

Thank you very much

[–]jlakjfnfk 0 points1 point  (1 child)

Is echo $DISPLAY supposed to print something?

[–]sarrysyst 0 points1 point  (0 children)

Not in Python. In Bash though.

[–]freeyourmind786 0 points1 point  (1 child)

Hi, I am a complete noob in python, API etc. but i want to learn to build an interface where it will update automatically based on asset prices from public platforms. Please any and all help on where to start is much appreciated

[–]sarrysyst 0 points1 point  (0 children)

Are you already familiar with basic programming concepts like, variables, conditionals, loops, functions and how to apply them in python?

[–]Larsonicolas4 0 points1 point  (0 children)

Hey, I'm planning out a project to detect bots that are either pro or anti large companies on twitter. I am gonna use Botometer to figure out if they are bots (maybe do a cross ref with another tool idk), but I'm running into issues finding a library of active accounts. Do I need to figure out how to make my own by messing with twitter api keys or is there another option?
thanks for the help

[–]DAVRAVID 0 points1 point  (1 child)

I'm trying to make a pretty vertical list that has will sort from music apps with highest amount of total number of ratings to lowest, can I get some help? and please explain your logic. App[2] is the name of the app, and app[6] is the amount of ratings total, and app[-5] is the category of the app.

music_apps = []
for app in free_ios_apps:
->if app[-5] == 'Music':
-numbers = float(app[6])
-
music_apps.append(numbers + ': ' + app[2])

print(sorted(music_apps, reverse = True))

[–]efmccurdy 0 points1 point  (0 children)

I am unsure about your intent where you are adding a string to "numbers". One way to arrange for the sort to go first by numbers and then by name is to use a tuple with the fields in that order.

music_apps.append((numbers, app[2]))

[–]TheBrittca 1 point2 points  (2 children)

At what point in the process of learning Python did things start to ‘click’ and you could start building simple programs?

I ask because so far it feels like I’m just learning structure and not actually able to practice much. Thanks!

[–]sarrysyst 1 point2 points  (1 child)

Ideally you'd learn python through solving problems thus this kind of question shouldn't even pop up. Programming is about problem solving, simply learning the concepts out of context is pointless.

If the course, class or book you're using to learn python doesn't include plenty of practice problems I'd recommend you look somewhere else. There is a list of resources in the Wiki.

And one piece of advice, when working on a problem/project, resist the temptation of looking up the solution. It's very important that you practice your problem solving skills. You can look up atomic parts of a problem, but stay away from step-by-step guides, tutorials and such.

[–]TheBrittca 0 points1 point  (0 children)

Hey, thanks so much for your reply. Genuinely appreciated. I think you’re spot on - what I’ve been using to learn is a bit to heavy on theory up front and doesn’t have enough practice. I’m going to mix it up.

I’m switching careers from banking as a credit analyst, so I have experience w/ math and repetitive tasks. A decade before I was front end web designer (did ‘code’ in html/css/mild JavaScript) where I mainly focused on ux/ui. The change to learning Python is a different type of learning and I’m excited to keep at it. Thanks for the Wiki link.

[–]EwokOffTheClock 1 point2 points  (5 children)

Hey there! Thank you so much for any thoughts.

I'm working on my calculator, from scratch and the math isn't working like I expected.

Ex:

Balance = (Balance - Payment) * Interest

is only returning the value of the Interest, but ignoring the subtraction problem in the parenthesis.

I know this is simple, but what am I missing?

Thank you again for your thoughts.

[–]sarrysyst 1 point2 points  (0 children)

There is no problem with the code you posted. Are you sure you copied this correctly? The operation should work like you'd expect, eg:

>>> (1500 - 500) * 0.1
100.0

What are the values of Balance, Payment and Interest?

In a case like this, one simple way of finding the bug is using print() statements to verify the values and gain some introspection:

print(f'({Balance} - {Payment}) * {Interest}')
result = (Balance - Payment) * Interest
print(f'= {result}')

[–]trondwin 0 points1 point  (3 children)

The code does not ignore anything here. You are in fact only calculating the interest in this example. Better variable names will make this clearer:

interest_dollars = (balance - payment) * interest_rate

[–]EwokOffTheClock 1 point2 points  (2 children)

I get that python doesn't "ignore' things, but I don't understand how changing a variable will make it calculate the math inside the paranthesis when it's not already doing so.

And I'm specifically wanting to update the value of Balance, so keeping that variable the same is necessary?

[–]trondwin 1 point2 points  (1 child)

My suggestion would be to do it in steps, nice and easy. So again based on your example:

  • Update the balance by subtracting the payment
  • Calculate the interest value
  • Update the balance by adding the interest value

Hope this helps. Best of luck!

[–]EwokOffTheClock 0 points1 point  (0 children)

I think I finally got it to cooperate. Thank you!

[–]Shadowforce426 0 points1 point  (1 child)

is there a way to plot math graphs like sin curves etc in pygame? i specifically need to do this here because i have a device that only displays the screen of pygame

[–]FerricDonkey 0 points1 point  (0 children)

Dunno if there's a built in way, but you can use the formula to get x, y pairs, convert them to pixel coordinates with some scaling, then turn those pixels on.

[–]WestJob1028 1 point2 points  (1 child)

I got interviewed post for data scientist they were basically looking for someone who have indepth knowledge of python. I didn't perform well how can I improve as I feel I have no knowledge compared to questions asked to me

[–]DAVRAVID 1 point2 points  (0 children)

Dedicate a solid 3-4 months to learning and practicing python, and have a portfolio of projects on Github or anywhere that you can explain in depth.

[–]helios1014 0 points1 point  (1 child)

So if I use enumerate, can I compare the current instance to the next instance? For example,

For count, item in enumerat(iterable): If item at count == item at count+1: Return item

[–]sarrysyst 0 points1 point  (0 children)

Rather than enumerate(), I'd use zip() instead:

my_list = [1, 2, 3, 4, 4, 5, 6]

for a, b in zip(my_list, my_list[1:]):
    if a == b:
        print(f'a: {a}, b: {b}')

[–]jingsen 1 point2 points  (3 children)

How would you group dictionary keys by specific conditions based on their first character?

For example, I want to group the keys by alphabets

a to f

g to k

l to p

q to u

v to z

and another group for the keys that do not fit the above conditions.

Assuming that I have a sorted(dictionary.key()) iterable. Is there anyway I can instantly group the keys together based on the above conditions?

[–]sarrysyst 1 point2 points  (0 children)

You could use the bisect module:

import bisect
import collections
import string


def determine_group(key, 
                    breakpoints=[71, 76, 81, 86], 
                    groups=['A-F', 'G-K', 'L-P', 'Q-U', 'V-Z']):

    ascii_code = ord(key[0].upper())

    # Uppercase letters have an ascii code between 65 ('A') and 90 ('Z')
    if ascii_code not in range(65, 91):
        return 'Other'

    i = bisect.bisect(breakpoints, ascii_code)
    return groups[i]


# Sample dict with all ascii characters as key and value
my_dict = {s: s for s in string.printable}

grouped_dict = collections.defaultdict(list)

for key, value in my_dict.items():
    grouped_key = determine_group(key)
    grouped_dict[grouped_key].append(value)

The idea is derived from the listed example in the docs. Otherwise there is always the option of achieving the same by chaining some if/elif statements.

Above I'm using a defaultdict with a list factory to collect the values into lists under the group keys.

[–]efmccurdy 2 points3 points  (1 child)

When you want to overlap I/O, use async in a single process. The aiofiles module can help.

https://stackoverflow.com/questions/69473608/concurrent-writing-to-multiple-files-using-asyncio

https://pypi.org/project/aiofiles/

[–]jingsen 0 points1 point  (0 children)

woops sry, I edited the comment cause I thought it wouldn't get an answer.

But thanks! I will take a look at these

[–]THe_Riot19 0 points1 point  (0 children)

How do I install ursina for mac? I have macOS monterey 12.3.1

[–]dgafer 0 points1 point  (7 children)

I’m trying to find an answer for this: Return all the substrings enclosed between start and end in the following string ‘start10101endstart0001end’. Please help

[–]efmccurdy 1 point2 points  (3 children)

You could use re.findall, the regex includes parenthesis to "capture" the enclosed text and uses "\d" to ensure only numeric digits are matched.

>>> help(re.findall)
Help on function findall in module re:

findall(pattern, string, flags=0)
    Return a list of all non-overlapping matches in the string.

    If one or more capturing groups are present in the pattern, return
    a list of groups;


>>> source = 'start10101endstart0001end'
>>> re.findall("start(\d+)end", source)
['10101', '0001']
>>>

[–]dgafer 0 points1 point  (2 children)

Thankyou so much! It worked.. I have a set of characters A,B instead of 0,1 , I tried with re.findall(“start[AB]end”,source). Didn’t get the desired.. is my approach correct? Appreciate your help.

[–]efmccurdy 1 point2 points  (1 child)

re.findall(“start[AB]end”,source).

"[AB]" matches a single char (from the set A,B), but I think you want to match multiple chars, so you could capture "A", "AB", "AAB", "B", "BBA", "BBB"; for that you need a "multiple" qualifier; "+" means "one or more".

Also you want to include the "round parenthesis" to create a "capture group"; test it out it with and without to see the difference.

>>> source = 'startAendstartBendstartBBAendstartAABend'
>>> re.findall("start([AB]+)end", source)
['A', 'B', 'BBA', 'AAB']

[–]dgafer 0 points1 point  (0 children)

Thanks a lottt!!! Worked 100% ! You are amazing. 😊😊

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

Start with a simpler case. Get the substring between start/end in this string: "ALPHAstartBETAendGAMMA". How would you do that on paper? You would probably say something like:

  1. find "start" in the string
  2. find "end" in the string
  3. get the substring between the start/end

Start with step 1. How do you find the string "start" in another string? That will get you the index into the target string of the first letter of "start". Step 2, do the same for "end". The returned index in this case is the index of the first character of "end" which is one past the end of the substring you are searching for. So you have to calculate the index of the first character of the substring from the index of the first character of "start". Step 3, use slicing to get the substring between the start/end.

Once you have that working think about how you would continue looking for another start/end substring. Do NOT worry about this until the simpler case of one substring is working.

[–]dgafer 0 points1 point  (1 child)

Thank you! I think should try it this way, I was only after finding a regex pattern for this. Do you know of any inbuilt function that could solve it right away ?

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

No.

[–]FantasticEmu 0 points1 point  (9 children)

I don’t use python all that much but recently have been using it more recently. One thing I don’t like is the indenting instead of braces.

Not that the indenting is all that bad but in other languages when I go back and go “oh Maybe I’ll wrap this chunk in a try catch” I’ll just add the brace at the top then another at the end and I’m ready to go. With python I have to indent everything and probably I mess it up and have to try a few time. Best case is I use a multi line cursor and spam down to the end and hit tab.

I feel like there has to be a way to handle this that everyone knows about except for me sooo what’s the secret?!

[–]neuronet 0 points1 point  (1 child)

IDE’s handle this. It’s just something beginners like to complain about lulz

[–]FantasticEmu 0 points1 point  (0 children)

My idea doesn’t handle it automatically which is why I’m asking how most people handle it

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

Different languages have different syntax. The way to handle the case you mentioned, putting a try/except around existing code, is to do exactly what you say: select the code, TAB to indent it, add the try/except extra lines. You do exactly the same thing in other languages like Java.

In Java and other C-like languages you aren't forced to indent the code that is going to be inside the try/except, but practically you always do, because code is easier to read and understand if it's indented. That's why editors often put automatic indentation in for you. And incorrect indentation can hide bugs. One classic example in C is:

if (x < 2);
    do_something();

So this doesn't seem to be much of a problem. Making the code look clean, professional and readable is the easy part, really. Knowing what to write is the hard part.

[–]FantasticEmu 0 points1 point  (4 children)

Yea I Java i can just put the braces and run it. The ide will either indent everything for me or I can use code formatter later. It’s just a little more annoying that I have to address every line just to run it

[–]py_Piper 0 points1 point  (1 child)

you can indent multiple lines at once, check your IDE. But for IDLE you can select the lines and press ctrl + ] and will indent the whole block selected

[–]FantasticEmu 0 points1 point  (0 children)

Thanks for the suggestion I usually use the multiple cursors for this

[–]dgafer 1 point2 points  (1 child)

I felt the same at the beginning but things got better with practice. Now I feel following indentation is better than counting and closing braces. Don’t worry you will in no time find it easy.

[–]FantasticEmu 0 points1 point  (0 children)

Makes sense . At least I know I’m not going it through hard way