返回介绍

Exercises

发布于 2025-02-25 23:43:36 字数 10369 浏览 0 评论 0 收藏 0

1 . Solve the FizzBuzz probelm

“Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

# YOUR CODE HERE

# range(start, stop, step)
# for loop
# print function
# % operator
# check for equality
# if-elif-else control flow

for i in range(1, 101):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

2 . Given x=3 and y=4, swap the values of x and y so that x=4 and y=3.

x = 3
y = 4
# YOUR CODE HERE

# use of temporary variable
# tuple unpacking

tmp = x
x = y
y = x
print x, y

x = 3
y = 4
x, y = y, x
print x, y
4 4
4 3

3 . Write a function that calculates and returns the euclidean distance between two points \(u\) and \(v\), where \(u\) and \(v\) are both 2-tuples \((x, y)\). For example, if \(u = (3,0)\) and \(v = (0,4)\), the function should return \(5\).

# YOUR CODE HERE

# euclidean distance formula
# operators **
# square root function
# anatomy of a function

u = (3, 0)
v = (0, 4)

((v[0] - u[0])**2 + (v[1] - u[1])**2)**0.5

def euclidean(u, v):
    """Returns the Euclidean distance between points u and v."""
    return ((v[0] - u[0])**2 + (v[1] - u[1])**2)**0.5

euclidean(u, v)
5.0

4 . Using a dictionary, write a program to calculate the number times each character occurs in the given string s. Ignore differneces in capitalization - i.e ‘a’ and ‘A’ should be treated as a single key. For example, we should get a count of 7 for ‘a’.

s = """
Write a program that prints the numbers from 1 to 100.
But for multiples of three print 'Fizz' instead of the number and f
or the multiples of five print 'Buzz'. For numbers which are
multiples of both three and five print 'FizzBuzz'
"""

# YOUR CODE HERE

# string methods
# dictionary
# for loop
# collections.Counter

# Version 1
print s.lower().count('a')

# Version 2
counter1 = {}
for _ in s.lower():
    counter1[_] = counter1.get(_, 0) + 1
print counter1['a']

# Version 3
from collections import defaultdict
counter2 = defaultdict(int)
for _ in s.lower():
    counter2[_] += 1
print counter2['a']

# Version 4
from collections import Counter
counter3 = Counter(s.lower())
print counter3['a']
7
7
7
7

5 . Write a program that finds the percentage of sliding windows of length 5 for the sentence s that contain at least one ‘a’. Ignore case, spaces and punctuation. For example, the first sliding window is ‘write’ which contains 0 ‘a’s, and the second is ‘ritea’ which contains 1 ‘a’.

s = """
Write a program that prints the numbers from 1 to 100.
But for multiples of three print 'Fizz' instead of the number and f
or the multiples of five print 'Buzz'. For numbers which are
multiples of both three and five print 'FizzBuzz'
"""

# YOUR CODE HERE

# string constants
# translate method
# replace method
# slicing iterables
# len function

import string
s1 = s.lower().translate(None, string.punctuation).replace(' ', '').replace('\n', '')

count = 0
start = 0
stop = 5

while (stop <= len(s1)):
    # print s1[start:stop]
    if 'a' in s1[start:stop]:
        count += 1
    start += 1
    stop += 1

print count
34

6 . Find the unique numbers in the following list.

x = [36, 45, 58, 3, 74, 96, 64, 45, 31, 10, 24, 19, 33, 86, 99, 18, 63, 70, 85,
 85, 63, 47, 56, 42, 70, 84, 88, 55, 20, 54, 8, 56, 51, 79, 81, 57, 37, 91,
 1, 84, 84, 36, 66, 9, 89, 50, 42, 91, 50, 95, 90, 98, 39, 16, 82, 31, 92, 41,
 45, 30, 66, 70, 34, 85, 94, 5, 3, 36, 72, 91, 84, 34, 87, 75, 53, 51, 20, 89, 51, 20]

# YOUR CODE HERE

# sort and remove duplicates
# negative indexing

# version 1
sorted_x = sorted(x)
unique_x = [sx[0]]
for _ in sorted_x[1:]:
    if _ != unique_x[-1]:
        unique_x.append(_)

print unique_x
print len(x)
print len(unique_x)

# using set
print list(set(x))
print len(x)
print len(set(x))
[1, 3, 5, 8, 9, 10, 16, 18, 19, 20, 24, 30, 31, 33, 34, 36, 37, 39, 41, 42, 45, 47, 50, 51, 53, 54, 55, 56, 57, 58, 63, 64, 66, 70, 72, 74, 75, 79, 81, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 94, 95, 96, 98, 99]
80
54
[1, 3, 5, 8, 9, 10, 16, 18, 19, 20, 24, 30, 31, 33, 34, 36, 37, 39, 41, 42, 45, 47, 50, 51, 53, 54, 55, 56, 57, 58, 63, 64, 66, 70, 72, 74, 75, 79, 81, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 94, 95, 96, 98, 99]
80
54

7 . Write two functions - one that returns the square of a number, and one that returns the cube. Now write a third function that returns the number raised to the \(6^{th}\) power using the two previous functions.

# YOUR CODE HERE

# getting comforatble with functions
# unit tests

def square(x):
    """Returns x^2."""
    return x**2

def cube(x):
    """Returns x^3."""
    return x**3

def pow6(x):
    """Returns x^6."""
    return cube(square(x))

# use of assert for testing
def test_pow6(x):
    assert(abs(pow6(x) - x**6) < 1e-6)

xs = [-2, 0, 1.5]
for x in xs:
    test_pow6(x)

8 . Create a list of the cubes of x for x in [0, 10] using

  • a for loop
  • a list comprehension
  • the map function
# YOUR CODE HERE

# list comprehensions
# map
# lambda functions

cubes1 = []
for i in range(1, 11):
    cubes1.append(i**3)
print cubes1

cubes2 = [i**3 for i in range(1, 11)]
print cubes2

print map(lambda x: x**3, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

9 . A Pythagorean triple is an integer solution to the Pythagorean theorem \(a^2 + b^2 = c^2\). The first Pythagorean triple is (3,4,5). Find all unique Pythagorean triples for the positive integers a, b and c less than 100.

# YOUR CODE HERE

# nested list comprehsnions
# inner and outer loops

print([(i, j) for i in range(1,4) for j in range(10, 14)])
print

pythagorean_triples = [(a, b, c) for a in range(1, 100)
                                 for b in range(1, 100)
                                 for c in range(1, 100)
                                 if a**2 + b**2 == c**2]
print pythagorean_triples
print

pythagorean_triples = [(a, b, c) for a in range(1, 100)
                                 for b in range(a, 100)
                                 for c in range(b, 100)
                                 if a**2 + b**2 == c**2]
print pythagorean_triples
[(1, 10), (1, 11), (1, 12), (1, 13), (2, 10), (2, 11), (2, 12), (2, 13), (3, 10), (3, 11), (3, 12), (3, 13)]

[(3, 4, 5), (4, 3, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 6, 10), (8, 15, 17), (9, 12, 15), (9, 40, 41), (10, 24, 26), (11, 60, 61), (12, 5, 13), (12, 9, 15), (12, 16, 20), (12, 35, 37), (13, 84, 85), (14, 48, 50), (15, 8, 17), (15, 20, 25), (15, 36, 39), (16, 12, 20), (16, 30, 34), (16, 63, 65), (18, 24, 30), (18, 80, 82), (20, 15, 25), (20, 21, 29), (20, 48, 52), (21, 20, 29), (21, 28, 35), (21, 72, 75), (24, 7, 25), (24, 10, 26), (24, 18, 30), (24, 32, 40), (24, 45, 51), (24, 70, 74), (25, 60, 65), (27, 36, 45), (28, 21, 35), (28, 45, 53), (30, 16, 34), (30, 40, 50), (30, 72, 78), (32, 24, 40), (32, 60, 68), (33, 44, 55), (33, 56, 65), (35, 12, 37), (35, 84, 91), (36, 15, 39), (36, 27, 45), (36, 48, 60), (36, 77, 85), (39, 52, 65), (39, 80, 89), (40, 9, 41), (40, 30, 50), (40, 42, 58), (40, 75, 85), (42, 40, 58), (42, 56, 70), (44, 33, 55), (45, 24, 51), (45, 28, 53), (45, 60, 75), (48, 14, 50), (48, 20, 52), (48, 36, 60), (48, 55, 73), (48, 64, 80), (51, 68, 85), (52, 39, 65), (54, 72, 90), (55, 48, 73), (56, 33, 65), (56, 42, 70), (57, 76, 95), (60, 11, 61), (60, 25, 65), (60, 32, 68), (60, 45, 75), (60, 63, 87), (63, 16, 65), (63, 60, 87), (64, 48, 80), (65, 72, 97), (68, 51, 85), (70, 24, 74), (72, 21, 75), (72, 30, 78), (72, 54, 90), (72, 65, 97), (75, 40, 85), (76, 57, 95), (77, 36, 85), (80, 18, 82), (80, 39, 89), (84, 13, 85), (84, 35, 91)]

[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (9, 40, 41), (10, 24, 26), (11, 60, 61), (12, 16, 20), (12, 35, 37), (13, 84, 85), (14, 48, 50), (15, 20, 25), (15, 36, 39), (16, 30, 34), (16, 63, 65), (18, 24, 30), (18, 80, 82), (20, 21, 29), (20, 48, 52), (21, 28, 35), (21, 72, 75), (24, 32, 40), (24, 45, 51), (24, 70, 74), (25, 60, 65), (27, 36, 45), (28, 45, 53), (30, 40, 50), (30, 72, 78), (32, 60, 68), (33, 44, 55), (33, 56, 65), (35, 84, 91), (36, 48, 60), (36, 77, 85), (39, 52, 65), (39, 80, 89), (40, 42, 58), (40, 75, 85), (42, 56, 70), (45, 60, 75), (48, 55, 73), (48, 64, 80), (51, 68, 85), (54, 72, 90), (57, 76, 95), (60, 63, 87), (65, 72, 97)]

10 . Fix the bug in this function that is intended to take a list of numbers and return a list of normalized numbers.

def f(xs):
    """Return normalized list summing to 1."""
    s = 0
    for x in xs:
        s += x
    return [x/s for x in xs]
# YOUR CODE HERE

# elementary debugging

def f(xs):
    """Return normalized list summing to 1."""
    s = 0
    for x in xs:
        s += x
    return [x/s for x in xs]

xs = [1.1,2.2,3.3,4.4]
print f(xs)

xs = [1,2,3,4]
print f(xs)


def f(xs):
    """Return normalized list summing to 1."""
    s = 0.0
    for x in xs:
        s += x
    return [x/s for x in xs]


xs = [1.1,2.2,3.3,4.4]
print f(xs)

xs = [1,2,3,4]
print f(xs)
[0.1, 0.2, 0.3, 0.4]
[0, 0, 0, 0]
[0.1, 0.2, 0.3, 0.4]
[0.1, 0.2, 0.3, 0.4]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文