Python Forum
Help with list sorting
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with list sorting
#1
Can someone help with my assignment. I have most of the code written theres just a few errors I need help with.
the text file and assignment: https://transfernow.net/49ffh2n6pjez

The code:
with open('cities.txt','r', encoding = 'cp1252') as fin: # opens file with read permission
  
    import math
  
    season = input('Will you take your vacation during summer or winter? ')
    climate = input('Do you want to go to a warm or a cold place? ')
  
    coldsummer = [] # these are empty lists that will be filled in later
    warmsummer = []
    coldwinter = []
    warmwinter = []
          
    data = fin.read().splitlines(True)
      
    for line in data[1:-1]: 
        line = line.split('\t') # splits elements in line with a tab
  
        lat = line[0] # these assign variables to certain parts of the file
        long = line[1]
        city = line[2]
            
        lat_deg = int(lat[0:2].strip('°').strip('N').strip('S')) # strips non integer parts
        lat_min = int(lat[3:5].strip('°').strip('N').strip('S'))
        long_deg = int(long[0:2].strip('°').strip('E').strip('W'))
        long_min = int(long[3:5].strip('°').strip('E').strip('W'))
  
        lat_DMS = lat_deg + (lat_min/60) # converts to degree-minute-second
        lat_rad = lat_DMS*(math.pi/180) # converts to radian
        long_DMS = long_deg + (long_min/60)
        long_rad = long_DMS*(math.pi/180)
  
        R = 6360 # assumed radius of Earth
        Mercedlat_DMS = 37 + 22/60 # coordinate for Merced, CA in degree-minute-second
        Mercedlat_rad = Mercedlat_DMS*(math.pi/180) # in radians
        Mercedlong_DMS = 107 + 25/60
        Mercedlong_rad = Mercedlong_DMS*(math.pi/180)
  
        distance = 2*R*math.sin(math.sqrt(math.sin((lat_rad - Mercedlat_rad)/2)**2 + # distance formula
                                          math.cos(lat_rad)*math.cos(Mercedlat_rad) *
                                          math.sin((long_rad - Mercedlong_rad)/2)**2))**-1
        line.append(distance)
  
        if lat_deg > 66: # these if statements will fill in lists with appropriate values
            coldsummer.append(line)
            coldwinter.append(line)
        elif lat_deg > 35 and lat_deg < 66:
            warmsummer.append(line)
            coldwinter.append(line)
        else:
            warmsummer.append(line)
            warmwinter.append(line)
 
        def sortByDistance(cityStats):
            return cityStats[len(cityStats)-1]
 
        """ The key argument requires a function or method that will act upon each item in the list.
        The function defined above should suffice in this case.
        In effect, list.sort() does this with more finesse:

            length = len(self)
            for i in range(length):
                if key(self[i]) > key(self[i + 1]):
                    swap(self[i], self[i + 1]) """
                    
        coldsummer.sort(key = sortByDistance)
        warmsummer.sort(key = sortByDistance)
        coldwinter.sort(key = sortByDistance)
        warmwinter.sort(key = sortByDistance)
       
        for x in warmsummer: # the for loops will take desired list and print values
            if season == 'summer':
                if climate == 'warm':
                    print(x[2])
        for x in coldsummer:
            if season == 'summer':
                if climate == 'cold':
                    print(x[2])
        for x in warmwinter:
            if season == 'winter':
                if climate == 'warm':
                    print(x[2])
        for x in coldwinter:
            if season == 'winter':
                if climate == 'cold':
                    print(x[2])
Any help would be greatly appreciated. Thank!

(Oct-15-2018, 08:55 PM)gonzo620 Wrote: Can someone help with my assignment. I have most of the code written theres just a few errors I need help with.
the text file and assignment: https://transfernow.net/49ffh2n6pjez

The code:
with open('cities.txt','r', encoding = 'cp1252') as fin: # opens file with read permission
  
    import math
  
    season = input('Will you take your vacation during summer or winter? ')
    climate = input('Do you want to go to a warm or a cold place? ')
  
    coldsummer = [] # these are empty lists that will be filled in later
    warmsummer = []
    coldwinter = []
    warmwinter = []
          
    data = fin.read().splitlines(True)
      
    for line in data[1:-1]: 
        line = line.split('\t') # splits elements in line with a tab
  
        lat = line[0] # these assign variables to certain parts of the file
        long = line[1]
        city = line[2]
            
        lat_deg = int(lat[0:2].strip('°').strip('N').strip('S')) # strips non integer parts
        lat_min = int(lat[3:5].strip('°').strip('N').strip('S'))
        long_deg = int(long[0:2].strip('°').strip('E').strip('W'))
        long_min = int(long[3:5].strip('°').strip('E').strip('W'))
  
        lat_DMS = lat_deg + (lat_min/60) # converts to degree-minute-second
        lat_rad = lat_DMS*(math.pi/180) # converts to radian
        long_DMS = long_deg + (long_min/60)
        long_rad = long_DMS*(math.pi/180)
  
        R = 6360 # assumed radius of Earth
        Mercedlat_DMS = 37 + 22/60 # coordinate for Merced, CA in degree-minute-second
        Mercedlat_rad = Mercedlat_DMS*(math.pi/180) # in radians
        Mercedlong_DMS = 107 + 25/60
        Mercedlong_rad = Mercedlong_DMS*(math.pi/180)
  
        distance = 2*R*math.sin(math.sqrt(math.sin((lat_rad - Mercedlat_rad)/2)**2 + # distance formula
                                          math.cos(lat_rad)*math.cos(Mercedlat_rad) *
                                          math.sin((long_rad - Mercedlong_rad)/2)**2))**-1
        line.append(distance)
  
        if lat_deg > 66: # these if statements will fill in lists with appropriate values
            coldsummer.append(line)
            coldwinter.append(line)
        elif lat_deg > 35 and lat_deg < 66:
            warmsummer.append(line)
            coldwinter.append(line)
        else:
            warmsummer.append(line)
            warmwinter.append(line)
 
        def sortByDistance(cityStats):
            return cityStats[len(cityStats)-1]
 
        """ The key argument requires a function or method that will act upon each item in the list.
        The function defined above should suffice in this case.
        In effect, list.sort() does this with more finesse:

            length = len(self)
            for i in range(length):
                if key(self[i]) > key(self[i + 1]):
                    swap(self[i], self[i + 1]) """
                    
        coldsummer.sort(key = sortByDistance)
        warmsummer.sort(key = sortByDistance)
        coldwinter.sort(key = sortByDistance)
        warmwinter.sort(key = sortByDistance)
       
        for x in warmsummer: # the for loops will take desired list and print values
            if season == 'summer':
                if climate == 'warm':
                    print(x[2])
        for x in coldsummer:
            if season == 'summer':
                if climate == 'cold':
                    print(x[2])
        for x in warmwinter:
            if season == 'winter':
                if climate == 'warm':
                    print(x[2])
        for x in coldwinter:
            if season == 'winter':
                if climate == 'cold':
                    print(x[2])
Any help would be greatly appreciated. Thank!

Mainly the issues are with my sorting
Reply
#2
It would be helpful if you provided sample input data you use, the (incorrect) result you get, and result you want to get.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  sorting a list using unicodes acending order, no loops, no sort(), using recursion lrn2codee 14 6,248 Jun-23-2021, 07:33 PM
Last Post: deanhystad
  Sorting list - Homework assigment ranbarr 1 2,202 May-16-2021, 04:45 PM
Last Post: Yoriz
  Input validation for nested dict and sorting list of tuples ranbarr 3 3,841 May-14-2021, 07:14 AM
Last Post: perfringo
  Question about Sorting a List with Negative and Positive Numbers Than999 2 12,593 Nov-14-2019, 02:44 AM
Last Post: jefsummers
  CODE for Bubble sorting an unsorted list of 5 numbers. SIJAN 1 2,255 Dec-19-2018, 06:22 PM
Last Post: ichabod801
  sorting a deck of cards (objects in a list) itmustbebunnies 1 7,145 Dec-05-2018, 02:44 AM
Last Post: ichabod801
  Sorting list of names by first two characters Otbredbaron 2 3,238 May-24-2018, 03:59 PM
Last Post: Otbredbaron
  Advanced sorting of a built-in list Whisper40 6 4,051 Jan-11-2018, 07:27 PM
Last Post: Whisper40
  Sorting Santa's List of Children sirox84 4 5,094 Feb-20-2017, 06:10 PM
Last Post: sirox84

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020