To Lecture Notes

Extract Methods Practice Problems

Zipfile with Problems: extract-methods.zip
Zipfile with Problems and Answers: extract-methods-ans.zip

  1. Method Name: convert_in_to_cm
    Action: Convert inches to centimeters:
    inches = float(input("Enter length in inches: "))
    cm = inches * 2.54
    print("Length in cm is:", cm)
    
  2. Method Name: convert_ft_in_to_m
    Action: Convert feet and inches to meters:
    feet = float(input("Enter length in feet: "))
    inches = float(input("Enter additional inches: "))
    cm = (feet * 12 + inches) * 2.54
    meters = cm / 100
    print("Length in meters is:", meters)
    
  3. Method Name: first_character
    Action: Return first character of a string.
    word = input("Input word: ")
    if len(word) > 0:
       first = word[0]
    else:
       first = ""
    print("First character:", first)
    
  4. Method Name: find_factors
    Action: Return list of all factors of an int:
    n = int(input("Input a positive int: "))
    factors = [1]
    for f in range(2, n):
        if n % f == 0:
            factors.append(f)
            
    factors.append(n)
    print("Factors of n:", factors)
    
  5. Method Name: load_list1
    Input File: values1.txt
    Action: Return list consisting of int values read from a file, one values per line:
    file_name = input("Input file name:")
    fin = open(file_name, "r")
    values = [ ]
    for line in fin:
        value = int(line)
        values.append(value)
        
    print("List of values: ", values)
    
  6. Method Name: load_list_of_lists
    Input File: values2.txt
    Action: Return list of lists consisting of int values read from a file, multiple values per line:
    file_name = input("Input file name: ")
    fin = open(file_name, "r")
    values = [ ]
    for line in fin:
        row = [ ]
        items = line.split(" ")
        for item in items:
            value = int(item.strip( ))
            row.append(value)
        values.append(row)
    fin.close( )
    
    print("List of values: ", values)