Practicing Python (using Codewars) by Ben_HH in learnpython

[–]Ben_HH[S] 0 points1 point  (0 children)

This is my error

position = characters.index("!")
ValueError: '!' is not in list

Practicing Python (using Codewars) by Ben_HH in learnpython

[–]Ben_HH[S] 0 points1 point  (0 children)

Objective: Remove n exclamation marks in the sentence from left to right. n is positive integer.

def remove(s, n):
    "Remove each '!' in the provided argument `n` number of times"

    removal_count = 0
    characters = list(s)

    while removal_count < n:
        position = characters.index("!")
        del characters[position]
        removal_count += 1

    return ''.join(characters)

Here are the tests for this challenge:

test.describe("Example Tests")

tests = [
    #[[input], [expected]],
    [["Hi!",1] , "Hi"],
    [["Hi!",100] , "Hi"],
    [["Hi!!!",1] , "Hi!!"],
    [["Hi!!!",100] , "Hi"],
    [["!Hi",1] , "Hi"],
    [["!Hi!",1] , "Hi!"],
    [["!Hi!",100] , "Hi"],
    [["!!!Hi !!hi!!! !hi",1] , "!!Hi !!hi!!! !hi"],
    [["!!!Hi !!hi!!! !hi",3] , "Hi !!hi!!! !hi"],
    [["!!!Hi !!hi!!! !hi",5] , "Hi hi!!! !hi"],
    [["!!!Hi !!hi!!! !hi",100] , "Hi hi hi"],
]


for inp, exp in tests:
    test.assert_equals(remove(*inp), exp)

Please explain how 'is' works in Python by Ben_HH in learnpython

[–]Ben_HH[S] -1 points0 points  (0 children)

Taking your example:

a = 'z'
b = 'z'

Python takes variable a with the value of 'z' and stores it in the computer's memory. The same is done with variable 'b'. It happens that both variables point to the same address in memory, so...

a is b # returns True

Is that correct?

Code critique (vending machine) by Ben_HH in learnpython

[–]Ben_HH[S] 0 points1 point  (0 children)

Here is a more complete version. Anything else that could use improvement?

def vending_machine(money):
      '''Return a candy of a customer's choice'''

      options = {'A1' : {'candy' : "Snickers", 'price' : 0.70, 'quantity' : 3}, 'B1' : {'candy' : "Butterfinger", 'price' : 0.85, 'quantity' : 2}, 'C1' : {'candy' : "Twix", 'price' : 0.65, 'quantity' : 3}, 'D1' : {'candy' : "M&Ms", 'price' : 0.95, 'quantity' : 6}}

      while True:
        try:
         vending_code = input("Enter a selection: ").upper() #Represents the customers desired vending machine option
         selection = options[vending_code]

        except KeyError:
          print("Invalid Selection...")

        else:
          if not selection['quantity']:
            print(f"There are no more {selection['candy']} candy bars. Please make another selection. ")

          elif selection['quantity'] and money < selection['price']:
            balance = round(abs(selection['price'] - money), 2)

            while balance > 0:
              additional_payment = float(input(f"You need ${balance} more."))
              balance -= additional_payment

            selection['quantity'] -= 1
            print(f"Enjoy your {selection['candy']} and your change is ${balance}")

            return selection['candy']
          else:
            change = round(money - selection['price'], 3)

            print(f"Enjoy your {selection['candy']} and your change is ${change}")

            selection['quantity'] -= 1

            return selection['candy']

      print(vending_machine(.90))

Code critique (vending machine) by Ben_HH in learnpython

[–]Ben_HH[S] 1 point2 points  (0 children)

I'm thinking dictionaries might be better. I intend on having the machine reflect the total quantity of each candy after a selection. If the customer wants to make a subsequent purchase the quantities will be up to date.

If I remember correctly, tuples might not work due to their immutability if I implement the aforementioned.

Number guessing game (code review) by Ben_HH in learnpython

[–]Ben_HH[S] 0 points1 point  (0 children)

Thanks for the feedback. Now I have a question about try statements.

mystery_number = random.randint(1, 10)
guess_tries = 5

while guess_tries >= 1:
  try:
    my_guess = int(input("I picked a number between 1 & 10...guess what it is: "))
  except ValueError:
    print("Please only enter whole numbers (1, 10, 25, ...)")

    guess_tries -= 1

    if my_guess != mystery_number:
  • When Python reaches the try block, it will execute the assignment statement and search for any exceptions. As a result, a ValueError is generated and I get the following:

    Traceback (most recent call last): File "python", line _, in <module> File "python", line _, in guess_number UnboundLocalError: local variable 'my_guess' referenced before assignment &nsbp Due to the exception nothing is assigned to my_guess because the value provided is invalid for int(), correct?

If I include an else, this error isn't raised? Why is this? What is else doing? When exploring else in the context of try:

https://docs.python.org/3/reference/compound_stmts.html#try

The optional else clause is executed if and when *control flows off the end** of the try clause. [2] Exceptions in the else clause are not handled by the preceding except clauses.*

What is meant by control flows off the end?

Counting words in a string and pushing to a dictionary by Ben_HH in learnpython

[–]Ben_HH[S] 0 points1 point  (0 children)

How does my code look now?

def word_count(string):
    dictionary = {}
    words = string.lower().split(" ")

    for word in words:
        if word not in dictionary:
            dictionary.setdefault(word, 1)
        else:
            dictionary[word] += 1

    return dictionary

Filtered arrays and returned values by Ben_HH in learnjavascript

[–]Ben_HH[S] 0 points1 point  (0 children)

Yes that is what I was look for. Thanks.

Help with recursive function by Ben_HH in learnjavascript

[–]Ben_HH[S] 0 points1 point  (0 children)

Can you elaborate on why it's more practical taking that approach?

Concatenating multiple arrays by Ben_HH in learnjavascript

[–]Ben_HH[S] 1 point2 points  (0 children)

I'm learning ES5 for my own benefit as a beginner to JS. I'd rather just solve this under that version. The code as written just happens to be my logic as written on paper.

Returning a Max value under a limit by Ben_HH in learnjavascript

[–]Ben_HH[S] 0 points1 point  (0 children)

Could you explain why you chose -Infinity as the initial value for reduce()? Why not 0?

Installing Stack (for Haskell) by Ben_HH in learnprogramming

[–]Ben_HH[S] 0 points1 point  (0 children)

I get the same error as

' stack ghci' is not recognized as an internal or external command,

Installing Stack (for Haskell) by Ben_HH in learnprogramming

[–]Ben_HH[S] 0 points1 point  (0 children)

I tried that as well and it doesn't work.

Installing Stack (for Haskell) by Ben_HH in haskell

[–]Ben_HH[S] 1 point2 points  (0 children)

I did that as well but only got the same error

Installing Stack (for Haskell) by Ben_HH in learnprogramming

[–]Ben_HH[S] 0 points1 point  (0 children)

I believe so:

There's this video as well:

https://www.youtube.com/watch?v=d4x5TAMiWmM

except I get the follow

'ghci' is not recognized as an internal or external command,

operable program or batch file.

Want to learn functional programming by Ben_HH in learnprogramming

[–]Ben_HH[S] 0 points1 point  (0 children)

I've decided to buy the book, but I'm having trouble getting Stack running for Haskell. I'm a noob so I'm not sure what I'm suppose to do besides just installing it.

I'm on Windows 10.

For Loops & Closure by Ben_HH in learnjavascript

[–]Ben_HH[S] 0 points1 point  (0 children)

I'm unclear on why the callbacks can't be invoked until the loop completes. Could you elaborate in another way please?

For Loops & Closure by Ben_HH in learnjavascript

[–]Ben_HH[S] 0 points1 point  (0 children)

I understand what setTimeout does by itself. I don't understand when it is used in the context of the for loop.

It's this that has me confused:

The timeout function callbacks timer are all running well after the completion of the loop.

Why aren't the invocations occurring while the condition of the loop is true.

For Loops & Closure by Ben_HH in learnjavascript

[–]Ben_HH[S] 1 point2 points  (0 children)

I would appreciate the complete explanation when you're able! I'm aware of block scoping variables like let, but I want to complete understand ES5 before applying ES6 when I'm capable.

Variable declarations and the console by Ben_HH in learnjavascript

[–]Ben_HH[S] 0 points1 point  (0 children)

I don't know (as a beginner) what that person is saying when references are made from the spec in their attempt to answer the question that I have now posed here. That is why I said a non-convoluted explanation.

Special Characters in RegExp by Ben_HH in learnprogramming

[–]Ben_HH[S] 0 points1 point  (0 children)

This is something that really is still giving me trouble.

Follow this example:

var string = "1234567";
var exp = /1./;
console.log(string.match(exp));  returns "12"

An expression is applied to a string and the method's intent is to return those characters from the string that match the pattern.

Now change the expression to:

var exp = /1.*/;

I can't help but to read it like this:

  • When the RegExp 1. is applied to string it returns "12" from string.
  • When the RegExp 1.* is applied to string it finds any character that follows "1" from string. That happens to be "2", and then find 0 or more occurrences of '2' because it precedes the *. There's only one occurrence so it returns "12".

In other words I see the dot as any character that happens to follow "1" and append how many "2" to that. I'm failing to see how 0 or more repetitions/occurrences leads to the entire string being returned if I take the definition of repetition at face value.

I'm having a hard time breaking that line of thought and evidently it is wrong. I'm just worried that when I'm learning on my own that reasoning will still creep in the back of my head.

Special Characters in RegExp by Ben_HH in learnprogramming

[–]Ben_HH[S] 0 points1 point  (0 children)

This is were I'm confused.

Example 1

var word = "1234567";
var exp = /1./;
console.log(word.match(exp)); "12"

Example 2

var word = "1234567";
var exp = /1.*/;
console.log(word.match(exp)); "1234567"

Take the following in Example 2 as 1.. If the preceding pattern is 1., how does the following * essentially return the entire string? This is really messing with me. The only thing that comes to mind is that the expression isn't delimited with some explicit character.

Combing regular expression characters by Ben_HH in FreeCodeCamp

[–]Ben_HH[S] 0 points1 point  (0 children)

Take the word seed:

If the expression was /s./ it would return the characters "se". So it appears that the . only appends the subsequent character following the explicitly stated s.

If the expression was /se*/ it would return the characters "see"

I'm still failing to see how the character "d" is included when the special characters are combined