Git Product home page Git Product logo

python-workout's Introduction

Code files from "Python Workout"

My book, "Python Workout" (https://PythonWorkout.com/) contains 50 exercises that help to improve your Python fluency. This repository contains the code and solutions to those exercises, including all of the "beyond the exercise" additional, bonus exercises.

The main exercises have "pytest" tests, while the "beyond" exercises don't.

While you're welcome to look at this code, you should NOT look at it before you work on a solution by yourself! You'll learn the most by actually putting in the work, and trying to solve the problems. Looking at the answer isn't nearly as useful to your learning.

Don't forget that my free, weekly "Better developers" newsletter (currently read by about 18,000 people) contains a new Python-related article each week. Sign up at https://BetterDevelopersWeekly.com/ .

Enjoy!

Reuven

python-workout's People

Contributors

reachtarunhere avatar reuven avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-workout's Issues

e05b2_punctuation.py do not return the correct result

When I tested with 2 words "python" and "air", the result was:

"ythonpay"
"iraay" (this is not correct, it should output airway)

I think the code should be like this

    if word[0].lower() in 'aeiou':
        output = f'{word}way'
        return output + punctuation

    output = f'{word[1:]}{word[0]}ay'
    return output + punctuation 

or

    if word[0].lower() in 'aeiou':
        output = f'{word}way'
    else:    
        output = f'{word[1:]}{word[0]}ay'

Chapter 1 Exercise 2 Beyond 1

The code in the repo is not in line with what is stated in the book because it uses the splat character for the first argument. This leads to different behaviour from the in-built sum

In [1]: sum([1,2,3], 4)
Out[1]: 10

In [2]: %paste

def mysum(*numbers, start=0):
"""Accepts any number of numeric arguments as inputs.
Returns the sum of those numbers, plus the value of "start",
which defaults to 0.
"""
output = start
for number in numbers:
output += number
return output

In [3]: mysum([1,2,3], 4)

TypeError Traceback (most recent call last)
in ()
----> 1 mysum([1,2,3], 4)

in mysum(start, *numbers)
6 output = start
7 for number in numbers:
----> 8 output += number
9 return output

TypeError: unsupported operand type(s) for +=: 'int' and 'list'

e21b1_md5_files.py (calculate the MD5 hash for the contents of every file)

I think you are calculating the MD5 of the filename string... not of the content of the file...

for one_filename in glob.glob(f'{dirname}/*'):
    try:
        m = hashlib.md5()
        m.update(one_filename.encode())
        output[one_filename] = m.hexdigest()
    except:
        pass

Perhaps...

for one_filename in glob.glob(f'{dirname}/*'):
    try:
        with open(one_filename, 'rb') as file:
            data = file.read()
            output[one_filename] = hashlib.md5(data).hexdigest()
    except:
        pass

wcfile.txt and e20_wc.py miscount

The statement of the exercise indicates: "Number of words (separated by whitespace)", however the last word of each line is separated by a '\n' instead of a ' ', therefore the count is not correct.

Solution to problem 19.2 seems to have a bug

The problem states:
"Ask the user to enter integers, separated by spaces. From this input, create a dict whose keys are the factors for each number, and the values are lists containing those of the users’ integers that are multiples of those factors."

For an input of "6 8 15 30 10", according to the question's phrasing, the expected output should be:

    {1: [6, 8, 15, 30, 10],
     2: [6, 8, 30, 10],
     3: [6, 15, 30],
     6: [6, 30],
     4: [8],
     8: [8],
     5: [15, 30, 10],
     15: [15, 30],
     10: [30, 10],
     30: [30]}

Here, the keys are the factors for each of the numbers - values are lists containing numbers from user input that are multiples of said factors.

However the solution when run with the same input string argument returns:

      {6: [1, 2, 3, 6], 
        8: [1, 2, 4, 8],
       15: [1, 3, 5, 15], 
       30: [1, 2, 3, 5, 6, 10, 15, 30]}

The issue with the given solution seems to be that the keys are the users' integers and the values are the factors for each numbers.

e12b1_most_repeated_vowels.py gives IndexError if word has no vowels

My suggestion:

def most_repeating_vowel_count(word):
    vowels = 'aieouAIEOU'
    vowel_dict = Counter({letter: count for letter, count in Counter(word).items() if letter in vowels})
    if not vowel_dict:  # if there are no vowels in the word
        return 0
    else:
        return vowel_dict.most_common(1)[0][1]

e07b1_capital.py do not check if the first character is a vowel and uppercase

As a result, if the word we check is: Octopus, then output should be Uboctubopubus, not Octubopubus.
I think the code can be something like this.

def ubbi_dubbi(string):
    output = []
    if string[0].lower() in "aiueo":
        result = f'ub{string[0]}'
    else:
        result = f'{string[0]}'   

    if string[0].isupper():
        output.append(result.capitalize())
    else:
        output.append(result)    

    for each in string[1:]:
        if each in "aiueo":
            output.append(f'ub{each}')
        else:
            output.append(each)    
    return ''.join(output)

e13b1_namedtuple_records.py throws KeyError

The solution in e13b1_namedtuple_records.py throws an error: KeyError: 'last'

In the solution below:

def format_sort_records(list_of_tuples):
    output = []
    template = '{last:10} {first:10} {distance:5.2f}'
    for person in sorted(list_of_tuples, key=operator.attrgetter('last', 'first')):
        output.append(template.format(*(person._asdict())))
    return output

I believe you need two asterisks in output.append to make it work:

output.append(template.format(**(person._asdict())))

Reference: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists

e46b2 - enumerate with optional argument

Hi @reuven , very nice book, I'm really enjoying doing the "beyond the exercises".

When you asked for writing the "enumerate" class passing an optional argument, did you mean to print return since the optional index or to return everything but with different indexing?

Your solution prints the following:

** Starting at 0 **
0: a
1: b
2: c
** Starting at 2 **
2: c

But I thought you were asking for this (and that's what I coded :)):

** Starting at 0 **
0: a
1: b
2: c
** Starting at 2 **
2: a
3: b
4: c

[Question]Chapter 10: Exercise 47 beyond the exercise 1

Reuven,

你好!
I am reading python workout and I really like this book, especially the beyond the exercise part . But I found that I don't understand the first beyond the exercise question of Exercise 47. What is the attribute "self.returns" expected to contain? What does "a list of attribute names" indicate?
I implemented my own "self.returns", but I am not sure whether it is correct. Here is my code:

class Circle(CircleIterator):
      def __init__(self, data, number):
          super().__init__(data, number)
          self.returns = []
    
      def __next__(self):
          value = super().__next__()
          self.returns.append(value)
          return value

Could you please give me more information if it's not correct? Thanks a lot!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.