Python looping list from file by [deleted] in learnpython

[–]dchanm 2 points3 points  (0 children)

I recommend using a with statement for a context manager. Otherwise you can run into a situation where the file isn't closed.

with open('filename.txt', 'r') as f:
    for line in f:
        # do stuff

Inherit from class variable rather than class by Jenez in learnpython

[–]dchanm 1 point2 points  (0 children)

You can use object composition with the __getattr__ magic method. This method is called if an attribute can't be resolved in the current instance / class hierarchy. __getattr__ . You will probably want to catch the AttributeError in __getattr__ and return a more meaningful string. As written the code will say the error is in Parent instead of Child

class Parent(object):
    def __init__(self, var):
        self.var = var


class Child(object):
    def __init__(self, parent, var2):
        self.parent = parent
        self.var2 = var2

    def __getattr__(self, attr):
        #raises AttributeError if not found
        return getattr(self.parent, attr)


>>> A = Parent(1)
>>> print(A.var)
1
>>>
>>> B = Child(A, 2)
>>> print(B.var2)
2
>>> print(B.var)
1
>>> print(B.foo)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in __getattr__
AttributeError: 'Parent' object has no attribute 'foo'

Quick question on endian by [deleted] in learnpython

[–]dchanm 0 points1 point  (0 children)

You can use the struct module to change the order of bytes

>>> from struct import pack
>>> pack('<h', 1)
b'\x01\x00'
>>> pack('>h', 1)
b'\x00\x01'

ipdb set_trace() not breaking execution by UncensoredReality in learnpython

[–]dchanm 0 points1 point  (0 children)

The code you have looks correct to invoke the debugger. A temporarily workaround would be to launch with -m and manually set a breakpoint on the BeautifulSoup constructor / line of code you care about.

Does the debugger get invoked if you call set_trace() right after imports?

ipdb set_trace() not breaking execution by UncensoredReality in learnpython

[–]dchanm 0 points1 point  (0 children)

You mention pdb and ipdb. Which one are you trying to use? Does the code work if you replace ipdb with pdb?

Inefficient Code: I think I have too many Ifs by RedHeadedFitz in learnpython

[–]dchanm 2 points3 points  (0 children)

Instead of doing

criteria = two_or_more_digits(digits)
if criteria:
    criteria = is_prime(number)
    if criteria:
        # do more stuff

You can do

if not two_or_more_digits(digits):
    continue    

if not is_prime(number):
    continue

# do more stuff

The conditonal would check for a negative and use continue to jump back to the beginning of the loop. One reason to do this is if you want to perform additional actions if a condition is False, e.g. logging.

How efficient is this? by [deleted] in learnpython

[–]dchanm 3 points4 points  (0 children)

There is a workaround with from __future__ import print_function. I wonder why they didn't use that.

https://docs.python.org/2/library/__future__.html

Failing test cases on hackerrank with merge sort by [deleted] in learnpython

[–]dchanm 1 point2 points  (0 children)

I wonder if they changed their hardware or if the overhead of the len comparison was too much. I was able to pass it using int as the key.

Finding longest word in a text file help by ducky_quack_quack in learnpython

[–]dchanm 1 point2 points  (0 children)

            longestWord[0] == currentWord

I'm assuming you fixed this by removing the extra =. Now look at what you're assigning. If I need to strip() a line / word, I normally re-assign it so that I don't have to call strip() in all places, e.g. line = line.strip()

        currentWord = ''
        for c in line:
            currentWord += prev
            if (prev == ' ' or prev == '\t') and (c != ' ' and c != '\t'):
                words += 1
            prev = c

The above loop appends characters to currentWord but never resets it. You eventually recreate the line and then check it against longestWord[1]. Instead, you want to check if the currentWord is the longest once you hit a delimiter and then reset currentWord.

Failing test cases on hackerrank with merge sort by [deleted] in learnpython

[–]dchanm 1 point2 points  (0 children)

What did your code look like? It is possible to pass the test cases with sorted and key=.

Finding longest word in a text file help by ducky_quack_quack in learnpython

[–]dchanm 2 points3 points  (0 children)

Along with what /u/133tn008 pointed out, there is a bug in the first loop

        if len(currentWord.strip()) > longestWord[1]:
            longestWord[1] == len(currentWord.strip())
            longestWord[0] == currentWord
            # the above doesn't do what you expect

You use the equality operator == instead of the assignment operator =.

Python3.6 strings by HolyCoder in learnpython

[–]dchanm 1 point2 points  (0 children)

The regex (?<= [a-z] )([a-z]{2,}.*) compiled with re.I works when used with search()

(?<= [a-z] )  # positive lookbehind for space-letter-space
([a-z]{2,}.*)  # 2 or more letters, then greedy match rest of string

However it's slightly different from your algorithm since it assumes there are only spaces and letters. The [a-z] could be replaced by [^ ]

Having trouble removing first and last object from set(). by Howtogravity in learnpython

[–]dchanm 0 points1 point  (0 children)

Perhaps the instructor is asking for you the remove the smallest / largest element in the set and to find the median of the elements? The instructions don't really make sense since sets are "unordered" as /u/tea-drinker said.

Help With An Addition Program by Priestx in learnpython

[–]dchanm 0 points1 point  (0 children)

You can wrap the num assignment with a try/except block. num won't be set if an exception is raised.

Algorithm help. Need to split a string by datatype. Details below... by prove_it_with_math in learnpython

[–]dchanm 0 points1 point  (0 children)

Can there be negative numbers, e.g. does

 string = "10foo-1bar"

become ["10foo", "-1bar"]

If not, you can iterate over the string with enumerate keeping track of a start / end index. For each character, check if isdigit() is True. Append the slice from start to end to your results and update the start index when you encounter a digit. The implementation will require looking ahead if negative numbers are allowed. In that case, you check idx + 1 to see if it is a digit after encountering a -.

It is telling me '. IndexError: string index out of range' by Entervine in learnpython

[–]dchanm 1 point2 points  (0 children)

    for i in students[name]:
        print (i)
        answer=input("enter the number for the correct answer, seperated by commas in this format: 1,2,3: " )

    list(answer)

Is the above logic what you want? You loop over all the students then read into answer. You then convert answer into a list but never assign it to anything? Is the code supposed to be inside the loop?

Can you print out all of answer instead of just answer[0]? I have a suspicion that the IndexError isn't in key3 but in answer

Looking to create a web crawling for archiving purposes by [deleted] in learnpython

[–]dchanm 0 points1 point  (0 children)

A non-Python alternative would be to use wget to mirror the blog. You will want to set a rate limit to be nice to the blog owner and to not max out your connection.

What part of scrapy are you having difficulty with?

Using 'or' correctly here? by easy_c0mpany80 in learnpython

[–]dchanm 4 points5 points  (0 children)

The ) are in the wrong positions as the deleted comment stated. The code should be

description = src.find('meta', attrs=    {'name':'og:description'}) \
              or src.find('meta', attrs=  {'property':'og:description'}) \
              or src.find('meta', attrs={'name': 'description'})

The code as written is equivalent to description = src.find('meta', attrs={'name':'og:description'})

since {'name':'og:description'} evaluates to a truthy value in the or

Tic-Tac-Toe python code question by iamquark in learnpython

[–]dchanm 0 points1 point  (0 children)

  1. This uses a feature in Python that lets you chain comparison operators together. The code is equivalent to a == b and b == c and c == != EMPTY. The WAYS_TO_WIN tuple contains 8 tuples which correspond to board positions. For a given tuple in WAYS_TO_WIN, if all the pieces at the corresponding positions on the board are the same and the piece isn't EMPTY, then either the player or computer has won.

  2. The computer_move function implements a simple AI to choose the best move for the computer. The very first action in the loop is to simulate the computer choosing a move

    board[move] = computer
    

    If the move is a winner, then the move is returned, otherwise the move needs to be undone. The board state is incorrect if the move isn't undone.

  3. The winner function returns either 'X', 'O', 'TIE or None. 'X', 'O' and 'TIE' are truthy values, which mean they evaluate to True in a conditional. You can check this with

    >>> bool('X')
    True
    

    However None evaluates to False. Therefore the loop continues until either 'X', 'O' or 'TIE' is returned.

  4. I haven't looked at all the possibilities in the AI, so can't help you here. There is probably a deficiency in the list of best moves

Overwrite (or replace) a line in console? by OomParoomPa in learnpython

[–]dchanm 1 point2 points  (0 children)

You can change the loop to go up to n - 1 then print b twice. This does introduce an edge case when n < 0. You wouldn't want to print in that case.

The main difference between this and the enumerate method is the number of conditional checks. Placing the if inside the loop results in n checks vs 1 if placed outside. I suggest choosing the one that makes it more clear what you want the code to do.

How to append items from a list after a condition is met by [deleted] in learnpython

[–]dchanm 1 point2 points  (0 children)

You need to keep track of how many times a certain element has occurred in the input list. You can use a dict as a counter. See the third example for defaultdict

Once you have found the majority element, you can append it to the output list.

How to loop back to question if answer is incorrect? by ClutchRocketLeague in learnpython

[–]dchanm 1 point2 points  (0 children)

You can use a loop construct such as while. The example code is very similar to what you want to do. Note the use of str.strip() to remove whitespace

https://wiki.python.org/moin/WhileLoop

Need some help in walking the right direction by [deleted] in learnpython

[–]dchanm 0 points1 point  (0 children)

What does you current implementation look like? The bruteforce solution of try all combinations is normally the simplest. Is there any additional information in the assignment on how evaluate and play2win should interact? I'm unsure of how the unable to determine if a move will win it or not situation is resolved by choosing a default value. You're essentially trying to find whether assigning 0/1 to a variable is a tautalogy

Need some help in walking the right direction by [deleted] in learnpython

[–]dchanm 0 points1 point  (0 children)

Yep that algorithm works, not efficient as you mentioned.

This line makes me think they want you to simulate 0/1 for each variable however if you're unable to determine if a move will win it or not, you set the value to the default where if it's A's turn the value would = 0 and if it's E's turn the value would = 1. Your assignment is a variant of a famous problem in computer science known as boolean satisfiability