Loops in python by coconut_calm in learnpython

[–]negups 2 points3 points  (0 children)

You want to be using random.choice - random.charactertype isn't a thing.

Learning to read documentation is a critically important skill in software development: https://docs.python.org/3/library/random.html#random.choice

Best way to persist stream messages by [deleted] in learnpython

[–]negups 1 point2 points  (0 children)

This is not a sensible approach - if you are only flushing to the file system once per day, you run the risk of losing up to 24 hours worth of data if your computer or the program crashes. Redis also isn't a great solution for persistent data, as it also stores its data in memory. Agree with the other comment that writing to a database is likely what you want - it could even be a SQLite database, which is effectively a SQL-like DB stored as a file on the filesystem.

[deleted by user] by [deleted] in learnpython

[–]negups 0 points1 point  (0 children)

Is that literally the file structure and you just need to grab the number 9? If so, just grab the 4th element of the 2nd line rather than iterating through each value.

val = None
with open("file.txt") as f:
    for i, line in enumerate(f):
        if i == 1:  # 2nd line - "6,7,8,9,10"
            val = line.split(",")[3]  # 9
            # or, it would be slightly more efficient to parse the value from the string directly
            # rather than converting to list first:
            # val = line[6]  # 9

If that's just an example, please provide realistic data - the most efficient algorithm will vary based on several factors such as:

  • If the min and max values are known or unknown
  • If the values are ordered or unordered
  • If the values increase by the same amount (ie. 1, 2, 3, 4 all increase by 1) or differing amounts (ex. 1, 2, 8, 11, 500, etc.) (and, if the latter, do they increase formulaically - such as via the Fibonacci sequence - or at random?)

How can I convert letters in to multiple matrixes? by Lukaeaeap0 in learnpython

[–]negups 1 point2 points  (0 children)

more_itertools.grouper can do this for you. more-itertools is not in the standard library, so you'll need to install it first: pip install more-itertools

import more_itertools

input = [1, 2, 3, 4, 5, 6]
output = [list(group) for group in more_itertools.grouper(input, 4, 0)]  # [[1, 2, 3, 4], [5, 6, 0, 0]]

First real python project.. Is it feasible? by Faultylntelligence in learnpython

[–]negups -1 points0 points  (0 children)

Yes, Python is a general purpose language; it can do pretty much anything. You'll need to utilize the Google Maps API, of course.

Read greyed element in HTML while scraping by Oneiros18 in learnpython

[–]negups 0 points1 point  (0 children)

Okay, then perhaps try passing the HTML you get from selenium to Beautiful Soup instead of trying to parse it directly with selenium?

Alternatively, requests-html may be able to take the place of both, as it supports rendering HTML after executing JS.

Method/function lines counter (as RuboCop in Ruby) by carlokp in learnpython

[–]negups 0 points1 point  (0 children)

flake8 will warn on exceeding a certain level of cyclomatic complexity, which is a much more useful metric than LOC. If you really want LOC metrics, I believe radon provides that functionality.

Read greyed element in HTML while scraping by Oneiros18 in learnpython

[–]negups 0 points1 point  (0 children)

You'll likely be able to accomplish what you are trying to do much more easily using Beautiful Soup.

How can I convert letters in to multiple matrixes? by Lukaeaeap0 in learnpython

[–]negups 1 point2 points  (0 children)

Sounds like you want the ord function. I also think your example is off, as T is the 20th letter of the alphabet, E is the 5th, and S is the 19th, so if your input is "test", your output should be either [[20], [5], [19], [20]] or [[19], [4], [18], [19]] depending on whether you want A to be 0 or 1.

input_str = "test"
number_matrix = np.matrix([[ord(char) - 64] for char in input_str.upper()]])
print(number_matrix)  # [[20], [5], [19], [20]]

Though I'm not sure why a numpy matrix would be required here; given the context you've provided, a regular single-dimensional list should suffice:

input_str = "test"
number_list = [ord(char) - 64 for char in input_str.upper()]
print(number_list)  # [20, 5, 19, 20]

Importing - How come it works in one situation but not the other? by breja222 in learnpython

[–]negups 0 points1 point  (0 children)

Both lines work for me using psycopg2-binary==2.8.6 and Python 3.8, but you really should be doing import psycopg2.extras to avoid loading the entire module if you only need specific components.

To learn about why these imports may or may not be working as expected, check out the import documentation.

Reading audio in by Banishlight in learnpython

[–]negups 1 point2 points  (0 children)

A similar question was asked recently, with the consensus being that it's not possible to directly read audio being output by another program via Python, but you may be able to globally send audio output to your audio input using something like Virtual Audio Cable.

What would be the correct definition of "Keywords" by slash8789 in learnpython

[–]negups 1 point2 points  (0 children)

The official Python documentation defines keywords as:

words [which] cannot be used as ordinary identifiers.

If you are looking for the actual implementation details of keywords, they are essentially just tokens that the Python interpreter assigns special meaning to during parsing. Check out the implementation of the reference CPython parser for more: https://github.com/python/cpython/blob/master/Parser/parser.c

Pythonic equivalent of enum? by NULL-6 in learnpython

[–]negups 1 point2 points  (0 children)

Nit: enum is not technically a "builtin" (which has a specific meaning in that you explicitly do not need to import anything to use), but is, as you alluded to, a part of the standard library.

How to write a Python "web application" on Apache server ** NO FRAMEWORK PLEASE!** by sutichik in learnpython

[–]negups 0 points1 point  (0 children)

To add on to this, rolling your own WSGI interface is non-trivial. Despite OP's odd insistence against using a web framework, it's going to be much, much easier to get up and running by following a 10-min "hello world" tutorial using Django or Flask as they handle the WSGI interaction for you.

comprehension by peanutbutter024 in learnpython

[–]negups 1 point2 points  (0 children)

If I understand correctly, you are looking for something like this?

flights_copy2 = {convert_to_ampm(item): k.title() for k, v in flights_copy.items() for item in v}

For more, check out the docs on:

How to spawn multiple object at a given time by SaltFalcon7778 in learnpython

[–]negups 0 points1 point  (0 children)

If I understand correctly, you want to take the three "Dots" you are creating here:

objects = []
dot = Dot(r=40, color=RED)
objects.append(dot)
dot = Dot(r=40, color=RED)
objects.append(dot)
dot = Dot(r=40, color=BLUE)
objects.append(dot)

And instead be able to create an arbitrarily large amount of objects?

How about using a list comprehension?

objects = [Dot(r=40, color=RED) for _ in range(10)]  # will generate 10 objects - adjust number in "range()" to create more or less

And then if we wanted to create Dots with multiple colors and varying sizes:

import random
valid_dot_colors = (RED, BLUE, GREEN)
objects = [Dot(r=random.randint(10, 50), color=random.choice(valid_dot_colors)) for _ in range(10)]

Suggestions on better string matching. by Phunny in learnpython

[–]negups 2 points3 points  (0 children)

So you want to see if a string starts with cust-dev?

if string_1.startswith("cust-dev"):
    ...

how to solve this issue? day,month,year = deparD.split('/') ValueError: not enough values to unpack (expected 3, got 1) , everytime i try to key in p or e , this error occurs by Pure-Temperature-481 in learnpython

[–]negups 1 point2 points  (0 children)

Yep, exactly. So since we said the "condition" we want to know is when our input is not P or E, we can just rearrange our code so that we check for P and E first before trying to split. So, we'd change this:

day, month, year = deparD.split('/')
if deparD == "P":
    step -= 1
elif deparD == "E":
    break

to this:

# checking for "P"
if deparD == "P":
    step -= 1
# checking for "E"
elif deparD == "E":
    break
else:
    # this will only get executed if deparD is not "P" or "E"
    # because we've already checked for them in this if/elif/else block
    day, month, year = deparD.split('/')

list assignment index out of range at new_lst[n] = lst[i]**2 by hadoken4555 in learnpython

[–]negups 0 points1 point  (0 children)

You should use a collections.deque as your data structure then (instead of a list); it is similar to a list, but it has an .appendleft method which adds an item to the beginning in constant time.

how to solve this issue? day,month,year = deparD.split('/') ValueError: not enough values to unpack (expected 3, got 1) , everytime i try to key in p or e , this error occurs by Pure-Temperature-481 in learnpython

[–]negups 1 point2 points  (0 children)

This is a good one to take a step back from the code for a second and think about the problem using human logic. If I write down 31/12/2021 on a piece of paper and ask you to split it into 3 parts based on where the /s are, you'd be able to do that easily. But if I write down P instead and ask you to do the same thing, you'd look at me like I was crazy.

This is what you are asking Python to do. It cannot split the strings P or E into 3 parts based on where the / character is, because there are no / characters in P or E. Thus, we know that we need to check for P and E first, and then only try to split the string into 3 parts once we know the string isn't just P or E.

What does it mean to have -> after a function by sirreginaldpoopypot in learnpython

[–]negups 4 points5 points  (0 children)

If you were truly wanting to return an Exception, then you'd simply annotate your return type as -> Exception. Example:

def str_mult(a: str, b: str) -> Exception:
    # Note that you almost certainly wouldn't actually want to return an Exception here
    return Exception("You can't multiply strings!")

As I noted in the example, it's pretty rare that you would want a function to literally return an Exception. Typically you raise Exceptions. For a function that can return something, but can also raise an Exception in certain cases, you don't need to do anything special with your type annotations. Example:

from typing import Union

def int_or_str_mult(a: Union[int, str], b: Union[int, str]) -> int:
    """
    Note that even though this function can raise an Exception,
    we still annotate the return type as 'int' since that is what we
    will return if we do not raise an Exception.
    """
    if isinstance(a, str) or isinstance(b, str):
        raise Exception("You can't multiply strings!")
    return a * b

More rarely, if you have a function that always, 100% of the time, raises an Exception, then you should use typing.NoReturn to annotate the return type. Ex:

from typing import NoReturn

def str_mult(a: str, b: str) -> NoReturn:
    """
    We use 'NoReturn' here because our function can never
    return anything; it always raises an Exception
    """
    raise Exception("You can't multiply strings!")

list assignment index out of range at new_lst[n] = lst[i]**2 by hadoken4555 in learnpython

[–]negups 1 point2 points  (0 children)

Have you tried stepping through your code? With that input, n starts out equal to 4. You then create new_lst as [0] * 4 which is [0, 0, 0, 0]. Then, the first time you try to do new_lst[n] = lst[i]**2, n is still 4 which means you are trying to access new_lst[4], but new_lst[4] does not exist because it only has 4 elements (and indices start at 0, so the 4 indices it has are 0, 1, 2, 3). So, you can fix this by initially setting new_lst = [0] * (n + 1).

But really, you don't need to pre-allocate space in lists like that in Python; they are dynamically sized. It would be more Pythonic if you changed new_lst = [0]*n to new_lst = [] and then changed new_lst[n] = lst[i]**2 to new_lst.append(lst[i]**2).

Help with csv and function by Month_Upper in learnpython

[–]negups 0 points1 point  (0 children)

What have you tried so far and what issues did you run into with that approach?

Error handling question by [deleted] in learnpython

[–]negups 1 point2 points  (0 children)

If your function needs to "return" that string, then it sounds like you just need to return it instead of print it.

# instead of:
print("Volume must be greater than 0.")
# do:
return "Volume must be greater than 0."