avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

9021_TUT_5

  2024-10-08        
字数统计: 2.6k字   |   阅读时长: 16min

Exercise 1

Problem Description

We are given a list L and an integer n. The task is to repeatedly extend the list L a certain number of times (n) by multiplying each element of the list by an increasing factor. The factors start at 2 and increase by 1 for each iteration.


In my solution, I used a while loop to iterate n times. In each iteration, I used a list comprehension to multiply each element of the list L by the current factor and then used the extend() method to add the new elements to the end of the list. Finally, I incremented the factor by 1 and decremented n by 1.
Because of the description: L'' == 3 * L', L' == 2 * L ….

My Solution

1
2
3
4
5
6
7
8
9
10
11
def f1(L: list, n: int):
# because of the des of L'' == 3 * L', L' == 2 * L ....
base = 2
# when n bigger than 0, base will always ++,
while n:
# I want use map() again, but list generator is more simple
# extend() will add all the elements in the list to the end of the list
L.extend([i * base for i in L])
base += 1
n -= 1
return L

Standard Solution

1
2
3
4
def f1(L, n):
for i in range(2, n + 2):
L.extend([e * i for e in L])
return L

Explanation

  1. My Solution: Uses a while loop where n is manually decremented after each iteration step by step since it can help me understand what we need. I keep track of the current base manually (base += 1).
  2. Standard Solution: Uses a for loop, which automatically increments i in each iteration. The range is explicitly set to go from 2 to n + 2, which avoids the need for manually handling the base.

Exercise 2

Problem Description

We are given a list L and an integer n. The task is to extend the list L such that it becomes the first n members of an infinite list, which is defined as:

  • L, followed by 2 * L, followed by 4 * L, followed by 8 * L, and so on.

This means that:

  • L is initially concatenated with 2 * L (all elements of L multiplied by 2).
  • Then, 4 * L (all elements of L multiplied by 4) is concatenated, followed by 8 * L, and so on, until the length of the list is at least n.

The challenge is to achieve this without using any for or while loops.


We can see the pattern here: L, 2 * L, 4 * L, 8 * L, ... until it reaches the length of n.

At first, I ignored the description that “without using any for or while loops.”

Here is my solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Assume that the argument L is a nonempty list of integers
# and the argument n is an integer at least equal to the
# length of L.
#
# Given an integer x and a list of integers S,
# let x * S denote the list obtained from S
# by multiplying all its elements by x.
#
# L becomes the first n members of the infinite list
# defined as L concatenated with 2 * L concatenated
# with 4 * L concatenated with 8 * L...
#
# Use no for nor while statement.
def f2(L: list, n: int):
while len(L) < n:
L.extend([i * 2 for i in L])
# use the slice to cut the list to reach the length of n
return L[:n]

Standard Solution

1
2
3
def f2(L, n):
L.extend(e * 2 for e in L if len(L) < n)
return L

Exercise 3

Problem Description

The goal of this problem is to process a list L, which contains nonempty lists of nonempty lists of integers, and return a pair of lists. Each of these lists will be filtered based on specific conditions related to the length of the sublists and the values inside them.

Here’s the task broken down:

  1. First List in the Pair:

    • For each sublist L' of L, if the length of L' is at least n, then:
    • For each sublist L'' of L', if the sum of the elements of L'' is strictly positive:
    • Collect all the strictly positive integers from L'' and add them to the first list.
  2. Second List in the Pair:

    • This is similar to the first list but slightly simpler:
    • For each sublist L' of L, if its length is at least n:
    • For each sublist L'' of L', if the sum of its members is strictly positive:
    • Directly collect all the strictly positive integers from L'' and add them to the second list.

The task specifies that we must use list comprehensions only—no loops, functions, or other control structures.

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
def f3(L, n):
# First list comprehension: we process L' for length and filter based on sum
first = [
[x for L2 in L1 if sum(L2) > 0 for x in L2 if x > 0]
for L1 in L if len(L1) >= n
]

# Second list comprehension: similar filtering but simpler output structure
second = [
[x for x in L2 if x > 0]
for L1 in L if len(L1) >= n for L2 in L1 if sum(L2) > 0
]
return first, second

Explanation

  1. First List (first):

    • We first filter out the sublists L1 whose length is at least n (for L1 in L if len(L1) >= n).
    • Inside this, for each valid L1, we process its members L2 (which are sublists of integers). We check if the sum of elements of L2 is strictly positive (if sum(L2) > 0).
    • For each valid L2, we collect the strictly positive integers (for x in L2 if x > 0).
    • This gives us the first list of lists, where each list contains the positive integers from sublists of sublists whose sum is positive.
  2. Second List (second):

    • Similar to the first list, but here we directly collect the strictly positive integers from the valid sublists L2, without additional nesting.
    • We again check that the sum of L2 is strictly positive and that the length of L1 is at least n.
    • The result is a more flattened structure than the first list.
  3. Key Concepts:

    • Filtering: Both lists involve filtering based on the length of L1 and the sum of L2.
    • List Comprehensions: Used extensively to meet the problem’s requirement of not using explicit loops or other control structures.

Standard Solution

1
2
3
4
5
6
7
8
9
10
def f3(L, n):
return ([[e for L2 in L1 if sum(L2) > 0
for e in L2 if e > 0
] for L1 in L if len(L1) >= n
],
[[e for e in L2 if e > 0]
for L1 in L if len(L1) >= n
for L2 in L1 if sum(L2) > 0
]
)

Exercise 4

We are given a list L of integers, and the goal is to return a list of lists that consists of pairs of elements from the beginning and end of the list. Specifically:

  1. The number of pairs n at the beginning and the end should be as large as possible while maintaining symmetry.
  2. If the length of L is odd, the remaining element in the middle (that cannot form a pair) should be included as a single list.
  3. No for or while loops should be used in the implementation.

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def f4(L: list[int]) -> list[list[int]]:
# Calculate the number of pairs we can take from both the beginning and end.
n = len(L) // 2

# Take pairs from the beginning of the list. These are the first n // 2 pairs.
start_pairs = [L[i:i + 2] for i in range(0, len(L) // 4 * 2, 2)]

# Take pairs from the end of the list. These are the last n // 2 pairs.
end_pairs = [L[i:i + 2] for i in range(len(L) - (len(L) // 4 * 2), len(L) - 1, 2)]

# Calculate the remaining part (middle element if the list length is odd).
remain_part = [L[len(L) // 4 * 2 : len(L) -(len(L) // 4 * 2)]] if len(L) % 4 else []

# Combine the start pairs, the remaining part (if any), and the end pairs.
return start_pairs + remain_part + end_pairs if remain_part else start_pairs + end_pairs

Standard Solution

1
2
3
4
5
6
def f4(L):
if len(L) % 2:
return [L[i : i + 2] for i in range(0, len(L) // 4 * 2, 2)] +\
[L[len(L) // 4 * 2 : len(L) -(len(L) // 4 * 2)]] +\
[L[i : i + 2] for i in range(len(L) - (len(L) // 4 * 2), len(L) - 1, 2)]
return [L[i : i + 2] for i in range(0, len(L) - 1, 2)]

Explanation

The reason of why we use len(L) // 4 * 2 is that we want to get the number of pairs we can take from both the beginning and end.

We have a pair at the beginning and a pair at the end, so we need to divide the length of the list by 4 to get the number of pairs. We then multiply this by 2 to get the total number of elements in these pairs.

Exercise 5

Before E5, let’s do some exercises.

Normal dictionary:

1
2
3
4
5
6
7
8
9
d = {}
for i in ['a','b','c','a','b','c']:
if i in d:
d[i] += 1
else:
# need to initialize the value of the key
d[i] = 1

print(d)

defaultdict:

1
2
3
4
5
6
7
8
from collections import defaultdict

d = defaultdict(int)
for i in ['a','b','c','a','b','c']:
# no need to initialize the value of the key
d[i] += 1

print(d)

Counter:

1
2
3
4
5
6
from collections import Counter

# easy to count the number of each element
d = Counter(['a','b','c','a','b','c'])

print(d)

Problem Description

The task is to count the number of customers from different countries by reading a CSV file and then printing the count per country in alphabetical order.

The provided solutions use Python’s csv module to read the data and a dictionary (from the collections.defaultdict class) to keep track of the count of customers from each country.

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import csv
from collections import defaultdict

def f5(filename= 'customers-100.csv') -> None:
# read the file
with open(filename, newline='') as csvfile:
reader = csv.reader(csvfile)
next(reader) # skip the header

# count the number of customers per country
count = defaultdict(int)
for row in reader:
count[row[6]] += 1 # country is in the 7th column

# Print the results sorted by country name
for key, value in sorted(count.items()):
print(f'{value} from {key}')

Standard Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
import csv
from collections import defaultdict

countries = defaultdict(int)
with open('customers-100.csv') as file:
_ = next(file) # skip the header
csv_file = csv.reader(file)
for records in csv_file:
countries[records[6]] += 1 # country data is in the 7th column

# Print the results sorted by country name
for country in sorted(countries):
print(countries[country], 'from', country)

Additional Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import csv
from collections import Counter

def f5_counter(filename='customers-100.csv') -> None:
with open(filename, newline='') as csvfile:
reader = csv.reader(csvfile)
next(reader) # skip the header

# Create a Counter from the country column (assumed to be the 7th column)
country_counter = Counter(row[6] for row in reader)

# Print the results sorted by country name
for key, value in sorted(country_counter.items()):
print(f'{value} from {key}')

f5_counter()

Additional Additional Solution (Data Analysis) (NOT Mandatory)

Not Mandatory, but it’s a good way to learn how to use pandas to do data analysis.

1
2
3
4
5
6
7
8
9
10
import pandas as pd

# read file by pandas
df = pd.read_csv("customers-100.csv")

# use pandas' count()
country_counts = df['Country'].value_counts().sort_index()

for country, count in country_counts.items():
print(f'{count} from {country}')

Explanation

Reading the CSV file:

1
df = pd.read_csv(filename)

Using the read_csv() function, Pandas can directly load a CSV file into a DataFrame object, which is similar to a table structure. Each column becomes an attribute of the DataFrame, and the column names automatically become the labels for the DataFrame.

Counting the number of customers per country:

1
df['Country'].value_counts()

Pandas provides the value_counts() method, which can directly count the frequency of each value in a column. Here, we call value_counts() on the Country column to get the number of customers from each country.

Exercise 6

Problem Description

The task is to create a directory structure where:

2024-10-08.png

  • There is a top-level directory named First_10_words_per_letter.
  • Under this directory, there are two subdirectories:
    • Vowels: Containing files for letters A, E, I, O, U, Y.
    • Consonants: Containing files for the rest of the letters in the alphabet (B, C, D, etc.).
  • Each letter (A to Z) has its own file, and each file contains the first 10 words from a dictionary.txt file that start with that letter.
  • The directory structure and the files should be generated programmatically, without using any existing hierarchy.

My Solution(Not Perfect, it relies on the sort of dictionary.txt )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

import os
from pathlib import Path
from string import ascii_uppercase

def main():
# Create the top directory
top_dir = Path('First_10_words_per_letter')
# Create the subdirectories
vowels_dir = top_dir / 'Vowels'
consonants_dir = top_dir / 'Consonants'
os.makedirs(vowels_dir)
os.makedirs(consonants_dir)

# Create the files for each letter
with open('dictionary.txt') as f:
for letter in ascii_uppercase:
# Read the first 10 words starting with the letter
count = 0
# Write the words to the file
letter_dir = vowels_dir if letter in 'AEIOUY' else consonants_dir
with open(letter_dir / f'{letter}.txt', 'w') as f2:
for word in f:
if word[0] == letter:
f2.write(word)
count += 1
if count >= 10:
break

if __name__ == '__main__':
main()

Explanation

Explanation of My Solution:

  1. Creating Directories:

    • I use os.makedirs() to create the top directory (First_10_words_per_letter) and its subdirectories (Vowels and Consonants).
  2. Reading the Dictionary File:

    • The program reads from dictionary.txt and processes each letter in the alphabet (ascii_uppercase).
    • For each letter, I decide whether to place the corresponding file in the Vowels or Consonants subdirectory based on whether the letter is a vowel or consonant.
  3. Writing the Words:

    • The program writes the first 10 words starting with the given letter into the corresponding .txt file.
  4. Potential Issue:

    • here is some limitations of this. Say that processing the dictionary on the fly would not be an option if the words in the file were not lexicographically ordered?
      [//]: # ( - One small mistake is that the file handle f for the dictionary.txt file is shared across iterations, but the file is being processed linearly. Once a word is read, it is not reset for the next letter. This will cause issues because the loop keeps reading until the end of the file and will skip words that should be in earlier letters.)

Standard Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os
from pathlib import Path
from string import ascii_uppercase

top_dir = Path('First_10_words_per_letter')
os.mkdir(top_dir)
vowels_dir = top_dir / 'Vowels'
consonants_dir = top_dir / 'Consonants'
os.mkdir(vowels_dir)
os.mkdir(consonants_dir)

with open('dictionary.txt') as dictionary:
for letter in ascii_uppercase:
letter_dir = vowels_dir if letter in 'AEIOUY' else consonants_dir
count = 0
with open(letter_dir / f'{letter}.txt', 'w') as filename:
for word in dictionary:
if word[0] != letter:
continue
if count >= 10:
break
print(word, file=filename, end='')
count += 1
  • Python
  • 9021
  • TUT

扫一扫,分享到微信

微信分享二维码
9021_TUT_8
Horse Racing-Inter-Uni Programming Contest
目录
  1. 1. Exercise 1
    1. 1.0.1. Problem Description
    2. 1.0.2. My Solution
    3. 1.0.3. Standard Solution
    4. 1.0.4. Explanation
  • 2. Exercise 2
    1. 2.0.1. Problem Description
    2. 2.0.2. Standard Solution
  • 3. Exercise 3
    1. 3.0.1. Problem Description
    2. 3.0.2. My Solution
    3. 3.0.3. Explanation
    4. 3.0.4. Standard Solution
  • 4. Exercise 4
    1. 4.0.1. My Solution
    2. 4.0.2. Standard Solution
    3. 4.0.3. Explanation
  • 5. Exercise 5
    1. 5.0.1. Normal dictionary:
    2. 5.0.2. defaultdict:
    3. 5.0.3. Counter:
    4. 5.0.4. Problem Description
    5. 5.0.5. My Solution
    6. 5.0.6. Standard Solution
    7. 5.0.7. Additional Solution
    8. 5.0.8. Additional Additional Solution (Data Analysis) (NOT Mandatory)
    9. 5.0.9. Explanation
      1. 5.0.9.1. Reading the CSV file:
      2. 5.0.9.2. Counting the number of customers per country:
  • 6. Exercise 6
    1. 6.0.1. Problem Description
    2. 6.0.2. My Solution(Not Perfect, it relies on the sort of dictionary.txt )
    3. 6.0.3. Explanation
    4. 6.0.4. Standard Solution

  • 150 篇 | 131.7k
    次 | 人
    这里自动载入天数这里自动载入时分秒
    2022-2025 loong loong | 新南威尔士龙龙号