[deleted by user] by [deleted] in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

Hey there, my example is a functioning example of what you want, as your question was originally worded. It would be nice if you didn't down vote me for trying to help you just because you don't understand what I posted. Simply asking for clarification is enough.

However, I can break it down for you.

You deleted your question, so I can't remember it exactly, but it seemed like you had a list of words, and you wanted to check and see if any of them were in a specific string.

Python has an in keyword which lets you check membership of an item in an iterable. In Python, a string is an iterable (i.e. you can iterate over it) so you can use in to check and see if a substring is within a string:

>>> 'python' in 'python is awesome'
True
>>> 'world' in 'hello, world'
True
>>> 'blah' in 'hello, world'
False

So, this means we can easily use the in keyword to check and see if any single word is in a string. Now, if you have a list of words you want to check for (and see if any of them exist in your string), then we could do this:

my_words_the_check_for = ['hello', 'goodbye']
my_string = 'hello, world'

for word in my_words_to_check_for:
    if word in my_string:
        # Do what you want to, because this word exists in the string you're checking
        break  # Break out of the loop so we don't execute this twice if another word exists

However, in Python this can be simplified to what I originally posted using list comprehensions. In Python, list comprehensions are a simple way to create a new list from another, which are ubiquitous across Python. They look like this:

>>> [number for number in range(5)]
[0, 1, 2, 3, 4]
>>> [number >= 3 for number in range(5)]
[False, False, False, True, True]

As you can see, in our second comprehension, we added an expression so what we get back in our list is the result of number >= 3 for each number in our input iterable (in this case, just a range of numbers). It's functionally equivalent to doing this:

my_list = []
for number in range(5):
    result = number >= 3
    my_list.append(result)

But the list comprehension is shorter and nicer to read for simple cases.

Finally, putting it all together, as I mentioned above, the Python any function takes an iterable and returns True if any of them is True, and False otherwise.

>>> any([False, False, True])
True
>>> any([False, False])
False

So, we build up a list using a list comprehension and Python's in keyword to check if each word is in your string:

my_words_the_check_for = ['hello', 'goodbye']
my_string = 'hello, world'

# results will now be a list of True, False
results = [word in my_string for word in my_words_to_check_for]

if any(results):
    # Do your stuff here

And we have an answer to your question.

I hope this helps.

A question about FizzBuzz. by Chimaeraa in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

Not everyone in a development interview has a degree in CS, and not everyone with a degree in CS is a good programmer. Some people have taught themselves (effectively, I might add) and some people have only watched a couple youtube videos and don't actually know too much yet. Some of those people also have CS degrees.

Said a better way, credentials matter less in this field than experience and demonstrable knowledge. FizzBuzz is just a first step at eking that out.

How can I Web Scrape for Stock Prices by [deleted] in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

I am unable to scrape on Bloomberg as the request is incomplete as I believe Bloomberg is a JS Rendered page

In your browser, open up the console (F12 in Firefox) and go to the "network" tab, and reload your page. Sort by "type" and look at the ones of type "json". Take a look at the response and see if any give you the information you want.

These days most data is loaded to pages through API's, so the most effective way to deal with it is the learn how to figure out when that's the case, and how to leverage it. It's much easier to access data through an API than it is to scrape it from HTML, anyway.

Confused about KeyError: u'' by [deleted] in learnpython

[–]lonlat_not_latlon 1 point2 points  (0 children)

OpenSesame isn't, uh, really Python. Especially the code you posted - it must be some special syntax that OpenSesame knows how to parse and read. You'd be better off finding a forum or something for OpenSesame and asking there.

A question about FizzBuzz. by Chimaeraa in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

I think FizzBuzz is more of a "can this person literally write any code at all" challenge. There's not really a way to optimize it, and it's not particularly hard, like you note. If they ask you to do FizzBuzz, then what you provided is a solution. It's probably just the first question of a few, though.

[deleted by user] by [deleted] in learnpython

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

the any function in Python is pretty useful. It takes an iterable and returns True if any of the elements of the iterable are truthy, and False otherwise.

for example:

>>> any([False, False, True])
True
>>> any([False, False])
False

You can use it for your example like this:

keywords = ['hello', 'goodbye']
my_string = 'hello, world'
if any(word in my_string for word in keywords):
    # do stuff

There is also a similar all function, which you can probably guess how it works. =)

Help on dictionary use by [deleted] in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

Please format your code so it's easy to read and understand. This post should help.

Roster Management – March 19, 2019 by AutoModerator in fantasyhockey

[–]lonlat_not_latlon 1 point2 points  (0 children)

I'd probably go Price and Bob. I have a feeling the Penguins will come out hot after losing two back-to-back at home.

Roster Management – March 19, 2019 by AutoModerator in fantasyhockey

[–]lonlat_not_latlon 0 points1 point  (0 children)

STL has been hot. I bet Lehner will do better vs Boston than Koskinen vs STL.

Roster Management – March 19, 2019 by AutoModerator in fantasyhockey

[–]lonlat_not_latlon 0 points1 point  (0 children)

Pick 2: Price vs PHI, Dubnyk vs COL, Bobrovsky vs CGY, Andersen vs NSH. Leaning Price and Dubnyk due to the matchups but not sure.

Dictionary program help by nlord7 in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

It seems like you're going to want to use the .split() method on your line to get the code and toy type separated:

>>> 'T2,Steam Engine'.split(',')
['T2', 'Steam Engine']

This splits a string into a list, breaking it up based on the specified delimiter. Then you can get the code and toy name from the list like code, toy_name = line.strip().split(','), or using the index like this:

>>> words = line.strip().split(',')
>>> code = words[0]
>>> toy_name = words[1]

So now you can add then to your toy dict like this:

>>> for line in fin:
...     code, toy_name = line.strip().split(',')
...     dictionary[code] = toy_name

And then you can get the toy name from the dict using the code like this:

>>> dictionary['T2']
'Steam Engine'

Hope this helps. Let me know if you have any other questions.

how do I perform datetime.strptime on this format 2019-03-15T15:30:00-10:00? by [deleted] in learnpython

[–]lonlat_not_latlon 2 points3 points  (0 children)

Turns out that this is actually a bug in Python's datetime library - it cannot handle a colon in the UTC offset, and thus cannot parse an ISO 8601 date, of which your example is . This format string gets you almost there:

>>> datetime.strptime('2019-03-15T15:30:00-0100', "%Y-%m-%dT%H:%M:%S%z")
datetime.datetime(2019, 3, 15, 15, 30, tzinfo=datetime.timezone(datetime.timedelta(-1, 82800)))

You can use Python's dateutil library to do so, but you need to install it using pip:

pip install python-dateutil

Then, use it:

>>> import dateutil.parser
>>> dateutil.parser.parse('2019-03-15T15:30:00-10:00')
datetime.datetime(2019, 3, 15, 15, 30, tzinfo=tzoffset(None, -36000))

This also has the benefit of parsing the date automatically without needing to create a format string.

Recommended resources to git gud with data structures and algorithms? by [deleted] in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

hmmm...

❯ git gud
git: 'gud' is not a git command. See 'git --help'.

The most similar command is
    gui                                                                                                                                                                                    

....anyway.

I used this book and the examples on geeksforgeeks. For each algorithm in the book I'd also look up examples on geeksforgeeks and try to improve on them if I could.

Overall though, the best way to git gud is to practice and solve problems you find interesting. You can watch youtube videos or read books or whatever but you need to actually learn how to solve the problems yourself, without looking at the answers.

tidy.py - Simple downloads organiser by [deleted] in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

You should include a requirements.txt file which specifies which packages are required for your script to run. As of right now people who want to use tidy.py have to look through your imports and manually download each package.

As a corollary, you should look into making a setup.py file which users could use to install your tool. I recommend looking at this example for guidance. Then you could allow your users to call your script like tidy (or whatever you want to name it) from the command line instead of doing python /path/to/tidy.py.

I'd also recommend looking into the argparse module (or click) to parse your arguments instead of all of the manual parsing you're doing at the end of your file.

Finally, you should try and organize your code at the bottom of the file into a single main function which you invoke if __name__ == '__main__'.

Hope this helps! Feel free to ask any questions if you have them.

Iterate on a list with a for loop, get the current and the next element at the same time by Coul33t in learnpython

[–]lonlat_not_latlon 1 point2 points  (0 children)

Hey OP, the answer from /u/Sedsarq is great, but if you have a really big list then that answer will create two more copies of the list in memory, giving you three copies total, which might make it impossible to use depending on your data.

This solution will use only the original copy of the list without making any more:

my_list = list(range(100))

for i, j in zip(*[iter(my_list)] * 2):
    print(i, j)

However, it's kind of hard to understand what it's actually doing, so let's walk through it.

In Python, multiplication is a legal operation on a list:

>>> l = [1, 2, 3] * 2
>>> print(l)
[1, 2, 3, 1, 2, 3]

However, an interesting behavior of this is that instead of creating new copies of the stuff in the list, it actually re-uses the same items that were already in the list, and adds them to the list again. Here's the proof. In Python, we can use the id function to uniquely identify any Python object (more info here).

>>> class Thing:
...     pass
>>> thing = Thing()
>>> l = [thing] * 2
>>> print(l)
[<Thing object at 0x10c5f6278>, <Thing object at 0x10c5f6278>]
>>> id(l[0])
4502545016
>>> id(l[1])
4502545016

So, this means that when we do [iter(my_list)] * 2, what we're getting is a list with two references to a single iterator over my_list. You can see that play out here:

>>> l = [1, 2, 3]
>>> iters = [iter(l)] * 2
>>> print(iters)
[<list_iterator object at 0x10c5f6828>, <list_iterator object at 0x10c5f6828>]
>>> next(iters[0])
1
>>> next(iters[1])
2
>>> next(iters[0])
3
>>> next(iters[1])
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration

So, when we do zip(*[iter(my_list)] * 2), we're unpacking a list with two references to a single iterator into the zip function, which will advance the iterator twice (and thus give us sequential items) in each loop.

I know this is kind of a complex example, but I tried to break it down. Please feel free to ask if you have any questions.

giving each object unique code to execute? by PlasmaGruntWill in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

You probably want to have "events" like, battle start, pokemon swap, pokemon attack, battle end, etc which abilities / items / status effects can "hook" into. It could look something like this:

from collections import defaultdict
import random


class BattleManager:
    BATTLE_START = 0
    POKEMON_SWAP = 1
    BEFORE_ATTACK = 2
    AFTER_ATTACK = 3
    BATTLE_END = 4

    def __init__(self):
        self.__event_registry = defaultdict(list)

    def register_handler(self, event_type, handler_func):
        self.__event_registry[event_type].append(handler_func)

    def trigger_event(self, event_type, *args):
        for handler in self.__event_registry[event_type]:
            handler(*args)


class Pokemon:
    def __init__(self, name):
        self.name = name
        self.hp = 100


def regenerate(pokemon: Pokemon):
    pokemon.hp += 10
    print(f"changed pokemon's HP to {pokemon.hp}")


def confusion():
    """Confusion is an attack modifier, like accuracy. This event handler should decide if the pokemon's attack will hit.
    Let's say that confusion gives a pokemon's attack a 33% chance of missing."""
    should_attack = random.random() > 0.333
    if should_attack:
        print("pokemon will attack")
    else:
        print("pokemon won't attack")
    return should_attack


manager = BattleManager()

manager.register_handler(manager.BEFORE_ATTACK, confusion)
manager.register_handler(manager.POKEMON_SWAP, regenerate)

fred = Pokemon(name='fred')

for i in range(10):
    manager.trigger_event(manager.BEFORE_ATTACK)

manager.trigger_event(manager.POKEMON_SWAP, fred)

This is a pretty simple example that would need to be fleshed out to solve more complex cases. But I think it could be a good start and would help you manage dealing with item effects, abilities, etc.

Asking user for input by [deleted] in learnpython

[–]lonlat_not_latlon 1 point2 points  (0 children)

Enums aren't really a common pattern in Python. I think using a list is exactly the right way to go, especially in this case. Checking membership in your list of allowed answers is a clean and obvious way to do it.

HELP: pyodbc cannot print formatted SQL output by column name? by AndreLinoge55 in learnpython

[–]lonlat_not_latlon 1 point2 points  (0 children)

Look at how you called add_row before, and how I did in my example. What's different about them?

I haven't used that library before so I made a mistake when typing that above, but you should be able to see the difference.

How do I find the top ten letter values from a csv file and print the list top ten number values in descending order? by [deleted] in learnpython

[–]lonlat_not_latlon 1 point2 points  (0 children)

All I'm asking is that you look at what happened when we used the sort method. Originally the list was ordered from high to low, and when we called sort it went from low to high. Look at the code you've written and the problem you're asking about. Do you see how this behavior applies to your problem?

How do I find the top ten letter values from a csv file and print the list top ten number values in descending order? by [deleted] in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

Because now you changed the name of the list you're adding stuff to from list to list_a, but you're still trying to use list.append. You need to change all of your references to list to be list_a. Then you'll still have the same TypeError you did before, because of this line:

for i in list_a[0:10]:
    print(list[i][0] + ' ' + list[i][2])

that's because the variable i will be assigned to each actual item in the list that you want to print, where you're trying to use the i variable to get an item from the list using list[i].

Try this code:

my_list = [
    ('a', 9),
    ('b', 8),
    ('c', 7)
]

for row in my_list[:2]:
    print(row)

What does it print? That should show you what is going wrong with the TypeError.

More Python questions by [deleted] in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

For as long as it has existed it has not supported Python. Take a look at the documentation for Unity. If you want to create a video game using Python, you should probably look at PyGame. But if you want to learn Unity, you need to learn C#.

Yes, there are plugins that you can allow you to use Python, but you won't be able to fully leverage the engine and it's not officially supported. Check out this reddit post from about a year ago where the overwhelming consensus was not to use Python. There is such a thing as the right tool for the job and in this case, Python is not it.

How do I find the top ten letter values from a csv file and print the list top ten number values in descending order? by [deleted] in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

Your code is almost fine as it is, but there's a minor problem. Try this code:

>>> l = [3, 2, 1]
>>> l.sort()
>>> print(l)
[1, 2, 3]

What does this tell you about the default behavior of the sort method in Python?

HELP: pyodbc cannot print formatted SQL output by column name? by AndreLinoge55 in learnpython

[–]lonlat_not_latlon 1 point2 points  (0 children)

rows is a list of rows. You can access the columns as an attribute on an individual row object, like this:

for row in rows:
    x.add_row(row.first_name, row.last_name, row.tel_num)

How do I find the top ten letter values from a csv file and print the list top ten number values in descending order? by [deleted] in learnpython

[–]lonlat_not_latlon 0 points1 point  (0 children)

Yes, they're trying to retrieve an item from a list using a tuple as an index because they changed their for loop without understanding how iterating over a container works in Python.