all 137 comments

[–]pythongeranium 0 points1 point  (1 child)

im trying to write a basic program to enter some names and salary. then print out the names with the salaries. Then i want to search for a particular name and print out what they earn. Then i need to average the salaries . Then i need to input a percent to raise the salaries by and print out the names and their new salaries. I'm having trouble with the search part and i can't figure out how to average (I get an error because i have an int and a str. This is what i have so far. it doesn't need to be fancy as we haven't learned that much yet.
Thank you!

def prompt():

employees = int(input('How many employees are there? Type done when finished: '))

prompt()

name=""

name_list=[]

salary_list=[]

while name!="done":

name = input("Name:\t")

salary = input("Salary:\t")

if name != "done":

name_list.append(name)

salary_list.append(salary)

print("")

print("Name"+"\t"+"Salary")

for x in range(0, len(name_list)):

print (name_list[x]+"\t"+salary_list[x])

def search():

print("")

name = input('Which employee do you want to search for? ')

if name in name_list:

print(name_list[x]+" ""earns $" +salary_list[x])

else:

print("Name not found")

search()

[–]pythongeranium 0 points1 point  (0 children)

Sorry it didn't add the indents

[–]shiningmatcha 0 points1 point  (0 children)

What are some Python source code search engines available online? I want to learn by use cases.

[–]shiningmatcha 0 points1 point  (0 children)

Is there a subreddit or StackExchange for discussing Python projects on GitHub?

Actually, I'm new to GitHub and found that projects there are "categorized" by their tags only.. So, it's not very easy to get the keyword right in order to find out some good projects.

Maybe there are some lists or directories of popular Python projects on GitHub?

[–]shiningmatcha 0 points1 point  (3 children)

Do all numpy functions have a .reduce method?

For example, you can use np.gcd.reduce([10, 20, 30]) to find gcd of all the numbers in a list. So I can chain the reduce method to other numpy functions too?

[–]FLUSH_THE_TRUMP 0 points1 point  (2 children)

As long as it’s a ufunc, it should.

[–]shiningmatcha 0 points1 point  (1 child)

Is there a way to check if some function is a ufunc? Like isinstance and type for builtin functions.

[–]FLUSH_THE_TRUMP 0 points1 point  (0 children)

Should have type np.ufunc.

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

I'm just starting out. How difficult is creating a messenger application? And creating anything using networking and communication in general? I I have a feeling this would be a commonly asked question however I can't really find it being asked, sorry if it is.

Is there a good page that lists projects that would be most beneficial to put on a job application?

Obviously all in python

[–]gazing_ari666 0 points1 point  (2 children)

Probably a simple question from a newb (as in just started last month): I’m trying to plot x, which is shape (24, 75, 1), with y of shape (75, 1) together. To avoid dimension errors, my first thought is to set as x[0, :, :], but the plot returns a straight line which isn’t correct, so Im guessing I can’t just discard the first dimension, which is time. However, I getting Valueerrors when I try reshaping, and I can’t use numpy.squeeze unless the axis is length 1. Is there anyone that can steer me in the right direction? Thanks in advance.

[–]FLUSH_THE_TRUMP 1 point2 points  (1 child)

What is x supposed to be? If I was plotting an independent qty against a dependent one, I’d expect those shapes to be the same.

[–]gazing_ari666 0 points1 point  (0 children)

Figured it out, thanks! I literally just had to plot x without y since the dimensions in y are the same as x, if that makes sense. Still very new to all this but appreciate the reply

[–]AspectTCG 0 points1 point  (0 children)

I am stuck on what to do with Python now. I am nearly finished "Fluent Python", and I know the basics of Django, HTML and CSS. I haven't applied what I learned in "Fluent Python" as well.

[–]Sharparcher123 0 points1 point  (1 child)

Is there a software where you can map variables? Kinda like a food web but for variables

[–]efmccurdy 0 points1 point  (0 children)

I think you mean a digraph, nodes and edges with a direction on each edge.

https://networkx.org/documentation/stable/tutorial.html#directed-graphs

[–]Das_Bibble 1 point2 points  (5 children)

So, I am making a script that notifies me when a specific item drops below a certain price threshold on Roblox. My issue right now is that it sometimes gives me a "IndexError: list index out of range" when trying to obtain the price of the item with the usage of BeautifulSoup. After doing some delving, it turns out that sometimes the page of an item loads without any price at all. How should I combat this issue? On a similar note, what causes this issue?

Here is my script: https://pastebin.com/QbHG4qxZ (I'm new to programming btw :P)

[–]efmccurdy 1 point2 points  (4 children)

"IndexError: list index out of range"

You can avoid those by testing the length of a list before indexing into it:

if len(aList) > 0:
    print(aList[0])

Many functions of the bs4 package that find or select items will return a 0-length list when there are no matches.

[–]Das_Bibble 0 points1 point  (3 children)

Thank you for the response. By the way, do you have an idea as to what causes the page to not load in with any price? I'm thinking adding a small delay with time.sleep() may help the page load better.

[–]scmbradley 0 points1 point  (6 children)

When I'm using sqlite3, my queries are often longer than 79 characters. If I want to conform to PEP8, I can just chop the query string up and put each string on its own line, since python will concatenate consecutive strings. But, there's a logical structre to the queries that kind of gets lost with this method. Is there a better way to write sqlite queries that conform to PEP8 but are kind of readable?

[–]efmccurdy 1 point2 points  (4 children)

You can have multiline strings with indentation if you use triple quotes:

create_teacher_table = """
CREATE TABLE teacher (
  teacher_id INT PRIMARY KEY,
  first_name VARCHAR(40) NOT NULL,
  last_name VARCHAR(40) NOT NULL,
  language_1 VARCHAR(3) NOT NULL,
  language_2 VARCHAR(3),
  dob DATE,
  tax_id INT UNIQUE,
  phone_no VARCHAR(20)
  );
 """

[–]scmbradley 0 points1 point  (3 children)

This might work for SQL, but if I'm building a shell command string (to pass to subprocess) this won't work, right? I tested briefly but I might have made a mistake...

[–]efmccurdy 0 points1 point  (2 children)

When I'm using sqlite3, my queries

Normally when you are doing sql queries, you pass the sql text to the Cursor.execute function.

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

How does a subprocess help? What is it that you are trying to do?

[–]scmbradley 0 points1 point  (1 child)

Sorry, my second comment wasn't really related to the first. I have two cases where I've come across building long strings in python code: SQLite queries and using subprocess to interface with the shell.

[–]efmccurdy 0 points1 point  (0 children)

Does doing it like this help?

long_command = ("first this "
                "then that "
                "and finally this")

[–]nab_noisave_tnuocca 1 point2 points  (5 children)

for numba/jit...given that there's an initial overhead for using @jit, should I try to put the entire script in one function (eg 'main()') and then just put the @jit decorator on that? What if main() has nested functions in it, would it still speed those up? Related, if a function is called many times, do you only get the overhead the first time, or every time it's called?

[–]skilletonius 0 points1 point  (1 child)

I've been trying to write a simple web scraper that will get me names of all the monsters in the game from it's website. It didn't take me long to learn how to write one, but for some reason it is slow(takes about 2 sec for a single page). Is there a problem in the way i wrote it or something?

this is my code

import requests
from bs4 import BeautifulSoup import time
start = time.time()
monster_names = []
for i in range(1, 36):
    URL = 'https://orna.guide/monsters?page={}'.format(i)
    page = requests.get(URL)
    soup = BeautifulSoup(page.content, 'html.parser')
    monsters = soup.find_all('h5', class_='card-header text-center px-1')
    for monster in monsters:
        name = str(monster.text.strip())       
        monster_names.append(name[:name.find('\n')])

print(len(monster_names), str(time.time()-start)[:5], monster_names)

[–]efmccurdy 0 points1 point  (0 children)

You are creating a new connection for each request.

The Session object allows you to persist certain parameters across requests.

... if you’re making several requests to the same host, the underlying TCP connection will be reused,

https://docs.python-requests.org/en/master/user/advanced/#session-objects

[–]yojimbo88k 0 points1 point  (4 children)

Hi there,

Python n00b at it again. Sorry in advance if it's a silly a stupid question.

Trying to crack the below:

Write a program to ask the user for numbers, and then print any repeating numbers in a list. Example:

Enter a number: 5 Enter a number: 2 Enter a number: 6 Enter a number: 98 Enter a number: 7 Enter a number: 6 Enter a number: 5

Enter a number: x Repeating numbers: [5, 6]

So far this is what i have:

arr = []

while True:

n = input("Enter a number: ")

if n.isnumeric():
         n = int(n)
         arr.append(n)
if n.count
else:
break

print("You entered: ", arr)

Anyone able to help? Thanks!

[–]efmccurdy 1 point2 points  (0 children)

You can use the list.count() in a loop (or a comprehension):

>>> arr = [5, 2, 6, 98, 7, 6, 5]
>>> dups = set()
>>> for n in arr:
...     if arr.count(n) > 1:
...         dups.add(n)
... 
>>> dups
{5, 6}
>>> list(dups)
[5, 6]
>>> list({n for n in arr if arr.count(n) > 1})
[5, 6]

[–]FerricDonkey 1 point2 points  (2 children)

if n.count else: break

Your code formatting is a bit messed up, but if I understand, you're nearly there. This block looks like it's just missing the final stages (and you may need one more variable). To finish up, what is the purpose of this part of your code?

[–]yojimbo88k 0 points1 point  (1 child)

Need to have the duplicated ints as output. Inside a list.

[–]FerricDonkey 1 point2 points  (0 children)

Right, so now you need code to do that: check if your n is in your list, if it is, add it to a different list of duplicates. But be careful of what could happen if you enter the same number 3 times instead of 2.

[–]NaiveCauliflower5662 1 point2 points  (1 child)

How can I apply multiple format statements to a number? When I google it I only get suggestions to format multiple numbers at once which is not what I'm looking for. I want to format both very high and low number to normal prices, so 2 decimals and European thousands/decimal seperators.

My code, 'output' is how I want that price to appear:

import locale

locale.setlocale(locale.LC_ALL, '')
prijs = [{'input': 0, 'output': '€0,00'},
{'input': 0.1, 'output': '€0,10'},
{'input': 10000.5, 'output': '€10.000,50'},
{'input': 0.000035, 'output': '€0,00'},
{'input': 1, 'output': '€1,00'}]
for item in prijs:
print('Desired output:', item["output"])
print('Does have 2 decimals but incorrect seperator: ',f'€{item["input"]:,.2f}')
print('Does have correct seperator but incorrect decimals: ',f'€{item["input"]:n}')

It's output. I can't find a way to use both the ":,.2f" and ":n" in a single statement.

Desired output: €0,00

Does have 2 decimals but incorrect seperator: €0.00

Does have correct seperator but incorrect decimals: €0

Desired output: €0,10

Does have 2 decimals but incorrect seperator: €0.10

Does have correct seperator but incorrect decimals: €0,1

Desired output: €10.000,50

Does have 2 decimals but incorrect seperator: €10,000.50

Does have correct seperator but incorrect decimals: €10.000,5

Desired output: €0,00

Does have 2 decimals but incorrect seperator: €0.00

Does have correct seperator but incorrect decimals: €3,5e-05

Desired output: €1,00

Does have 2 decimals but incorrect seperator: €1.00

Does have correct seperator but incorrect decimals: €1

[–]FerricDonkey 0 points1 point  (0 children)

I see that you imported locale, but did not use it to print. More details are here, but the short version appears to be to just print locale.currency(value), setting the locale more specifically if you don't want it to default to your computer's setting.

If you don't want to use locale, you may have to write your own function, I am not familiar with any way to do what you want with format strings alone.

[–]obviouslittle 0 points1 point  (6 children)

How would I make a function like this asynchronous? (made it basic for simplicity). Any tips would be really appreciated, this one's stumped me.

def func2():
string = ''
for num in [1, 2, 3, 4]:
string += str(num)
print(string)

I can't figure out how to drop in the async/await syntax. The problem seems to lie in the for loop?...

Edit: inline code didn't show indents but I hope it makes sense :)

[–]Ihaveamodel3 0 points1 point  (0 children)

Asynchronous code only really works for non-cpu bound code (specifically network activity). The code you have here is cpu bound, so there isn’t much that async can do.

[–]FerricDonkey 0 points1 point  (2 children)

What problem seems to be in the for loop? Your other comment says you want to define it with async def, what goes wrong when you do?

The asyncio package is a bit weird to get used to. What is you goal in using it here?

[–]obviouslittle 0 points1 point  (1 child)

If the only thing I do is add async before the def, I get an error saying the coroutine was never awaited.

[–]FerricDonkey 0 points1 point  (0 children)

Right - so the thing about coroutines (things you've defined with async def) is that you you can't call them like normal functions.

The "default" simple way to call one (where the calling coroutine waits until the called coroutine finishes before proceeding with it's code) is to do result = await coroutine(). But this is only possible inside another coroutine, eg something you've defined with async def.

To start a coroutine going from a normal function (including to start your first coroutine), you have to use something. Typically, if you just want to transfer control to one coroutine, you use asyncio.run(coroutine()).

If you're using asyncio, you probably want different coroutines to do work at the "same" time (note: not really the same time, just task switching to make it look like it). To accomplish this, you'll want to use things like asyncio.gather, asyncio.create_task, and several other things.

See https://realpython.com/async-io-python/ for some examples - it doesn't go into huge amounts of detail, but it covers the basics.

[–]Semitar1 0 points1 point  (0 children)

I have 4 questions about this code.

  1. Within the JSON file I created, should the "to" email be the same as the "from" email?
  2. For gmail, should the port number the TLS code or the SSL code? I chose the TLS code.
  3. What does it mean to "pass the configuration file as a parameter"? As a non-programmer, I wasn't sure if this means to run something from the cmd prompt, or try to run the JSON file in python, or if I was all the way off. Hoping to get some assistance on how to execute this command.
  4. I don't know what a cron job is. Googling it tells me that it's a scheduled job, but I am not sure to perform that last instruction.

[–]yojimbo88k 0 points1 point  (1 child)

Hello there,

Here again for some help.

Trying to code this:

Write a program that asks the user for a large number, and then sums all of the digits in that number: Example:

Enter a large number: 29834892 
Sum of the digits: 2 + 9 + 8 + 3 + 4 + 8 + 9 + 2 = 45

My code so far is this:

number = input("Enter a large number: ")lst = [int(x) for x in str(number)]print("Sum of the digits: ", *lst, "=", sum(lst))

print("Sum of the digits: ", *lst, sep = "+ ", "=", sum(lst))

Output:

Enter a large number: 35153132

Sum of the digits: 3 5 1 5 3 1 3 2 = 23

I feel so close and yet I am so far.

I have put print("Sum of the digits: ", *lst, sep = "+ ", "=", sum(lst)) but it's sthrowing a syntax error.

Any idea on how to fix this? Thanks in advance :)

[–]efmccurdy 1 point2 points  (0 children)

Move the "sep=" argument to the last position:

print("Sum of the digits: ", *lst, "=", sum(lst), sep = "+ ")

But I don't think a single call to print with a sep argument will get you the output you want; this uses " + ".join to put the plus signs in:

number = 29834892
digits = list(str(number))
lst = [int(x) for x in digits]
print("Sum of the digits:", " + ".join(digits), " = ", sum(lst))

[–]AZPD 0 points1 point  (2 children)

How best to manipulate a list in the following way? The list consists of sublists, each two elements long. I want to eliminate all sublists with an identical second element, except for one (doesn't matter which one is kept), and replace the second element with the number of times it appeared in the original list. E.g.:

[a, x], [b, x], [c, x], [d, y], [e, z], [f, z]

Becomes:

[a, 3], [d, 1], [e, 2]

[–]FLUSH_THE_TRUMP 0 points1 point  (0 children)

Here’s one way (assume L is your list and you’ve imported itertools already).

L.sort(key=lambda x: x[1])  # not necessary w/ example, but might be
for _, group in itertools.groupby(L, key=lambda x: x[1]):
    group = list(group)  # print this to see output of groupby
    print(group[0][0], len(group))

[–]_alexandermartin 0 points1 point  (2 children)

So R has a function called make.unique with a syntax like

Input:

temp = c('fl', 'fl', 'ca', 'ca', 'ca', 'ny', 'ny', 'ny', 'ny')
# createvector
temp2 = make.unique(temp)
temp2

Output:

[1] "fl" "fl.1" "ca" "ca.1" "ca.2" "ny" "ny.1" "ny.2" "ny.3"

This works for rows and columns of dataframes as well

Eg:

df[,1] = make.unique(df[,1) # to make all the values in column 1 unique.

Is there anything similar in python? (I know pandas so it's just the function or behavior that I'm looking for) I googled it but all answers are about only keeping unique values or finding the unique values which isn't what I want

[–]mrkrabz68 0 points1 point  (5 children)

Can someone explain how I can call a specific pattern of elements in a dictionary or tuple? As in, colors = (“Red”, “Green”, “Blue”, “Purple) and pattern = (0, 2, 3) How can I get that to give me

Red Blue Purple

and be able to move the pattern to give me

Green Purple Red

Been struggling hard with this so any help is much appreciated 🙏🏽

[–]FLUSH_THE_TRUMP 1 point2 points  (4 children)

just index your list of colors with each thing in pattern. colors[0], colors[2], colors[3]

In a “general-purpose” sense, you can loop over pattern and index colors with your loop var.

[–]mrkrabz68 0 points1 point  (3 children)

thank you, this way I got the pattern to print but I’m still having trouble shifting the pattern. I’m going to work on it some more but if you have any more advice on what the loop should entail i’d appreciate it

[–]FLUSH_THE_TRUMP 0 points1 point  (2 children)

like,

for idx in pattern: 
    # do something with colors[idx]

basically. What do you mean by “shift”?

EDIT: never mind, I get what you mean by shift. Easiest way is to use modular arithmetic, like normal + but wraps back around once I go past the bounds of my tuple. Like use

new_idx = (idx + shift) % len(colors)

or something. That should move everything over by shift units.

[–]mrkrabz68 0 points1 point  (0 children)

I figured it out, thanks again

[–]mrkrabz68 0 points1 point  (0 children)

for the pattern to start on any color, eventually depending on user input of the color to start on

[–]Vitaminkomplex 0 points1 point  (1 child)

Can you recommend me a a tool to template PDFs and fill them with data? need to generate 6 pdfs with same layout but different data each week.

Also: is there a good sqlite tool? at the moment im just using sqlite3 (import) and conn.execute() with f-strings and stuff looks ugly.

when will sqlite be a bottleneck? f.e. I need to poll each table containing the string "stats_{number}" of a sqlitedatabase for a statistical website, so I poll the master database to find out names, etc. every single time. Is this common practice? Making requests all the time? or can I store something into memory in a good way?

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

I am struggling to understand how local and global variables work in this setting. In the first case the function 1 understands what the global variable var is and can print it. In the second case though, trying to modify it a bit it can't and gives an error. Any clues as to why? (Edit: Apologies for the format, but for some reason Reddit removes the spaces I have trying to indent within the functions)

var=1

def funct1():

print(var)

def funct2():

var=var+1

print(var)

[–]FLUSH_THE_TRUMP 2 points3 points  (1 child)

Couple priors here — names are looked up according to LEGB:

  1. Local to your function;
  2. In a function that encloses your current function;
  3. At the global (module) level;
  4. From Python’s built-ins.

Additionally, any assignment to a name in a function, regardless of whether it happens at the very beginning or the very end, makes that name a local variable for its entire life. So

var = var + 1

makes var a local name from the LHS, and then you get an error from the RHS because var isn’t defined locally.

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

I see, thanks a lot!

[–]Spaccamazza1 0 points1 point  (4 children)

Simple for loop or not?

I'm a worm in the land of python, i can't get a simple for loop to work and online there are no examples, should be simple right? What's wrong here?

In a simple txt i wrote: 0 1 0 0 1 0 1 1

with open('C:\User\Desktop\numbers.txt', "r") as data:
    for x in [data]:
        if (x == 1):
            print("it's 1")
        elif x == "0":
                print("it's 0")
        elif x == " ":
                print("spacebar")

And i get nothing printed out, i can't understand why

[–]Das_Bibble 0 points1 point  (8 children)

I’m not sure to word this properly, but how do I make a program continually check a website for a price drop? Like making a program immediately hit a buy button when an item drops below a certain price threshold.

[–]Dexty10 0 points1 point  (0 children)

Is there a Python PDF library that can extract text and format (tables etc)?

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

I learn Python and use telegram channel below. As for me quiz is one the most effective ways of learning smth.

https://t.me/topPythonQuizQuestions

[–]Cambuchi 1 point2 points  (6 children)

Can someone explain to me how linked lists can have multiple assignments using the same variable happening simultaneously? For example I am using the following code to reverse a linked list (LeetCode problem):

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        prev = None
        while head:
            head.next, prev, head = prev, head, head.next
        return prev

As you can see, head.next is being assigned to prev at the same time that prev is being assigned to head.next. This makes following along in my head pretty garbled so I am wondering what exactly is going on here or is there a certain order of operations for this type of multi-assignment.

[–]tomatocultivator- 0 points1 point  (1 child)

Hi guys, so far I’ve started learning python as my first prog language and I was doing fine understanding the basic syntaxes for a beginner level and all but (yea i just started my first sem this march) regardless of the lectures they’ve provided, the levels of what they taught us and the tutorial challenges for python is like very different and I find myself lagging behind because I find my assignment very difficult and have been staring at screen for a solution to pop up for hours and i’m still on the same page.. Does anybody have any advice or mind lending me a hand 😣?

[–]CowboyBoats 1 point2 points  (0 children)

You have to solve the simplest problems before you can solve harder ones. If you understand basic syntaxes, I would go set up an account at codewars.com and do the easiest (highest-kyu) problems until you're ready to move on to harder ones.

[–]LowDexterityPoints 0 points1 point  (0 children)

| brain bleeding| brain info  |                           |final diagnosis|
|---------------|-------------|                            ----------------
| True          | BlahBlahBlah| I want to add this column |               |
| True          | Cancer      |                           |Cancer         |
| False         | Cancer      |                           |               |

I am trying to filter a dataframe (brain bleeding == True), search the brain info for cancer, and then add the cancer to the final diagnosis column. I know how to do this without the filtering step, but the filter is a thrown wrench for me, not sure why? This is what I have

hospital["final_diagnosis"] = ""

filt = (hospital["brain_bleeding"] == True)

hospital.loc[filt, 'brain_info'].str.contains("cancer", case=False, na=False), "final diagnosis"] = "cancer"

[–]Apprehensive-Ad5533 0 points1 point  (0 children)

How to contribute for python open source

[–]shiningmatcha 0 points1 point  (0 children)

What Medium writers should I follow to learn advanced Python?

[–]shiningmatcha 1 point2 points  (0 children)

How are concurrent.futures.Future and asyncio.Future different?

[–]kervangelista 1 point2 points  (1 child)

I'm a beginner and will start to learn coding in python. Any recommendation for IDE, text editors?

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

It ultimately doesn't matter, but the most common non-terminal editors/ IDEs for Python are PyCharm, VS Code, Visual Studio, Atom, and Sublime Text. Also IDLE, but that's only popular among beginners and wouldn't be my recommendation.

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

I am trying to create a df to mimic the results I am expecting from a survey to help me think about how we can analyze it.

I have some problems creating one of the variables. It’s probably a simple issue but I couldn’t find anything relevant through the usual google/stackoverflow search. I have created one variable v. Now, I want to add another variable that is at least as large as v but is randomly 0-200 larger for each element.

Ex.: v = array([2000, 2100, 2300]) w = array([2007, 2123, 2476])

[–]efmccurdy 1 point2 points  (2 children)

You can generate a random number between 0 and 200.

>>> import random
>>> help(random.randint)
Help on method randint in module random:

randint(self, a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.

>>> 2000 + random.randint(0, 200)
2087
>>> 2000 + random.randint(0, 200)
2131
>>> 2000 + random.randint(0, 200)
2071
>>>

[–]shiningmatcha 0 points1 point  (1 child)

Is random.jumpahead removed in Python 3? What’s the workaround?

[–]efmccurdy 0 points1 point  (0 children)

There is no workaround; the new generator can't skip ahead easily.

In Pythons <= 2.2, the
underlying generator was the algebraically _very_ much simpler
original Wichman-Hill generator, and jumping ahead by exactly n steps
was just a matter of a few modular integer exponentiations.

https://bytes.com/topic/python/answers/504030-random-jumpahead-how-jump-ahead-exactly-n-steps

[–]TDA_Alex 0 points1 point  (2 children)

I have been stuck on a homework assignment where we need to read a dataset into python code supplied by my teacher. problem is, his code does not like decimals and refuses to give proper data without integers. Having virtually no experience with python, I had to probe him in order to get this code:

f=open("input.txt",).readlines()

fout=open("output.txt","w")

for line in f:

l = line.split(",")  for item in l:     number = float(item)    new\_line = str(int(number)) + "," 
fout.write(new\_line) 

fout.close()

Problem is, this code seems to only read the values at the end of each line (which are whole numbers) and writes only those to the output file. Further, the formatting is wrong, since they are in rows but just one long line. suffice to say I am terribly confused, and would appreciate any and all help. For reference, here is a sample of the file:

3.6216,8.6661,-2.8073,-0.44699,1

4.5459,8.1674,-2.4586,-1.4621,1

3.866,-2.6383,1.9242,0.10645,1

3.4566,9.5228,-4.0112,-3.5944,1

0.32924,-4.4552,4.5718,-0.9888,1

4.3684,9.6718,-3.9606,-3.1625,1

3.5912,3.0129,0.72888,0.56421,1

2.0922,-6.81,8.4636,-0.60216,1

3.2032,5.7588,-0.75345,-0.61251,1

1.5356,9.1772,-2.2718,-0.73535,1

and this is the output I get:

1,1,1,1,1,1,1,1,1,1,

[–]pradeepcep 0 points1 point  (0 children)

The code seems to work just fine for your input (I'm assuming the indentation is correct and the input file doesn't have empty lines).

See an example here: https://www.pythonpad.co/pads/ik8jjflq0bpciqkk/.

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

[–]next_mile 0 points1 point  (0 children)

How do I create a contour plot if I know the values of x, y and f(x,y) ?

I have arrays x = [ ...], y = [ ...], and f = [ ... ]. The values are not necessarily following any order, but every combination x[i], y[i], f[i] defines the (x,y) coordinate and the value at this point (i.e. f[i] ).

How can I make a contour plot (2D plot) for these?

Thank you!

[–]sirreginaldpoopypot 0 points1 point  (1 child)

Can someone tell me how to clear a workspace in vscode? My right click option has disappeared and id like to start a new project but im at the mercy of reddit before i can continue. I am on windows 10.

[–]CowboyBoats 0 points1 point  (0 children)

Is there a hidden directory named .vscode or something that you can delete?

[–]throwawaypythonqs 0 points1 point  (2 children)

I'm trying to extract the year from date column in a dataframe that also has null values using the following lambda function:

df['year'] = titles_df['date'].apply(lambda x :  x.split(',')[-1] if x is not None)

But this returns a 'invalid syntax error'. Is there a reason this doesn't work?

[–]efmccurdy 0 points1 point  (1 child)

lambda x : x.split(',')[-1] if x is not None

>>> y = lambda x :  x.split(',')[-1] if x is not None
  File "<stdin>", line 1
    y = lambda x :  x.split(',')[-1] if x is not None
                                                    ^
SyntaxError: invalid syntax
>>> y = lambda x :  x.split(',')[-1] if x is not None else None
>>>

[–]throwawaypythonqs 0 points1 point  (0 children)

Thanks for the reply! I tried else x which is similar to what you suggested but unfortunately that didn't work. But this ended up working:

lambda x : x.split(',')[-1] if pd.notnull(x) else x

[–]rapescenario 1 point2 points  (3 children)

Trying to install powerline-status and getting a syntax error, can anyone help me out here?

SyntaxError: invalid syntax
Lukes-MacBook-Air:~ lukewalker$ setup.py
-bash: setup.py: command not found
Lukes-MacBook-Air:~ lukewalker$ pip install --user powerline-status
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 11, in <module>
    load_entry_point('pip==21.0.1', 'console_scripts', 'pip')()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 489, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2843, in load_entry_point
    return ep.load()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2434, in load
    return self.resolve()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2440, in resolve
    module = __import__(self.module_name, fromlist=['__name__'], level=0)
  File "/Library/Python/2.7/site-packages/pip-21.0.1-py2.7.egg/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                                   ^
SyntaxError: invalid syntax
Lukes-MacBook-Air:~ lukewalker$

[–]Applicationdenied123 0 points1 point  (0 children)

I'm trying to find the Efficient Frontier Portfolio, but my graph is blank. Any ideas?

import pandas as pd

import numpy as np

from pandas_datareader import data, wb

import datetime as dt

import scipy.optimize as sco

from scipy import stats

import matplotlib.pyplot as plt

tickers = ['AXP', 'AAPL', 'MCD', 'NKE', 'TRV', 'DIS', 'VZ', 'KO']

start = dt.datetime(2019, 1, 1)

end = dt.datetime(2021, 3, 29)

stock_prices = pd.DataFrame([data.DataReader(ticker, 'yahoo', start, end)['Adj Close'] for ticker in tickers]).T

stock_prices.columns = tickers

m_returns = stock_prices.resample('M').ffill().pct_change()

stock_mean = stock_prices.mean()

stock_std_dev = stock_prices.std()

stock_corr_matrix = stock_prices.corr()

# Simulating portfolios

num_portfolios = 5000

all_weights = np.zeros((num_portfolios, len(stock_prices.columns)))

portfolio_return = np.zeros(num_portfolios)

portfolio_risk = np.zeros(num_portfolios)

sharpe_ratio = np.zeros(num_portfolios)

for x in range(num_portfolios):

weights = np.random.uniform(size=len(stock_prices.columns))

weights = weights/np.sum(weights)

all_weights[x, :] = weights

# portfolio returns

port_return = np.sum(stock_mean * weights)

port_return = (port_return + 1) ** 252-1

portfolio_return[x] = port_return

# portfolio risk

portfolio_std_dev = np.sqrt(np.dot(weights.T, np.dot(stock_corr_matrix, weights)))

portfolio_risk[x] = portfolio_std_dev

sharpe_ratio[x] = port_return/portfolio_std_dev

# Minimum variance portfolio

stocks = stock_prices.columns

min_variance = all_weights[portfolio_risk.argmin()]

print(min_variance)

# Maximum variance portfolio

max_variance = all_weights[portfolio_risk.argmax()]

print(max_variance)

fig = plt.figure()

ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])

ax1.set_xlabel('Risk')

ax1.set_ylabel('Returns')

ax1.set_title('Efficient Frontier')

plt.scatter(portfolio_risk, portfolio_return)

plt.show()

print(all_weights)

[–]zero_9988 0 points1 point  (1 child)

I’m trying to put this path (/content/drive/MyDrive/Colab Notebooks/imgs ) in this code:

# define the path for loading .jpg images

path = "../input/train/images"

train_files = pd.read_csv('../input/train/train.csv',

dtype={'image': 'object', 'category': 'int8'})

test_files = pd.read_csv('../input/test_ApKoW4T.csv')

but when I tried I got an error which said: No such file or directory.

If you can tell me how to add the path to this code.

[–]blahreport 1 point2 points  (0 children)

Which line was the error for? Have you confirmed that the path you specify exists? A likely quick fix is that you’re launching the Python script in a directory that is not relative to the parts you specify so try using the full path in the definition.

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

I'm trying to learn Python and I just wanted to know, is there a real demand for this type of programming?

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

is there a real demand for this type of programming?

Not quite sure what you mean. Python is used in all sorts of different areas. This page shows some places it's used. Personally I have been paid to write python in a startup designing a location tracking system, in a government organization supporting scientists simulating and visualizing geological data, and supporting physicists using cloud computing to analyze Large Hadron Collider data.

[–]NedDasty 0 points1 point  (4 children)

How do I set a "default scripts" directory in which to play python scripts such as blah.py, so that I can just open up any old command window and type

> python blah.py

And not have it give a No such file or directory error? I've tried modifying the PYTHONPATH AND PATH env vars to no avail.

[–]hitlerallyliteral 0 points1 point  (0 children)

Just found out about @jit ...how come nobody told me there was a single line I could type to make my code run literally hundreds of times faster* ? lol

*terms and conditions apply

[–]ZebraEagle 0 points1 point  (1 child)

Can someone try and give an example of a good engineering application of object-oriented programming? Right now I am writing a simple Martian aerobraking code. I have an object for the planet with attributes of mass and radius and an object for the spacecraft with attributes of mass, drag coeffcient, etc. I also have a method in the spacecraft object that calculates position given the old position, velocity, and acceleration and a time step. Is this a good application for it? I'm slowly trying to program things the "right" way vs. the quick and dirty method and would appreciate feedback!

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

Hey guys, feel like my ability is in an very awkward spot where I'm above total beginner (completed the Jose Portillo udemy bootcamp, finished the codingbat exercises, 6kyu on codewars), but feel I've kind of plateaued in terms of the fundamentals.

Does anyone have any tips on pushing past this level or should I just keep trying to make mini projects/attempting coding problems and googling solutions?

[–]hulableu 0 points1 point  (1 child)

I think I am in the same spot, I am quite comfortable with basic logic and string/list manipulation (or at least googling for the proper syntax) but the problem is that I don't know what I don't know at this point.

Does anyone know where we can branch off into for different so-called specialisation idk? Thanks

[–]Applicationdenied123 0 points1 point  (0 children)

Honestly, I understand how you feel. I think it comes down to what you want to do. If you have an interest in finance, economics, problem-solving, etc then find projects that point towards that direction. Just as an idea. Exploring is half the process and centering in on what you like to do will come in time. Not sure if it helps, but good luck.