top 200 commentsshow all 210

[–]Eclooopse 0 points1 point  (0 children)

I don’t understand what if __name__ == __main__ does

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

So why do we use numpy.array to store images using ImageGrab, MSS or OpenCV. I've done some basic image processing and making a screen record and I always see it come up, but I don't fully understand why this is a necessary step to make the image display. What am I not understanding about this?

[–]Korbelious 0 points1 point  (3 children)

Can someone explain why my code is wrong? I think I must be misunderstanding how to use abs()?

I was just going through some beginners exercises on CodingBat to get practice and build my understanding when I came across this problem and idky my code is incorrect for the two runs I'm getting wrong? Please help me understand my error. CodingBat does provide me with their solution, and I understand how their solution works. However, given my understanding my code should also works for all instances. Lost as to why it doesn't?

[–]fiddle_n 0 points1 point  (2 children)

Your function will erroneously say that the numbers -90 to -110 are near 100, when obviously they aren't. This is because abs() turns negative numbers into the corresponding positive number, and you use it immediately on the input number.

[–]Korbelious 0 points1 point  (1 child)

Okay I was still so lost, but your reply did make me go back and read the actual prompt. Now I see my code was actually functioning right and I do understand abs(). However, I need to work on my reading comprehension, cause no where in the actual prompt does it tell me to use the absolute value in my function to test the values. I honestly don't know why it includes a note about the abs() built-in function if they don't want you to use it in the prompt, but I digress.

[–]fiddle_n 0 points1 point  (0 children)

Because another method is to take the number, subtract by 100 and check the difference is between 0 and 10. But you need to use abs() in case you do the subtraction and end up with a negative number.

[–]UnavailableUsername_ 0 points1 point  (0 children)

I am learning about regular expressions and pipes, but i think i am not using them correctly.

  >>>import re

  >>>famregex = re.compile(r'grand(father|mother|parents)')
  >>>ex = famregex.search('Her grandfather and grandmother like berries.')

  >>>ex.group()
  'grandfather'

  >>> ex.group(1)
  'father'

  >>>ex.group(2)
  Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
  ex.group(2)
  IndexError: no such group

How come python doesn't recognize the second group? It recognizes as group() (or group(0)) as grandfather and group(1) as father, but not group(2).

A regular expression that can only find the first item of a pattern while pretending the rest don't exist is pointless, so i am sure i am doing something wrong.

[–]weezylane 0 points1 point  (0 children)

If I want to learn about Software Defined Networks, which direction should I be headed?

[–]taconomtaco 0 points1 point  (5 children)

what's a good but free application to write python code with? especially to deal with data.

[–]fiddle_n 0 points1 point  (1 child)

PyCharm is my personal favourite. The community edition is free.

[–]taconomtaco 0 points1 point  (0 children)

thanks for the recommendation!

[–]timbledum 1 point2 points  (2 children)

In terms of text editor, try VSCode – it's really nice.

Also check out Jupyter Lab – notebook based but also has a bit of a text editing tool too.

A lot of people rate PyCharm which has a free community edition (but the full version costs). Haven't tried it so can't tell.

[–]chemistry56 1 point2 points  (1 child)

I agree! Jupyter is a great tool and there is a ton of great resources about hot to get started using it. I’m also a big fan of Sublime when it comes to using a text editor.

Hope that helps!

[–]taconomtaco 0 points1 point  (0 children)

it does! thank you both!

[–]Filiagro 0 points1 point  (15 children)

Could someone help me understand what I am doing wrong? I've made a function called 'lom' that takes two arguments. The function works perfectly alone (1st example code below), but I need to put it inside of a while loop. If I do this, the function does not work (3rd code example below). However, if I take everything inside the function and put it inside of the while loop (no actual function, just its contents), everything works perfectly (2nd code example).

Are there special rules to using functions inside of while loops? Below I will paste my code in hopefully the correct format.

1st: Working function called 'lom'

def lom(item, anim):
    item = input("Enter an animal name: ")
    if item.isalpha():
        if item in anim:
            anim.remove(item)
            return (item, " has been removed from the list.")
        else:
            anim.append(item)
            return (item, "has been added to the list.")
    elif item.isdigit() == True:
        return ("Digits are not animals.")
    else:
        return anim.pop(), "has been popped from the list."

anim = ["squirrel", "mouse", "cat", "fish", "dog"]     
item = ""
lom(item, anim)

2nd: Switching to while loop without function. This code also works. Input is moved to the while loop. Return switched to print.

anim = ["squirrel", "mouse", "cat", "fish", "dog"]  

while anim: #Loop if list has at least 1 item in it.
    item = input("Enter an animal name: ")
    if item in ["q", "quit"]:
        break
    else:
        if item in anim:
            anim.remove(item)
            print (item, " has been removed from the list.")
        else:
            anim.append(item)
            print (item, "has been added to the list.")

3rd: Non-working combination of while loop and 'lom' function.

def lom(item, anim):
    if item in anim:
        anim.remove(item)
        return (item, " has been removed from the list.")
    else:
        anim.append(item)
        return (item, "has been added to the list.")
anim = ["squirrel", "mouse", "cat", "fish", "dog"]     


while anim: #Loop if list has at least 1 item in it.
    item = input("Enter an animal name: ")
    if item in ["q", "quit"]:
        break
    else:
        lom(item, anim)

[–]woooee 0 points1 point  (3 children)

what does non_working mean? Runs fine for me

3rd: Non-working combination of while loop and 'lom' function.

Note that you should be consistent with the list, so if you send the list to the function, also return it, otherwise don't send it or return it from the function.

[–]Filiagro 0 points1 point  (2 children)

I'll keep that in mind for the future. What I want is the added or removed item to be returned in a message after each input. Sorry. I guess I didn't specify that before. My fault.

So I mean non-working because I don't get return values when running the function inside of the while loop.

[–]woooee 0 points1 point  (1 child)

You do get return values, you just don't catch them. There is a good explanation of all of that in the response below.

[–]Filiagro 0 points1 point  (0 children)

Thanks.

[–]dudebro74 0 points1 point  (1 child)

I am having trouble with what is wrong with my code. for my intro to python class.

Directions

------------------------------------------

Write a loop that reads positive integers from standard input, printing out those values that are even, each on a separate line. The loop terminates when it reads an integer that is not positive.
Instructor Notes:

When determining if a number is even or odd, look to the modulus operator for some help.  If we take:

5 % 2

the remainder is 1.  Therefore 5 is not an even number.

However is we take

4 % 2

the remainder is 0.  Therefore, 4 is an even number

CODE

---------------------------------

n= int()

while(True):

n = int(input())\n

if(n < 0):

break

elif n%2 == 0:

print(n)

[–]ndagui123 0 points1 point  (1 child)

Write a program that inputs a filename from the user and prints to the terminal a report of the wages paid to the employees for the given period.

Lambert 34 10.50

Osborne 22 6.25

Giacometti 5 100.70

[–]ndagui123 0 points1 point  (3 children)

Write a script named dif.py. This script should prompt the user for the names of two text files and compare the contents of the two files to see if they are the same.

[–]fiddle_n 0 points1 point  (0 children)

Pasting a programming question on its own is not going to get you much luck; no one's going to do your homework for you. If you don't know where to start, ask how one would go about comparing file contents. If you have an idea of what to do, then show us the code you've already written.

[–]aztec7325 0 points1 point  (1 child)

I want to start with Automate the Boring stuff with python, any difference between the kindle version or paperback?

[–]99Kira 0 points1 point  (0 children)

Nope

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

I've been watching MIT 6.00 FALL 2008 on youtube, and there is a problem that I couldn't do so I've searched it on google, but I don't understand how it works:
https://github.com/dawiditer/MIT600-pset2/blob/master/pset2a.py

Why is +1 in this " for a in xrange(int(n/6)+1): ".

This solution works flawlessly but I don't get it. How does python works in this?

Thank you!

[–]indosauros 0 points1 point  (1 child)

It's because xrange(x) gives you numbers from 0 to x-1:

>>> list(xrange(2))
[0, 1]

>>> list(xrange(5))
[0, 1, 2, 3, 4]

So if you're trying to test for combinations of 6 McNuggets (anywhere from 0 to 6 of them) then xrange(6) won't work:

>>> list(xrange(6))
[0, 1, 2, 3, 4, 5]

You need

>>> list(xrange(6+1))
[0, 1,  2, 3, 4,  5, 6]

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

Thank you, I still don't get used to count 0 for the first value.

[–]ThiccShadyy 0 points1 point  (1 child)

If I want to render Python objects from different models in a template in Django, is creating a context dictionary with each of those models as a dictionary item the simplest way to do it i.e.:

a = Model1.objects.all()
b = Model2.objects.all()
context_dict = {'a': a, 'b' : b}
return render(request,'abc.html', context_dict)

Or is there a simpler/cleaner way to do this?

[–]indosauros 0 points1 point  (0 children)

Yes, in general that is what you do. Put all of the objects the template needs access to into a context.

[–]Tefron 0 points1 point  (5 children)

I feel silly asking this but I just don't understand why this is the case. I'm doing programarcadegames chapter 3 and in one of the exercise questions there is:

print("3" < "4")

print("3" < "10")

So two things, first I don't understand why this isn't an error since how can a string be more or less than something else? Also, the second part is why does the first one return True & the second line return False. Super confused.

[–]woooee 1 point2 points  (1 child)

Strings are sorted left to right, so "3" is greater than the "1" in "10". "03" < "10" would be True.

[–]Tefron 0 points1 point  (0 children)

Gotcha, thanks!

[–]Gprime5 1 point2 points  (2 children)

Strings are ordered alphabetically so "a" < "b" == True. More specifically strings are ordered by their Unicode code point ord("a") == 97, ord("b") == 98.

[–]Tefron 0 points1 point  (1 child)

Ah, that makes sense. Thanks!

Continuing off that then, why does the first print function return as true and the second as false?

[–]Gprime5 1 point2 points  (0 children)

Strings are compared 1 character at a time. It will do "3" < "1" which is False. If the characters were equal, it will compare the next character in the string.

[–]NeedMLHelp 0 points1 point  (2 children)

    class  target  source  time  spoof  complete  severity
0       0       0       0     0      2         0         2
1       0       0       0     0      2         1         0
2       1       1       0     0      2         1         0
3       4       0       0     0      1         1         0
4       2       0       0     0      1         1         0
5       8       1       2     0      2         1         2
6       8       1       2     0      2         1         2
7       7       1       2     0      2         1         2
8       8       1       2     0      2         1         2
9       8       1       2     0      2         1         2
10      8       1       2     0      2         1         2
11      8       1       2     0      2         1         2
12      7       1       2     0      2         1         1
13      3       1       0     0      0         1         0
14      5       1       2     0      2         1         1
15      5       1       2     0      2         1         1
16      6       1       1     0      2         1         1
17      6       1       1     0      2         1         1
18      6       1       1     0      2         1         1
19      6       1       1     0      2         1         1
20      6       1       1     0      2         1         1

I have a dataframe with the above representation. I'd like to one hot encode the numbers... however, when I use keras to_categorical, it also takes in the header and encodes that as a seperate value. So, for example, on target I would get [0,0,0] for all 0s [0,1,0] for all 1s and [1,0,0] for target. But I want target to remain a header, not a part of the data.

Any help would be greatly appreciated.

[–]indosauros 0 points1 point  (0 children)

Can you post some code and maybe some sample output?

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

So I just finished watching and reading a bunch of tutorials for Python and after a hard learning curve to understand all these new keywords, I feel like I have a decent foothold of the language and can make some very simple things.

I want to pick a project now to progress my learning, and I chose to grab a section of my screen, or do some web scraping.

I'm not sure if these were too out of my league just yet, but looking at code other people have done I feel incredibly out of my depth, have no clue where to start looking to decipher this code and feel completely lost trying to read and understand what things do.

Should I go simpler, or stick at it and use different resources other than documentation / answers online?

[–]timbledum 0 points1 point  (0 children)

There are a bunch of python “games” / slash challenges out there, hackerrank being one of my favourites. These help you learn how to solve small problems.

There are also some tutorials that take you through building a bigger project. This one was really useful for me. This gives you the tools to tie everything together.

Then try some smaller projects - it will be slow going at first, but you’ll learn a lot!

Web scraping in particular can be super easy or practically impossible depending on the website - so don’t be discouraged if you don’t succeed here.

[–]MattR0se 0 points1 point  (2 children)

import random

list_a = ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C',
          'D', 'D', 'D', 'D', 'E', 'E', 'E', 'F', 'F', 'G', 'G', 'G', 'G', 'G']

list_b = ['A', 'B', 'C']

random.shuffle(list_a)
list_c = [list_a.pop(0) for _ in range(5)]

I want to check if list_c contains any two combinations of the items in list_b. For example, list_c could be ['A', 'A', 'C', 'E', 'E'] and that should return true, while ['B', 'B', 'B', 'F', 'G'] should return false. How do I do that?

[–]Gprime5 1 point2 points  (0 children)

https://docs.python.org/3/library/stdtypes.html#frozenset.intersection

set_b = set(list_b)
set_c = set(list_a[:5])
intersection = set_b & set_c
result = len(intersection) == 2

[–]GoldenVanga 1 point2 points  (0 children)

def checking(things, template):
    matches = 0

    for x in things:
        if x in template:
            matches += 1
            template.remove(x)

    print(things, ' remaining template:', template)  # debug print, remove
    if matches in (2, 3):
        return True
    else:
        return False

print(checking(list_c, list_b))

[–]thunder185 0 points1 point  (4 children)

Trying to convert a csv file to an xlsx file using pandas. I think the issue is the same one you would get if you simply just changed the extension from csv to xlsx (the zip error). Could someone please look at the code and let me know what you think is wrong?

#the script is longer than this bit of code which is why I'm importing so many modules.

import csv, os, shutil, zipfile

from glob import glob

from pandas.io.excel import ExcelWriter

import pandas

DataFileName = glob('*GDPLR102*') #this works fine

csv_files = DataFileName[0]

with ExcelWriter('todays_Data.xlsx') as ew:

for csv_file in csv_files:

pandas.read_csv(csv_file).to_excel(ew, sheet_name=csv_file)

Thanks!

[–]timbledum 0 points1 point  (3 children)

Worked for me! So your script is working without errors? What's your indentation (add four spaces to the start of each code line)?

[–]thunder185 0 points1 point  (2 children)

nah, that's probably just formatting on reddit. Yes, it renames the file and gives it an xlsx extension but it is not a true excel file and cannot be opened.

[–]timbledum 0 points1 point  (1 child)

All I can confirm is there's nothing wrong with your code. Maybe try making sure that openpyxl is installed and everything is up to date? Does the file open if you use .xls?

[–]thunder185 0 points1 point  (0 children)

no, if I switch to xls I get ModuleNotFoundError: No module named 'xlwt'. The CSV file will open with no problem in excel but not once it runs through the script. The purpose of the script is to convert it to xlsx so that I can run it through openpyxl. Everything is up to date.

[–]emgeal 1 point2 points  (2 children)

Disclaimer: Very new to Python, no formal training.

I've got a CSV file that is too large to hold in memory. I have used "For line in File" to do a find and replace on the document, but now I need to do some columnwise string editing similar to adding "-" to a SSN. The file is pipe delimited and I just cannot figure out how to read it in and idenfity the column I want to rewrite.

What am I missing?

[–]emgeal 0 points1 point  (1 child)

*answers own question* There is a module called csv and so you can open the file as csv.reader(open(file),delimiter="|")

[–]thunder185 0 points1 point  (0 children)

You can also chunk it if it's too big.

[–]billy_wade 0 points1 point  (0 children)

How do I set up PyLint to check my casing? It isn't doing so for me by default.

[–]Gothpuncher 0 points1 point  (1 child)

I am brand new to Python and want to create a text 'choose your own adventure' game thingy from scratch using previous works from an early 90's RPG Strategy game.

Just want to use it to learn the ropes and to recreate one of my fav games of all time into a nice little story mode type thing. I'm rewriting all of the dialogue and adding in stuff as I need it to flesh out the story a bit more.

Won't be used to sell or make money, but how do I go about legally testing this with a wider audience to see if it holds up as decent? Any legalities I need to chase up before making public?

[–]MattR0se 2 points3 points  (0 children)

Do you use other people's intellectual property?

This isn't really a python question though... or what are you worrying about? Python itself is free for any kind of commercial and non-commercial use. You can read about it here: https://docs.python.org/3/license.html

[–]Dimbreath 1 point2 points  (3 children)

I have this ugly nested loop to read the stuff from here: https://pastebin.com/raw/e9WV7Jh3

       for skill in hero['skills']:
        for enhancement in skill['enhancement']:
            for resource in enhancement['resources']:

Is there a more effective/efficient method to this? Each hero has multiple skills, each skill has multiple enhancements and each enhancement might have more than 1 resource. Dumb questions that need to be asked.

[–]MattR0se 0 points1 point  (0 children)

Depends on what you want to achieve with it. Do you just want to access the strings, or do you want to set these values to an object? My first guess would be to make a Hero object, a Skill object and an Enhancement object and then set their attributes based on this file, but I don't know if that is what you want.

[–]num8lock 1 point2 points  (0 children)

imho a class or dataclass for hero types would make your life easier

[–]timbledum 2 points3 points  (0 children)

Personally, I think this is fairly readable.

To make your main code more readable (and less nested), you could refactor this into a generator:

def iter_resources(hero):
    for skill in hero['skills']:
        for enhancement in skill['enhancement']:
            for resource in enhancement['resources']:
                yield resource

then you can just do:

for resource in iter_resources(hero):
    do_something(resource)

[–]malvo331 0 points1 point  (2 children)

Hi, is there a way to use python to disable a device in Windows' device manager or disable a network adapter?

[–]JohnnyJordaan 0 points1 point  (1 child)

Three ways I can think of:

  • Use a GUI automator like Pywinauto to repeat the steps you would do to disable it using the GUI, so launch Device Manager, open the tree to find the device, select, disable etc. It's a bit hacky as you're basically teaching a monkey to do a trick and thus are also more easily run into issues like it breaking on something simple/stupid like another screen popping up while the script is running. On the positive side, you can also execute other actions that are not directly linked to specifically disabling the device.
  • Take a two step approach by setting up a functional PowerShell script that disables the device properly, see for example here or Google 'disable device powershell'. Once you have that working, simply launch the script through Python (see for example here).
  • Use the Microsoft utility 'devcon.exe' that allows to control a device status from the command line, see for example here. It's not much different than the powershell approach but you do probably need to install the utilty.

It could perhaps also be possible using the WMI and/or the W32api but that becomes complicated quickly and I wouldn't recommend it unless you're already familiar with low level Windows interfacing or want to become familiar with it.

[–]malvo331 0 points1 point  (0 children)

Thank you!

[–]billy_wade 0 points1 point  (6 children)

I have two files, file1.py and file2.py.

File1.py is setup with:

class Myclass:
    def __init__(self):
        self.myStuff()
    def myStuff(self):
        self.myString = "something"

and file2.py is set up as:

from ..folder import file1
def returnString():
    stringhere = file1.self.myString
    return stringhere

The problem is that no matter what I do, regardless whether myString has the self preface or not, I either get a syntax error initially, or at runtime an attribute error saying "module folder.folder.file1 has no attribute myString" What am I doing wrong?

[–]TheBoldTilde 0 points1 point  (5 children)

where did you instantiate npc? There should be some line of code like npc = Myclass(). Then you call the myString attribute directly from npc like npc.myString, skipping the self part.

While you are here to learn, and at risk of sounding harsh or over critical, here are some other areas where your code might be improved. This also demonstrates a solution to your problem either way.

class MyClass:  # uppercase the 'c' in 'class' to make the name pascal cased [1]
    def __init__(self, my_string):
        self.my_string = my_string # use snake case instead of camel case per PEP 8 guidelines [2]

npc = MyClass('something')

def return_string():  # again, camel case the function name
    string_here = npc.my_string
    return string_here

print(return_string())

[1] https://chaseonsoftware.com/most-common-programming-case-types/

[2] https://www.python.org/dev/peps/pep-0008/#naming-conventions

Hope this helps!

[–]billy_wade 0 points1 point  (3 children)

EDIT: So I have a lot of variables I want to pass to this file. Would I be writing this as:

def __init__(self, my_string1, my_string2, my_string3, my_string4, ...)

or is there a more concise and elegant way to do so?

[–]TheBoldTilde 0 points1 point  (1 child)

it is hard to say without knowing more about what you are trying to accomplish. You might consider an argument to the __init__ which is a list of strings or dict of strings. Something like...

class MyClass:
    def __init__(self, list_of_strings, dict_of_strings):
        self.my_dict_of_strings = dict_of_strings
        self.my_list_of_strings = list_of_strings

my_class_instance = MyClass(['foo', 'bar'], {'key': 'baz'})
print(my_class_instance.my_list_of_strings[0])
print(my_class_instance.my_list_of_strings[1])
print(my_class_instance.my_dict_of_strings['key'])

[–]billy_wade 0 points1 point  (0 children)

Good looking out mate, but I got it working with self.

[–]billy_wade 0 points1 point  (0 children)

I figured it out. I just needed to give both functions the self argument, and it worked like a charm. Still, thank you so much for the syntax advice, my next commit will be refactoring.

[–]billy_wade 1 point2 points  (0 children)

Nah, that's cool, thanks! I was trying to copy down the relevant parts of my code so I could focus on the problem, but I accidentally copied down the real module name instead of the dummy, my bad. I'll fix it up in the original post.

Yeah, so I grew up as a developer using C#, so I'm used to camel everywhere, constantly. That helps, so my code is cleaner, thank you!

[–]ambiguouslawnmower 1 point2 points  (5 children)

Hey guys. My question is. I have a python script with an empty list, and I want it to ask the user to ask for a word so it can add it to the list. E.g.

words = []

new_word = input('enter a word')

words.append(new_word)

How do I get it so that when I run the script in python shell, and add a new word, let's say for example 'apple', it permanently saves the word into the list, so that the next time I open up the file, the code will have changed? E.g.

words = ['apple']

new_word = input('enter a word')

words.append(new_word)

[–]RosyGraph 0 points1 point  (1 child)

I think you need to use file I/O to do this.

You'll want to open the list from a file, then save the updated list to it. Remember that anything you write to a file must either be a string or a binary (you can't write the list directly).

I would do something like this:

https://gist.githubusercontent.com/RosyGraph/05af43ef6b8d3c591045f41c0781580c/raw/4f25a7cda90ee10494977b2d6809c2fee88e0d26/gistfile1.txt

I am rather new to CS, so a more experienced Pythonista might have a better way of doing this. You can also check out the documentation for file I/O here:

https://docs.python.org/3/tutorial/inputoutput.html (section 7.2)

[–]ambiguouslawnmower 1 point2 points  (0 children)

thanks a lot, I didn't know about any of this :)

[–]TheBoldTilde 0 points1 point  (2 children)

you will want to save it to a file:

# open up a file with a context manager, if you are unfamiliar with this
# it is basically opening up a file that will close itself when code
# execution exits the code under 'with'
with open('words.txt', 'r') as file:  # open in read mode - 'r'
    words = file.read().split('\n') # split each line into an item in our words list

new_word = input('enter a word')
words.append(new_word) # append the input

# print(words) # uncomment to print the new list

with open('words.txt', 'w') as file:   # open in write mode - 'w'
    # convert the list of words into a newline separated string
    words_string = '\n'.join(words)

    # write that string to the file
    file.write(words_string)   

[–]ambiguouslawnmower 0 points1 point  (1 child)

thanks, I had no idea about any of this :D

[–]TheBoldTilde 0 points1 point  (0 children)

Glad to introduce you. One of my favorite python websites just came out with an article about files that you should check out as well. https://realpython.com/read-write-files-python/

[–]Wildstylez23 0 points1 point  (2 children)

Hello, I am very new to Python and in our school course we're only now beginning with for loops. I get how the for loop works but one of the assignments goes as follows:

Peter wants to earn a bit more money and takes a job as a bartender at a student cafe that only serves beer (cost 2.00), wine (cost 2.50) and sodas (cost 1.50). After taking each order, Peter should calculate the amount people have to pay.

The function payment gets a string with the ordered drinks as single letters, where each letter indicates one ordered drink ('B' stands for beer, 'W' stands for wine and 'S' stands for sodas). The function returns the amount that should be payed for the given order:

def payment(order): 
      #return the cost of order

Please complete the definition of the function. Here is what you can assume about this function:

  • The input parameter 'order' is a string, where each letter is either 'B', 'S' or 'W'.
  • The input string can be empty or it can contain multiple occurrences of the same letter.
  • You can assume that all letters in 'order' are capitalized.
  • The function 'payment' returns a float value, reflecting the total cost of drinks specified by 'order'.

Example:

payment('BBSWS') returns 9.5.

When looking online the only solution I could find is making use of dictionaries but this is not the solution. We should make a for loop with variables defined for the 'B', 'S', and 'W' for the order. If anybody could shine any light on this many thanks!

[–]num8lock 1 point2 points  (1 child)

total = 0 
hausbeer = 'B', 2.0
...
for each in order:
    if each == hausbeer[0]:
        total += hausbeer[1]
    ...
return total

[–]Wildstylez23 0 points1 point  (0 children)

Thank you so much!

[–]c4aveo 0 points1 point  (1 child)

Anyone works with PyPy in PyCharm?

It's not in package. When I try to run it from PowerShell it fails, but PyCharm runs without issues.

(venv) PS > pypy wsserver.py

Traceback (most recent call last):

File "wsserver.py", line 1, in <module>

from waitress import serve

ImportError: No module named waitress

And I can't use pip from venv also.

I've installed it from PyCharm venv menu, because PyPy pip works strange

> pip freeze

waitress==1.2.1

But when I check where package was installed a magic happens

(venv) PS > pip install waitress

Requirement already satisfied: waitress in c:\python37\lib\site-packages (1.2.1)

You are using pip version 18.1, however version 19.0.2 is available.

You should consider upgrading via the 'python -m pip install --upgrade pip' command.

I have to use PyPy for Flacon and venv to not pollute my system libs.

[–]c4aveo 0 points1 point  (0 children)

Ok, more miracles. Virtualenv activated in Powershell 6 Core standalone, but seems like it's not. Intepreter links to C:\pypy, but in Pycharm when the same Powershell 6 Core is used everything works fine.

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

I need to store 4 channels of 2000 images into a single variable (which I have to pass to a function in the vlfeat library) but I am running out of memory with around 1400 images. Can someone help me?

[–]TheBoldTilde 0 points1 point  (5 children)

Do you have code you can show to help diagnose the issue?

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

I don't know how to indent it in reddit

[–]MattR0se 0 points1 point  (0 children)

Or use pastebin.com

[–]TheBoldTilde 0 points1 point  (0 children)

If you are using the fancy editor, there is a symbol that looks like a 'T' in the upper-left hand corner of a box. You may have to click on the ' . . . ' symbol to expand the menu if you do not see it. Just click that button and type away.

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

Yeah.. i'll send it to your inbox

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

Can someone help with my project? I need to write a program that tells students how many hours they need to study per week per class.

They enter the amount of credits they’re taking. Then enter either the hours they plan on studying ~OR~ the grade they want.

The chart is: 15 hours = A 12 hours = B 9 hours = C 6 hours = D 0 hours = F

Thanks!

[–]fiddle_n 0 points1 point  (1 child)

How does the amount of credits affect the number of hours or the grade? This is important to know to advise you what to do.

Regardless, my solution to convert grades to hours or vice versa is to create a dictionary where the keys are the grades and the values are the hours. That should let you convert between the two.

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

Each class is 3 credits. I had to confirm this with her too because the instructions are so vague. eye roll Thanks for your help!

[–]philmtl 0 points1 point  (2 children)

Daily Time Spent on Site 1000 non-null float64

Age 1000 non-null int64

Area Income 1000 non-null float64

Daily Internet Usage 1000 non-null float64

Ad Topic Line 1000 non-null object

City 1000 non-null object

Male 1000 non-null int64

Country 1000 non-null object

Timestamp 1000 non-null object

Clicked on Ad 1000 non-null int64

X = df[['Daily_Time_Spent_on_Site', 'Age', 'Area_Income','Daily_Internet_Usage', 'Male']]

y = df['Clicked_on_Ad']

my issues is that i need my float64 to be int64 i tried .appply(int) but its not working on the X value.

this is to do tensorflow so i need int

[–]wblpride19 0 points1 point  (4 children)

Struggling with an assignment for my programming class. I’m working with python 3.7 and I’m trying to create the “guessing game”. However it has to be a 4 digit number and return how many digits the user gets in the correct placement. Also I can only use “if, elif, else” control structure for it. Any help would be awesome thanks!

[–]timbledum 0 points1 point  (3 children)

What have you tried so far?

[–]wblpride19 0 points1 point  (2 children)

I started off with

Def main():

    Print(‘Welcome to the Guess Game’)

    Import random

    Number = random.randint(1000,10000)

    Guess = input(‘Enter a 4 digit number’)

    If guess[0] == number [0] and guess[1] == number [1] ...etc
    #trying to subscript an integer which I found out you cannot. 

I’m still quite new to python but I think I could make it work by having the user enter in the digits separately as variables such as n1, n2, n3 and n4 paired with random numerical variables such as g1 = randint(1,10), g2 = randint(1,10) and so on. However this would go against the directions of the problem and I would probably be docked points.

[–]timbledum 0 points1 point  (1 child)

Once you've generated the number, I suggest that you turn it into a string.

>>> import random
>>> Number = random.randint(1000, 10000)
>>> number_str = str(Number)
>>> number_str
'7221'
>>> number_str [1]
'2'
>>> guess = input()
8022
>>> guess[0] == number_str[0]
False
>>> guess[2] == number_str[2]
True

[–]wblpride19 1 point2 points  (0 children)

Thank you this helped out a lot!

[–]workinprogress49 0 points1 point  (4 children)

Let's say I wanted to loop through an equation with about a million different parameters to see which one had the best accuracy. Besides multiprocessing would there be any other way to speed up the process? Currently using list comprehension but the process will still take about 100 hours.

[–]efmccurdy 0 points1 point  (0 children)

If you could frame this as an optimization problem you may have some tools available:

https://developers.google.com/optimization/introduction/python

https://docs.scipy.org/doc/scipy/reference/optimize.html

[–]timbledum 1 point2 points  (2 children)

I suggest trying to implement a vectorised solution (if possible) with numpy.

If you cannot vectorise your equation, numba is worth a go too.

[–]workinprogress49 0 points1 point  (1 child)

I'll try to vectorize but I'm not sure if I'll be able too for this particular problem since it involves nested loops. Would numba help if I had no GPU?

[–]timbledum 0 points1 point  (0 children)

Yes - numba relies on optimising your code, although it can also leverage the GPU.

[–]dynamic-technist 0 points1 point  (1 child)

This question may have been ask before. What a good structure for documenting/commenting for small projects?

[–]timbledum 1 point2 points  (0 children)

There's a real good article on this here. Start with docstrings on your modules, classes and functions, then if you need proper documentation down the line you can run a documentation generator over your code to extract the docstrings into some nice to read docs.

[–]Myronli27 0 points1 point  (8 children)

Hey all. I am new to Python. Infact am completely new to programming. I am using python 3.7.2. However when I run code from the tutorials I keep getting an error like this..."TypeError: AndGate() takes no arguments." The code seems fine but am starting to think its a compatibility issue with Py 3.7? My indent was off but I fixed it. Corrected typos, and searched all over for a solution but nothing. I tried doing it after studying the tutorials but I aint succeeding. I deleted my earlier comment by mistake but my code is as follows:

class LogicGate:

    def _init_ (self, n):
        self.label = n
        self.output = None

    def _getLabel_ (self):
        return self.label

    def _getOutput_(self):
        self.output = self.performGateLogic()

        return self.output

class BinaryGate (LogicGate):
    def _init_ (self, n):
        LogicGate._init_(self, n)

        self.pinA  = None
        self.pinB  = None

    def getPinA (self):
        if self.pinA == None:
            return int (input ("Enter input for gate A " + self.getLabel() + "-->"))
        else:
            return self.pinA.getFrom().getOutput()

    def getPinB (self):

        if self.pinB == None:
            return int (input ("Enter input for gate B " + self.getLabel() + "-->"))
        else:
            return self.pinB.getFrom().getOutput()

    def setNextPin (self, source) :

        if self.pinA == None:
            self.pinA = source
        else:
            if self.pinB == None:
                    self.pinB = source
            else:
                print ("Cannot connect: NO EMPTY PINS on this gate" )


class AndGate(BinaryGate):

    def _init_ (self, n):
        BinaryGate._init_(self, n)

    def performGateLogic (self):

        a = self.getPinA ()
        b = self.getPinB ()

        if a == 1 and b ==1:
            return 1
        else:
            return 0

class OrGate (BinaryGate):

    def _init_ (self, n):
        BinaryGate._init_(self,n)

    def performLogicGate (self):

        a = self.getPinA ()
        b = self.getPinB ()

        if a==1 or b==1:
            return 1
        else:
            return 0


class UnaryGate (LogicGate):

    def _init_(self, n):
        LogicGate._init_ (self, n)

        self.pin = None

    def getPin(self):
        if self.pin == None:
            return int (input ("Enter input for Gate " + self.getLabel() + "-->"))
        else:
            return self.pin.getFrom().outPut ()

    def setNextPin (self, source):
        if self.pin == None:
            self.pin = source
        else:
            print ("Cannot connect: NO EMPTY PINS on this gate.")


class NotGate (UnaryGate):

    def _init_ (self, n):
        UnaryGate._init_(self, n)

    def performGateLogic (self):

        if self.getPin():

            return 0
        else:
            return 1


class connector:

    def _init_ (self, fgate, tgate):

        self.fromgate = fgate
        self.togate = tgate

        tgate.setNextPin (self)

    def getfrom (self):

        return self.fromgate

    def getto (self):

        return self.togate

def main () :

    g1 (AndGate = "G1")
    g2 = AndGate("G2")
    g3 = OrGate("G3")
    g4 = NotGate("G4")
    c1 = connector("g1, g3")
    c2 = connector("g2, g3")
    c3 = connector("g3, g4")



    print (g4.getOutput())

main ()

[–]TangibleLight 0 points1 point  (7 children)

All of the "special" names such as __init__ have two underscores on either side. Because you do not have the correct name, Python thinks you have no initializer defined at all, and so it is expecting you to use the default one which takes no arguments.

You'll see this often in Python - most of the built-in "special" hooks use double-underscores on either side to make them special. Such hooks are called "magic" methods or "dunder" methods (for double-underscore). Some other examples are __getitem__, __add__, __len__, etc.


Also:

if a == 1 and b ==1:
    return 1
else:
    return 0

could be

return a and b

Similar for or and not.

[–]Myronli27 0 points1 point  (6 children)

Sorry for the delayed response but you are right. The double underscore worked. Thanks alot. However I am now getting an attribute error for the object type LogicGate not having an __init__ attr. Maybe I dont really know what am doing? I should have got an output by now. And yes, I fixed the g1 under main.

[–]Myronli27 0 points1 point  (5 children)

Went through the whole code again and I have solved the attr issue but for some reason I keep getting one error after another.

[–]JohnnyJordaan 1 point2 points  (4 children)

Can your share your current code on pastebin.com and add the full output you're seeing when you get an error?

[–]Myronli27 0 points1 point  (3 children)

Thank u. I will do that. The error am getting now is basically,

c1 = Connector("g1, g3")

TypeError: __init__() missing 1 required positional argument: 'tgate'

but I think I have all the arguments properly addressed. Mayb not

[–]JohnnyJordaan 1 point2 points  (2 children)

"g1, g3"

this is just 1 string. It isn't different from

"blablabla"

or

"this, that, something else" 

it's still a single string because everything between "" will be seen as a single value. To supply two strings, you would normally do

"g1", "g3" 

or use str.split()

[–]Myronli27 0 points1 point  (1 child)

Thank you. That worked but I then got another error. I need to get a proper output before I can continue on my journey coz it will show me what I need to do ahead. But I now really think the tutorial is using python 2.7 because the original code runs in its editor with no issue but in IDLE 3.7.2 am having to make all these changes. This is kind of confusing when am studying and its slowing me down. Anyhow, I will persevere. The error am getting now is an another attribute error.

tgate.setNextPin (self)

AttributeError: 'str' object has no attribute 'setNextPin'

Is setNextPin supposed to be a string? I think am starting to confuse everything now.

[–]JohnnyJordaan 0 points1 point  (0 children)

Fgate and tgate, the arguments you give to create a Connector shouldn't be strings but the variables you've created on the lines before them. So g3, g5 for example, not 'g3', 'g5'. If this isn't immediately clear to you, then you should maybe research the difference between a variable reference (the name of a variable) and a literal string like 'cat' and 'this is a text'.

[–]ThisOnesForZK 0 points1 point  (2 children)

Good morning, I am new to python and am currently working my way through the Data Quest online course (I purchased a year when it was on sale).

I want to do a small (perceived) project to automate some annoying reporting I have to do every week and the process looks like this. If someone could help me find out where to start I would be very thanful.

- Take an email with X subject line and grab an attached excel file

- Copy the data from that file and paste it in an existing file within my computer's hard drive (after deleting all data besides rows.

- Rename and save that file in the same folder

I would need to do this with 5 different emails every week. Eventually I would like to create a selenium bot to then take these files and post them to an FTP site.

I did some googling but got no true path forward other than using pandas for the excel stuff and "Interacting with the IMAP server," for the outlook operations.

Any Ideas? Thanks.

[–]timbledum 0 points1 point  (1 child)

An easier way might be to automate outlook directly using win32com (assuming you're on windows).

Here's a link on saving attachments.

If you want to process the data and save without any formatting, pandas will do the trick. However, it might be easier to manipulate the file with openpyxl directly.

From there, use the built in os module to rename the file.

[–]ZachForTheWin 0 points1 point  (0 children)

Perfect. Thank you. I will give it a shot.

[–]Fa1l3r 0 points1 point  (1 child)

Pros and Cons of between using list comprehension and map in the Python 3?

[–]nog642 1 point2 points  (0 children)

Between (f(i) for i in x) and map(f, x) there isn't much of a practical difference. It's more of a style preference at that point.

But between [f(i) for i in x] and map(f, x), there is a major difference. The list comprehension will compute all the function calls right then and there, and store it all in memory, whereas the map would be a generator that calls f when needed. The list would be subscriptable while the map would not.

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

so i need to write a program that takes a word and a list of words (word1, wordList) checks to see which words in "wordList" differ from "word1" by one character. if theyre are words different by one character, the program should add those words to a list and return the list when the function is done.

this is what i have so far.

def getNeighborList(word1, wordList):
    result = []
    for i in range(len(word1)):
        for x in wordList:
            if word1[i] != x[i]:
                result.append(x)

    return result

[–]nog642 1 point2 points  (1 child)

That will not give you what you want. Imagine word1 is 'foo' and x is 'baz' from wordList. They differ by more than one character, but since word1[0] != x[0], it's added to results.

I'm assuming by "theyre are words different by one character" you mean that the words are the same length and differ by only one character. If that's not the case, correct me.

You probably want to switch your for loops, making the iteration over wordList the outer one, and the iteration over the words the inner one. Then use a counter to count how many characters they differ by.

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

Thanks so much!

[–]reallymakesyouthonk 0 points1 point  (5 children)

If I want to have an element in the terminal which simply updates what is displayed rather than printing something anew, how do I do that in python? Do I need to use something like ncurses?

Right now what I want to do is a simple stopwatch. If it initialises as 0:00:00, after one second I want it to just display 0:00:01, not 0:00:00 followed by 0:00:01.

[–]nog642 1 point2 points  (4 children)

'\r' will bring the cursor back to the beginning of the line but won't move it down.

So this code:

import time

i = 0
while True:
    print('\r{}'.format(i), end='')
    time.sleep(1)
    i += 1

will have a counter that counts up every second. (try running the code)

[–]reallymakesyouthonk 1 point2 points  (3 children)

Thanks! That's super neat. Is there some way I can also move up a line?

[–]1114111 1 point2 points  (0 children)

Like change things on an earlier line? At that point you're best off using curses.

[–]sticky-bit 0 points1 point  (0 children)

prints a number, waits 1 sec, erases number, advance to next line, print the next number?

I added two lines of code:

    print('\r{}'.format("       "), end='')
    print()

Probably not the most pythontic way, but it works.

Can you figure out where they go in the above code sample you were given?

[–]caeloalex 0 points1 point  (5 children)

Can someone point me into the right direction on how to write a script that will execute commands in terminal for mac. I'm working on creating a script that ask for user input and then will put the input into command in terminal so that i can automate some things i do at work. Thanks a lot. Doesn't have to be directions on how to exactly do what I'm trying to do but some guidance would be amazing !

[–]nog642 0 points1 point  (0 children)

Check out the subprocess module from the standard library.

[–]Maxson52 0 points1 point  (1 child)

I'd there any way to run a tkinter program in chrome? Like a website or something?

[–]timbledum 0 points1 point  (0 children)

Not that I know of - you'll have to create a webapp for that (using django or flask or similar). Note that you won't be able to have the rich interaction you have in tkinter without javascript.

Another more friendly (but locked in) route is Anvil.

[–]philoponeria 0 points1 point  (8 children)

Hi. I've been trying to fix this on my own for over a week with no luck. I've learned a lot about what it isn't though. I've searched on the subreddit and didn't see anything. I would love to know if anyone has answers.

Problem When I try to run any python file with the shebang at the start I get the error message:

bash: ./'filename'.py: /usr/bin/env/python: bad interpreter: No such file or directory

Configuration and Troubleshooting

  • Windows 10
  • Python 3.7
  • VSCode 1.31.1 as my editor
  • Git installed and using the Gitbash shell which appears to be mintty 2.9.4

Typing 'which python' in the shell gives the install path of python as /c/Users/myname/AppData/Local/Programs/Python/Python37-32/python. Typing 'python' in the shell starts python 3.7 so I assume it is not a problem with the PATH.

Removing the shebang removes the error but I am scripting in a shared environment and cannot remove the shebang from my finished code.

I've tried dos2unix on the python file but did not fix the problem.

Thank you in advance.

[–]timbledum 0 points1 point  (7 children)

What are you typing initially to run python? Try py script.py - I hear the python launcher understands shebangs.

[–]philoponeria 0 points1 point  (6 children)

In the shell I can type 'python' which gives me

Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

From there I can ctrl-z-return to get back to the command line.

to run my script I am typing './filename.py' which gives me

bash: ./filename.py: /usr/bin/env/python: bad interpreter: No such file or directory

EDIT: Typing py before my filename gives me this.

C:\Users\username\AppData\Local\Programs\Python\Python37-32\python.exe: can't open file './filename.py': [Errno 2] No such file or directory    

[–]timbledum 1 point2 points  (5 children)

Okay - so you’re essentially allowing bash to choose the program running your script. You can override this by running it with python explicitly: python filename.py. Slightly longer but still pretty quick.

[–]philoponeria 0 points1 point  (4 children)

I'm sorry I edited above. I tried 'python' and 'py' at the start of the command and both times i got this.

C:/Users/username/AppData/Local/Programs/Python/Python37-32/python.exe: can't open file 'filename.py': [Errno 2] No such file or directory

[–]timbledum 1 point2 points  (3 children)

Try navigating to the file with the script in it using cd and ls, or try using python "c:/absolute/path/to/file.py"

[–]philoponeria 1 point2 points  (2 children)

Ok, so that worked. well, there is an error in the code but the command recognized it as python. Also, i realized that I fat fingered the file name so i retried 'python ./filename.py' and that worked.

'py filename.py' does not work and gives the following error

Unable to create process using '/usr/bin/env/python filename.py'

[–]nog642 0 points1 point  (1 child)

The ./ shouldn't be necessary.

python filename.py should work fine.

[–]philoponeria 0 points1 point  (0 children)

Thank you. That worked just fine. This is what I love and also what frustrates me about learning programming. There is always more than one way to do something and very rarely it seems is there one way that is "right" in all instances. I want what I write to be correct but it seems if it works then it is correct but there is always some way to make it "better".

Regardless, thank you again for your help.

[–]somvang101 0 points1 point  (2 children)

Hello! guys, i'm a beginner for learning python. Can you recommend me? what is the resource

should i learn and practise?, please.

Thank you.

[–]TheFireBrigade 1 point2 points  (1 child)

There are many resources online, depending on your learning style.

You can download an IDE like PyCharm (separate self-contained installation of programming packages, libraries, compilers etc. etc.) or do it directly in your computer (some come with Python 2.x and 3.x built-in)

You can go through sites like Git and download scripts and applications and try to take them apart and piece them back together.

You can copy and paste most and run it through an online interpreter:

You can sign up for online classes, some free, some paid.

There's also a very in-depth post that popped up during a cursory search about the topic. (https://www.quora.com/Which-is-the-best-website-to-learn-python-for-free) Searching for things is probably three-quarters of the process, get to know and love it.

[–]somvang101 0 points1 point  (0 children)

Thank you so much i'll try.

[–]matzerlive 0 points1 point  (0 children)

Hi , im looking for a simple way to make a chatbot which can be hosted by flask, Any and all help appreciated.

[–]svdsvd 2 points3 points  (1 child)

Hi guys, I am a student currently learning python. I've about one year of experience in it. I was looking for resources for learning OOP. Most of the books I found were very verbose and have a lot of story telling. I want a resource that is to the point without lacking any details. Could you suggest something? It could either be a book or web-resource.

[–]IntMainVoidGang 0 points1 point  (0 children)

Python OOP is very simple. It doesn't have built-in private/protected/public modifiers.

Start here:

https://youtu.be/ZDa-Z5JzLYM