Soldier Serial Number Generator

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to implement a Weapon Factory class that generates unique IDs for clone soldiers in the Galactic Empire's clone factory. The Weapon Factory class is designed as an iterator, allowing you to easily generate and manage a sequence of unique IDs.

👀 Preview

------test1-------
1000face
1000facf
1000fad0
------test2-------
1000f000
1000f001
1000f002
1000f003
1000f004
1000f005
1000f006
1000f007
1000f008
1000f009
1000f00a

🎯 Tasks

In this project, you will learn:

  • How to create a custom iterator class in Python
  • How to generate unique hexadecimal IDs in sequence
  • How to use the iterator class to generate and manage a sequence of IDs

🏆 Achievements

After completing this project, you will be able to:

  • Implement a custom iterator class in Python
  • Generate unique hexadecimal IDs in sequence
  • Use an iterator class to manage a sequence of IDs
  • Enhance the iterator class with additional features, such as ID validation

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/break_continue("`Break and Continue`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/AdvancedTopicsGroup -.-> python/iterators("`Iterators`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/variables_data_types -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/numeric_types -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/type_conversion -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/conditional_statements -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/for_loops -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/break_continue -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/lists -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/tuples -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/function_definition -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/classes_objects -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/constructor -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/polymorphism -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/encapsulation -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/iterators -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/data_collections -.-> lab-302764{{"`Soldier Serial Number Generator`"}} python/build_in_functions -.-> lab-302764{{"`Soldier Serial Number Generator`"}} end

Implement the WeaponFactory Class

In this step, you will learn how to implement the WeaponFactory class as an iterator class.

  1. Open the soldier_generator.py file in your code editor.

  2. Define the WeaponFactory class with the following requirements:

    • The __init__() method should accept a string as an argument. This argument is the starting ID of the weapon factory.
    • The __next__() method should generate the next ID in sequence. The generated ID should be a string of 8 hexadecimal characters.
    • The __iter__() method should return the WeaponFactory instance itself, so that the class can be used as an iterator.

Here's the code for the WeaponFactory class:

class WeaponFactory:
    def __init__(self, start_id):
        self.current_id = int(start_id, 16)

    def __iter__(self):
        return self

    def __next__(self):
        hex_id = hex(self.current_id)[2:]
        self.current_id += 1
        return hex_id.zfill(8)

In the __init__() method, we initialize the current_id attribute by converting the start_id string to an integer using the int() function with a base of 16 (hexadecimal).

In the __next__() method, we generate the next ID by converting the current_id to a hexadecimal string using the hex() function, and then removing the leading '0x' using slicing [2:]. We then increment the current_id by 1. Finally, we use the zfill() method to ensure that the ID string is always 8 characters long, padded with leading zeros if necessary.

The __iter__() method simply returns the WeaponFactory instance itself, so that the class can be used as an iterator.

Test the WeaponFactory Class

Now that you've implemented the WeaponFactory class, let's test it to make sure it's working as expected.

  1. Add the following code to the if __name__ == "__main__": block in the soldier_generator.py file:
wf = WeaponFactory("1000face")
print("------test1-------")
print(next(wf))   ## Output: '1000face'
print(next(wf))   ## Output: '1000facf'
print(next(wf))   ## Output: '1000fad0'

count = 0
max_count = 10
print("------test2-------")
for id in WeaponFactory("1000f000"):
    print(id)
    count += 1
    if count > max_count:
        break
  1. Save the soldier_generator.py file and run the script:
python3 soldier_generator.py

The output should be:

------test1-------
1000face
1000facf
1000fad0
------test2-------
1000f000
1000f001
1000f002
1000f003
1000f004
1000f005
1000f006
1000f007
1000f008
1000f009
1000f00a

This confirms that the WeaponFactory class is working as expected, generating the next ID in sequence when the __next__() method is called, and iterating over the IDs when used as an iterator.

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like