Python Programming Exercises: Collections and Dictionaries

String Deduplication and Sorting

Simple code to remove duplicate characters from a string and sort the characters:

input_string = input()
unique_chars = list(set(input_string))
unique_chars.sort()
result = ''.join(unique_chars)
print(result)

List Deduplication

Removes duplicate names from a comma-separated list while preserving order:

name_input = input()
name_list = name_input.split(',')
result = []
for name in name_list:
    if name not in result:
        result.append(name)
print(result)

Age Guessing Puzzle

Finds the age of a mathematician based on constraints about its cube and 4th power containing all digits 0-9 exactly once:

for age in range(11, 23):
    cube = age ** 3
    fourth = age ** 4
    cube_digits = [cube // 1000, (cube % 1000) // 100, (cube % 100) // 10, cube % 10]
    fourth_digits = [fourth // 100000, (fourth % 100000) // 10000, (fourth % 10000) // 1000,
                     (fourth % 1000) // 100, (fourth % 100) // 10, fourth % 10]
    all_digits = cube_digits + fourth_digits
    if len(set(all_digits)) == 10 and fourth > 100000:
        print(age)
        break

Set Operatiosn

Implements various set operations based on user input:

n = int(input())
locations = input().split()
my_set = set(locations)

for _ in range(n):
    operation, *params = input().split()
    if operation == 'print':
        print(sorted(list(my_set)))
    elif operation == 'update':
        my_set.update(params)
    elif operation == 'add':
        my_set.add(params[0])
    elif operation == 'del':
        my_set.discard(params[0])
    elif operation == 'clear':
        my_set.clear()

Average Calculation with Sets

Calculates average height using unique values:

def calculate_average(heights):
    unique_heights = set(heights)
    return f"{sum(unique_heights)/len(unique_heights):.3f}"

if __name__ == '__main__':
    plant_heights = list(map(int, input().split()))
    result = calculate_average(plant_heights)
    print(result)

Mobile Sales Analysis

Analyzes mobile phone sales data for different years:

with open('step7/sale2019.csv', 'r', encoding='utf-8') as file_2019:
    sales_2019 = [line.strip().split(',') for line in file_2019]
with open('step7/sale2018.csv', 'r', encoding='utf-8') as file_2018:
    sales_2018 = [line.strip().split(',') for line in file_2018]

set_2019 = set(item[0] for item in sales_2019)
set_2018 = set(item[0] for item in sales_2018)

selection = input()
if selection == '1':
    print(sorted(set_2019), sorted(set_2018), sep='\n')
elif selection == '2':
    print(sorted(set_2019 & set_2018))
elif selection == '3':
    print(sorted(set_2019 | set_2018))
elif selection == '4':
    print(sorted(set_2019 - set_2018))
elif selection == '5':
    print(sorted(set_2019 ^ set_2018))

Country Counting

Counts unique countries in a stamp collection:

total_stamps = int(input())
countries = set()
for _ in range(total_stamps):
    country = input().strip()
    countries.add(country)
print(len(countries))

Dictionary List Sorting

Sorts a list of dictionaries by age or name:

n = int(input())
people = []
for _ in range(n):
    name, age = input().split()
    people.append({"name": name, "age": int(age)})

people.sort(key=lambda x: x['age'])
print(people)

people.sort(key=lambda x: x['name'])
print(people)

GPA Calculation

Calculates grade point average:

grade_points = {
    'A': 4.0, 'A-': 3.7, 'B+': 3.3, 'B': 3.0, 'B-': 2.7,
    'C+': 2.3, 'C': 2.0, 'C-': 1.5, 'D': 1.3, 'D-': 1.0, 'F': 0
}

total_points = 0
total_credits = 0

while True:
    grade = input()
    if grade == '-1':
        break
    credit = int(input())
    total_points += grade_points[grade] * credit
    total_credits += credit

print(f"{total_points/total_credits:.2f}")

Contact Book (Modification)

Modifies contact information in a dictionary:

contact_book = {
    'Zhang Ziqiang': ['12652141777', 'Materials'],
    'Geng Tongshuo': ['14388240417', 'Automation'],
    'Wang Yan': ['11277291473', 'Arts']
}

print(contact_book)
MENU = '''\nWelcome to the PYTHON contact book
1: Add contact
2: Delete contact
3: Modify contact information
4: Search contact
5: Display all contacts
6: Exit and save'''

print(MENU)
selection = int(input())

if selection == 3:
    name = input()
    if name in contact_book:
        contact_book[name] = [input(), input()]
        print("Success")
    else:
        print("No Record")
    print(contact_book)
else:
    print("ERROR")

Dictionary Element Addition

Adds elements to a dictionary if they don't already exist:

contact_list = {
    'Zhao Xiaoming': '13299887777',
    'Te Minglang': '814666888',
    'Pushi Jing': '522888666',
    'Wu Xiaojing': '13999887777'
}

new_name = input()
new_number = input()

if new_name not in contact_list:
    contact_list[new_name] = new_number
    for name, number in contact_list.items():
        print(f"{name}:{number}")
else:
    print("This name already exists in the contact book")

Dictionary Operations

Performs various dictionary operations:

n = int(input())
names = input().split(',')
numbers = input().split(',')

contact_book = dict(zip(names, numbers))

for _ in range(n):
    parts = input().split()
    operation = parts[0]
    
    if operation == 'key':
        print(list(contact_book.keys()))
    elif operation == 'value':
        print(list(contact_book.values()))
    elif operation == 'print':
        print(contact_book)
    elif operation == 'clear':
        contact_book.clear()
    elif operation == 'add':
        contact_book[parts[1]] = parts[2]
    elif operation == 'update':
        contact_book.update({parts[1]: parts[2]})
    elif operation == 'del':
        if parts[1] in contact_book:
            del contact_book[parts[1]]
        else:
            print('Key not found')

Capital City Lookup

Looks up capital cities for Chinese provinces:

capitals = {
    'Hunan': 'Changsha', 'Hubei': 'Wuhan', 'Guangdong': 'Guangzhou',
    'Guangxi': 'Nanning', 'Hebei': 'Shijiazhuang', 'Henan': 'Zhengzhou',
    # ... (other provinces)
    'Hong Kong': 'Hong Kong', 'Macao': 'Macao'
}

while True:
    province = input()
    if not province:
        break
    if province in capitals:
        print(capitals[province])
    else:
        print('Input error')

English-Chinese Dictionary

Translates English text to Chinese:

def load_dictionary(filename):
    dictionary = {}
    with open(filename, 'r', encoding='utf-8') as file:
        for line in file:
            line = line.replace('survive,', 'survive ')
            word, translation = line.strip().split(maxsplit=1)
            dictionary[word.lower()] = translation
    return dictionary

def tokenize_sentence(sentence):
    sentence = sentence.replace("n't", ' not').replace("'s", ' is')
    for char in '!"#$%&()*+,-./:;<=>?@[\$$^_`{|}~':
        sentence = sentence.replace(char, ' ')
    return sentence.split()

def translate(sentence, dictionary):
    words = tokenize_sentence(sentence)
    for word in words:
        print(word, dictionary.get(word.lower(), 'Guess'))

if __name__ == '__main__':
    user_input = input()
    dictionary = load_dictionary('dicts.txt')
    translate(user_input, dictionary)

Contact Book (Addition)

Adds contacts to a dictionary:

contact_book = {
    'Zhang Ziqiang': ['12652141777', 'Materials'],
    'Geng Tongshuo': ['14388240417', 'Automation'],
    'Wang Yan': ['11277291473', 'Arts']
}

print(contact_book)

MENU = '''\nWelcome to the PYTHON contact book
1: Add contact
2: Delete contact
3: Modify contact information
4: Search contact
5: Display all contacts
6: Exit and save'''

print(MENU)
selection = int(input())

if selection == 1:
    name = input()
    if name in contact_book:
        print('Fail')
    else:
        phone = input()
        department = input()
        contact_book[name] = [phone, department]
        print('Success')
    print(contact_book)
else:
    print('ERROR')

Tags: python Sets Dictionaries Data Processing Sorting

Posted on Wed, 14 Oct 2026 16:18:39 +0000 by sockit2em