Finished Chapter 6

This commit is contained in:
kerogen-pezy
2017-06-12 19:39:10 +08:00
parent 9dcd6a828c
commit c102fed0dd
17 changed files with 190 additions and 41 deletions

View File

@@ -0,0 +1,2 @@
@python.exe BulletPointAdder.py %*
@pause

View File

@@ -0,0 +1,16 @@
#! python3
'''
BulletPointAdder.py - Adds Wikipadia bullet points to the start
of each line of text on the clipboard
'''
import pyperclip
TEXT = pyperclip.paste()
# Separate lines and add stars.
LINES = TEXT.split('\n')
LINES = ["* " + line for line in LINES]
TEXT = '\n'.join(LINES)
pyperclip.copy(TEXT)

View File

@@ -0,0 +1,2 @@
@python.exe CharacterPictureGrid.py %*
@pause

View File

@@ -0,0 +1,2 @@
@python.exe Collatz.py %*
@pause

View File

@@ -0,0 +1,2 @@
@python.exe CommaConnection.py %*
@pause

View File

@@ -0,0 +1,2 @@
@python.exe DisplayInventory.py %*
@pause

View File

@@ -0,0 +1,2 @@
@python.exe Password.py %*
@pause

View File

@@ -0,0 +1,21 @@
#! python3
'''Password.py - An insecure password locker program'''
import sys
import pyperclip
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
if len(sys.argv) < 2:
print('Usage: python Password.py [account] - copy account password')
sys.exit()
ACCOUNT = sys.argv[1] # first command line arg is the account name
if ACCOUNT in PASSWORDS:
pyperclip.copy(PASSWORDS[ACCOUNT])
print('Password for ' + ACCOUNT + ' copied to clipboard.')
else:
print('There is no account named ' + ACCOUNT)

View File

@@ -0,0 +1,2 @@
@python.exe TestPrintTable.py %*
@pause

View File

@@ -0,0 +1,21 @@
#! python3
'''TestPrintTable.py - Test print_table function'''
TABLE_DATA = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def print_table(str_list):
'''print the table'''
col_widths = [0] * len(str_list)
for i in range(len(str_list)):
for j in range(len(str_list[0])):
if len(str_list[i][j]) > col_widths[i]:
col_widths[i] = len(str_list[i][j])
for j in range(len(str_list[0])):
for i in range(len(str_list)):
print(str_list[i][j].rjust(col_widths[i]), end=' ')
print()
print_table(TABLE_DATA)

View File

@@ -1,4 +1,7 @@
grid = [['.', '.', '.', '.', '.', '.'],
#! python3
"""Print character picture grid"""
GRID = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
@@ -8,7 +11,7 @@ grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
for i in range(len(grid[0])):
for l in grid:
for i in range(len(GRID[0])):
for l in GRID:
print(l[i], end="")
print()
print()

View File

@@ -1,22 +1,28 @@
def collatz(x):
if x % 2 == 0:
x = x // 2
else:
x = 3 * x + 1
print(x)
return x
#! python3
"""Calculate collatz function"""
def getInput():
def collatz(x_value):
'''collatz calculation'''
if x_value % 2 == 0:
x_value = x_value // 2
else:
x_value = 3 * x_value + 1
print(x_value)
return x_value
def get_input():
'''get custom input'''
try:
return int(input())
except (ValueError, NameError):
print('Your should input an integer.')
return getInput()
return get_input()
n = getInput()
if n == 0:
N = get_input()
if N == 0:
print('It would enter an infinite loop.')
else:
while n != 1:
n = collatz(n)
while N != 1:
N = collatz(N)
print(N)

View File

@@ -1,14 +1,18 @@
spam = ['apple', 'bananas', 'tofu', 'cats']
#! python3
'''test for list_to_str'''
def list2Str(l):
if not l:
SPAM = ['apple', 'bananas', 'tofu', 'cats']
def list_to_str(lst):
'''show list in string format'''
if not lst:
return ''
if len(l) == 1:
return l[0]
s = ''
for i in range(len(l) - 1):
s += l[i] + ', '
s += 'and ' + l[-1]
return s
if len(lst) == 1:
return lst[0]
ret = ''
for i in range(len(lst) - 1):
ret += lst[i] + ', '
ret += 'and ' + lst[-1]
return ret
print(list2Str(spam))
print(list_to_str(SPAM))

View File

@@ -1,20 +1,29 @@
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
#! python3
'''inventory'''
def displayInventory(inventory):
import os
STUFF = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
DRAGON_LOOT = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def display_inventory(inventory):
'''display'''
print("Inventory:")
total_num = 0
for k, v in inventory.items():
print(str(v) + " " + k)
total_num += v
for k, value in inventory.items():
print(str(value) + " " + k)
total_num += value
print("Total number of items: " + str(total_num))
def addToInventory(inventory, addedItems):
for item in addedItems:
def add_to_inventory(inventory, added_items):
'''add item to inventory'''
for item in added_items:
if item in inventory:
inventory[item] += 1
else:
inventory.setdefault(item, 0)
addToInventory(stuff, dragonLoot)
displayInventory(stuff)
add_to_inventory(STUFF, DRAGON_LOOT)
display_inventory(STUFF)
os.system('pause')

View File

@@ -5,5 +5,4 @@
- [Chapter 3 - Functions](ch03/README.md)
- [Chapter 4 - Lists](ch04/README.md)
- [Chapter 5 Dictionaries and Structuring Data](ch05/README.md)
- [Chapter 6 Manipulating Strings](ch06/README.md)

View File

@@ -1,21 +1,27 @@
# Chapter 5 Dictionaries and Structuring Data
> Q: 1. What does the code for an empty dictionary look like?
`{}`
> Q: 2. What does a dictionary value with a key 'foo' and a value 42 look like?
`{'foo', 42}`
> Q: 3. What is the main difference between a dictionary and a list?
The item stored in dictionary are unordered, while the items in a list are ordered.
> Q: 4. What happens if you try to access spam['foo'] if spam is {'bar': 100}?
`KeyError` error.
> Q: 5. If a dictionary is stored in spam, what is the difference between the expressions 'cat' in spam and 'cat' in spam.keys()?
no different.
> Q: 6. If a dictionary is stored in spam, what is the difference between the expressions 'cat' in spam and 'cat' in spam.values()?
`'cat' in spam` checks whether there is a 'cat' key, while `'cat' in spam.values()` checks whether there is a 'cat' value.
> Q: 7. What is a shortcut for the following code?

View File

@@ -0,0 +1,50 @@
# Chapter 6 Manipulating Strings
> Q: 1. What are escape characters?
Escape characters represent characters in string values that would otherwise be difficult or impossible to type into code.
> Q: 2. What do the \n and \t escape characters represent?
newline, tab
> Q: 3. How can you put a \ backslash character in a string?
`\\`
> Q: 4. The string value "Howl's Moving Castle" is a valid string. Why isnt it a problem that the single quote character in the word Howl's isnt escaped?
because of double quotes.
> Q: 5. If you dont want to put \n in your string, how can you write a string with newlines in it?
Multiline strings.
> Q: 6. What do the following expressions evaluate to?
> `'Hello world!'[1]`
> `'Hello world!'[0:5]`
> `'Hello world!'[:5]`
> `'Hello world!'[3:]`
'e', 'Hello', 'Hello', 'lo world!'
> Q: 7. What do the following expressions evaluate to?
> 'Hello'.upper()
> 'Hello'.upper().isupper()
> 'Hello'.upper().lower()
'HELLO', True, 'hello'
> Q: 8. What do the following expressions evaluate to?
> 'Remember, remember, the fifth of November.'.split()
> '-'.join('There can be only one.'.split())
['Remember,', 'remember,', 'the', 'fifth', 'of', 'November.']
> Q: 9. What string methods can you use to right-justify, left-justify, and center a string?
`rjust`, `ljust`, `center`
> Q: 10. How can you trim whitespace characters from the beginning or end of a string?
`lstrip`, `rstrip`