reuven / python-workout Goto Github PK
View Code? Open in Web Editor NEWFiles for the Python Workout book
Files for the Python Workout book
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.
I think it's supposed to be like that
if word[0].lower() in 'aeiou':
output = f'{word}way'
else:
output = f'{word[1:]}{word[0]}ay'
def sum_numeric(*items):
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!
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.
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'
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
https://github.com/reuven/python-workout/blob/master/ch01-numbers/e03b1_before_after.py
"preceding the dEcimal point"
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]: 10In [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 outputIn [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 outputTypeError: unsupported operand type(s) for +=: 'int' and 'list'
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]
The user input is a word. We are guessing the word so we don't need to convert the user input into the integer.
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
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)
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
The solution on github returns sum of old and even numbers which is not in line with the idea in the book.
The code can be like:
def ex9_ch4(list):
return [sum(list[0::2]), sum(list[1::2])]
If I run the function sum_intable() with the input list ['1', '2', '3'] the function will return the TypeError. The is_intable function returns True for each of these input elements.
The code doesn't run because of "in_instable" typo in the line below:
Further, even if we correct the typo sum_intable([42, 1]) would result in 2 instead of 43 because everything is being typecasted to an int from a bool
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.