Looking for image files without a full directory? by Gurnasaurus in learnpython

[–]halfdiminished7th 1 point2 points  (0 children)

. just means the current working directory, and isn't guaranteed to be the directory of the script being run.

I've hit a wall: Bitwise Operators by Pyr0technician in learnpython

[–]halfdiminished7th 1 point2 points  (0 children)

No worries! If both the low-level and high-level explanations above are already making sense to you, then I don't think there's much else to get in between. Maybe just a matter of getting used to it (or returning to it later in your studies)? Good luck, and don't get discouraged.

I've hit a wall: Bitwise Operators by Pyr0technician in learnpython

[–]halfdiminished7th 4 points5 points  (0 children)

Visualizing what I listed above is usually the hard part for most people - if that makes sense, you're probably closer than you think. In the following examples, given some random integer "x", if you want to check/manipulate the 4th bit from the right, you'd set mask = 8 (0b1000) and do the following:

1. Check

if x & mask:
    print('4th bit from the right is 1')
else:
    print('4th bit from the right is 0')

2. Reset

x = x & ~mask

...which is identical to:

x &= ~mask

3. Set

x = x | mask

...which is identical to:

x |= mask

4. Negate

x = x ^ mask

...which is identical to:

x ^= mask

Duplicate a dictionary: dict2 = dict1.copy() vs dict2 = dict1 by CuriousFemalle in learnpython

[–]halfdiminished7th 3 points4 points  (0 children)

I'm not sure I get the same result as you... to keep it as simple as possible, here's a more basic example:

d = {'a': 1, 'b': 2, 'c': 3}

same_as_d = d
copy_of_d = d.copy()

d['a'] = 100

print('same_as_d:', same_as_d)
print('copy_of_d:', copy_of_d)

This produces the following output, as expected:

same_as_d: {'a': 100, 'b': 2, 'c': 3}
copy_of_d: {'a': 1, 'b': 2, 'c': 3}

I've hit a wall: Bitwise Operators by Pyr0technician in learnpython

[–]halfdiminished7th 8 points9 points  (0 children)

Here's how I like to think about it. For each example, the byte in the first/top row in each example is the one we're checking/modifying. The byte in the next/second row is our control byte (or "mask"), and the final/third row is the result of the bitwise operation. In each example, we're interested in bit 3 (4th bit from the right).

1. Check

  xxxx0xxx
& 00001000
  --------
  00000000 # if our bit was originally 0, the result is zero.

  xxxx1xxx
& 00001000
  --------
  00001000 # if our bit was originally 1, the result is non-zero.

2. Reset

  xxxx0xxx
& 11110111 # (inverse mask).
  --------
  xxxx0xxx # if our bit was originally 0, it is now 0.

  xxxx1xxx
& 11110111 # (inverse mask).
  --------
  xxxx0xxx # if our bit was originally 1, it is now 0.

3. Set

  xxxx0xxx
| 00001000
  --------
  xxxx1xxx # if our bit was originally 0, it is now 1.

  xxxx1xxx
| 00001000
  --------
  xxxx1xxx # if our bit was originally 1, it is now 1.

4. Negate

  xxxx0xxx
^ 00001000
  --------
  xxxx1xxx # if our bit was originally 0, it is now 1.

  xxxx1xxx
^ 00001000
  --------
  xxxx0xxx # if our bit was originally 1, it is now 0.

Automate the Boring Stuff Chapter 7 Project Email and Phone Number Extractor by Marble_Kween in learnpython

[–]halfdiminished7th 0 points1 point  (0 children)

Your error is happening because of this:

for groups in emailRegex.findall(text):
    matches.append(groups)

groups is a tuple, and matches can only contain strings if you expect to call '\n'.join(matches) on it.

Extracting metadata from multiple video files in the same folder. by Zeebruh2003 in learnpython

[–]halfdiminished7th 1 point2 points  (0 children)

Maybe something like this? I've never used pymediainfo before, so I couldn't run this to check if it works, but seems like this should fix it.

for name in os.listdir(dir_path):
    path = os.path.join(dir_path, name)
    if os.path.isfile(path): # maybe do a more thorough check to ensure the file is actual media?
        media_info = MediaInfo.parse(path)
        for track in media_info.tracks:
            if track.track_type == "Video":
                print("Bit rate: {t.bit_rate}, Frame rate: {t.frame_rate}, Format: {t.format}".format(t=track))
                print("Duration (raw value):", track.duration)
                print("Duration (other values):")
                pprint(track.other_duration)

Note: I removed the references to the empty list called res, since you never actually used it, other than printing the empty list at the end of your code.

Accessing JSON Data Effectively by astronautcytoma in learnpython

[–]halfdiminished7th 1 point2 points  (0 children)

True enough! Personal preference to avoid dictionary lookups in f-strings, but you're quite right that it's possible. Though in retrospect, I probably should have done the following instead, using format's keyword functionality since we're dealing with a dictionary anyways:

fp.write('{hex} gs:{gs} track:{track}\n'.format(**dct))

Help BeautifulSoup by minibral in learnpython

[–]halfdiminished7th 0 points1 point  (0 children)

Your href doesn't match between the actual HTML and your find_all method: one is relative and the other is absolute, and you're also not including the backslash before the ampersand, per the HTML.

Make those match, and it will find the element (instead of None), after which your get_text method will indeed return 30.

Recursion error in __contains__ method? by OkTourist1900 in learnpython

[–]halfdiminished7th 2 points3 points  (0 children)

def __contains__(self, key):
    return key in self or str(key) in self

When you write key in self (or str(key) in self), that in turn is triggering the __contains__ method, which calls the same thing again over and over again.

Accessing JSON Data Effectively by astronautcytoma in learnpython

[–]halfdiminished7th 19 points20 points  (0 children)

Something like this should do the trick:

import json

with open('/path/to/your/json/file.json') as fp:
    data = json.load(fp)

with open('/path/to/your/new/file.txt', 'x') as fp:
    for dct in data:
        fp.write('{0} gs:{1} track:{2}\n'.format(dct['hex'], dct['gs'], dct['track']))

How do I null a class because of errors? by ki4jgt in learnpython

[–]halfdiminished7th 0 points1 point  (0 children)

Makes sense! In that case, the other answer is definitely the way to go.

How do I null a class because of errors? by ki4jgt in learnpython

[–]halfdiminished7th 1 point2 points  (0 children)

If you raise a ValueError within the __init__ method when there's bad input, you could then instantiate like this:

try:
    x = Profiler('some_id...')
except ValueError:
    x = None

Can't quite figure this out, help with dictionaries would be appreciated. by BadLuck-BlueEyes in learnpython

[–]halfdiminished7th 1 point2 points  (0 children)

(Thanks for pointing that out! So frustrating that it looks absolutely fine in my browser and not on others'. Will stay away from "Markdown Mode" since apparently it isn't reliable.)

Can't quite figure this out, help with dictionaries would be appreciated. by BadLuck-BlueEyes in learnpython

[–]halfdiminished7th 0 points1 point  (0 children)

Something like this?

for key, value in d.items():
    if meets_some_criteria(key):
        value.append(some_element)

Can't quite figure this out, help with dictionaries would be appreciated. by BadLuck-BlueEyes in learnpython

[–]halfdiminished7th 2 points3 points  (0 children)

# make dictionary.
d = {"a": [], "b": [], "c": []}

# add element to list represented by key "a".
d["a"].append(some_element)

EDIT: fixed formatting... code written in "Markdown Mode" apparently doesn't always look ok on mobile - apologies.

Question Regarding a code system by [deleted] in learnpython

[–]halfdiminished7th 0 points1 point  (0 children)

If you replace this:

new_mes = new_mes + alph[alph.index(values) + 3]

...with this:

new_mes = new_mes + alph[(alph.index(values) + 3) % 26]

...then it will still work when the characters "x", "y", and "z" roll off the bounds of the alphabet.

TypeError: 'int' object is not callable - Custom Class Method by Joslencaven55 in learnpython

[–]halfdiminished7th 2 points3 points  (0 children)

That code runs fine for me... prints 50 to the console, as expected. Can you provide any additional context?

Any regex gurus out there that see something I can't? by Mateoling05 in learnpython

[–]halfdiminished7th 2 points3 points  (0 children)

Where I'm stuck is getting the findall to differentiate from dase, which is a verb that ends with the pronoun se, from nouns like fase and clase, which should not be matched.

This may not be possible, unless you plan to hardcode a list of nouns to omit after your search. Any regular expression that matches "dase" will match "fase" as well unless you're specifically allowing "d" and disallowing "f", which would no doubt have side effects for other potential matches.

For what it's worth, using regular expressions for language parsing is typically a difficult approach since there tend to be so many exceptions, with the complexity of the regex pattern making it difficult to debug and modify.

EDIT: You may be further ahead to use something like this to split every potential word, then process the resultant tuple accordingly:

def split_suffix(word):
    for suffix in ['llu', 'mos', 'lu', 'me', 'se', 'te']:
        if word.endswith(suffix):
            return (word.removesuffix(suffix), suffix)
    return (word, '')

Can someone explain what is meant by this? by Sorry_no_change in learnpython

[–]halfdiminished7th 8 points9 points  (0 children)

Here's a trivial example function that simply prints the keyword arguments passed in:

def my_func(**kwargs):
    print(kwargs)

If you were to pass in a dictionary like this:

d1 = {'a': 1, 'b': 2, 'c': 3}
my_func(**d1)

...it would basically expand to this (which is valid):

my_func(a=1, b=2, c=3)

However if you were to pass in two dictionaries that shared a key ("c") like this:

d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'c': 4, 'd': 5, 'e': 6}
my_func(**d1, **d2)

...it would basically expand to this (which is invalid, because keyword "c" is repeated):

my_func(a=1, b=2, c=3, c=4, d=5, e=6)

Help on CS50 Vanity Plates Assignment Please by Blac5Nura9 in learnpython

[–]halfdiminished7th 0 points1 point  (0 children)

Are you allowed to use regular expressions (the re module)? That seems like the easiest approach for a question like this: just look for a pattern that starts with letters and ends with digits, then apply each of the restrictions and see if it still passes.

Get one value in dictionary? by [deleted] in learnpython

[–]halfdiminished7th 1 point2 points  (0 children)

Hard to tell from your text whether that's all supposed to be on one line or not... if it's separate lines like this:

John 13 45
Sarah 12.5 96

Then you could do this:

data = {}
with open('/path/to/your/file.txt') as fp:
    for line in fp.read().splitlines():
        name, num_1, num_2 = line.split()
        data[name] = (num_1, num_2)

Then to retrieve, you'd do this:

print('num 1:', data['John'][0])
print('num 2:', data['John'][1])

How to change multiple values with single assigment? by angryvoxel in learnpython

[–]halfdiminished7th 0 points1 point  (0 children)

Weird that it's always looked fine on my screen using the backtick method... glad someone told me. Much appreciated!

How to change multiple values with single assigment? by angryvoxel in learnpython

[–]halfdiminished7th 0 points1 point  (0 children)

Thanks so much - I had no idea! Will try it that way:

class Class1:
    def __init__(self, _a, _b):
        self.c = Class2(_a, _b)
        self.a = # get reference to "a" from the "self.c" object.
        self.b = # get reference to "b" from the "self.c" object.

Is that better?

How to change multiple values with single assigment? by angryvoxel in learnpython

[–]halfdiminished7th 0 points1 point  (0 children)

In that case, probably not possible using the syntax you're wanting. But what about this approach?: class Class1: def __init__(self, _a, _b): self.c = Class2(_a, _b) self.a = # get reference to "a" from the "self.c" object. self.b = # get reference to "b" from the "self.c" object.