Python Forum
Sorting ID with first and last name Arrays
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting ID with first and last name Arrays
#1
my question here
I have an assignment where I am having an issue. I am to generate random numbers from 10 - 99. Then take an array list of first and last name  and display the Unique ID first and last name in descending order.
ex: 18 Anna Zenoff         
      12 Annamma Shultz
      2 Debby Rahman

should display:
      2 Debby Rahman
      12 Annamma Shultz
      18 Anna Zenoff         
I am not sure how to merge the two into one list display just first and last name
any help will be gladly appreciated.

firstName=['Anna','Annamma','Debby','Jim','Kenneth','Lusan','Maggie','Manny','Michael','Norma','Paige','Patti','Teresa','Tobi','Tom','Val']
lastName=['Zenoff','Shultz','Rahman','Hooper','Black','Zenoff','Perdue','Ryan','Franco','Ayala','Braun','Rahman','Kuawata','Bombino','Ulch','Umeda']

# Input: get values
listSize = len(firstName)
numberId = [0] * listSize
min2max = [0] * listSize
mergedList= [0] * listSize


# generate list of unique, random IDs
for index in range(listSize):
    numberId[index] = random.randint(10,99)
     
# Processing: carry out calculations
for index in range(listSize):
    min2max[index] = numberId[index]
count = listSize
flag = 0
while flag == 0:
    flag = 1
    k = 0
    while k<=(count - 2):
        if min2max[k] > min2max[k+1]:
            temp = min2max[k]
            min2max[k] = min2max[k+1]
            min2max[k+1] = temp
            flag = 0 
        k = k + 1
print(min2max[index]
#only prints one random number doesn't display 16 of them
Reply
#2
I don't know what min2max list was but hopefully it wasn't important ^_^. Maybe I'm starting to get sleepy.
for a random_id you could put a for loop that will put a random int for every name in firstname list. 
I put a counter 

list_size = len(firstName)
random_id = [random.randint(10,99) for x in range(list_size)]
student_data =[]
counter = 0
Then all you need is another loop and to append data to a list. 
using the counter and format function you can get your desired result

 student_data.append("{} {} {} ".format(random_id[counter],firstName[counter],lastName[counter]))
 counter += 1
My results:
12 Debby Rahman 
15 Tom Ulch 
20 Tobi Bombino 
29 Annamma Shultz 
30 Manny Ryan 
30 Patti Rahman 
48 Anna Zenoff 
48 Kenneth Black 
51 Norma Ayala 
57 Michael Franco 
64 Jim Hooper 
70 Lusan Zenoff 
71 Paige Braun 
73 Teresa Kuawata 
85 Val Umeda 
87 Maggie Perdue
Reply
#3
Well, you will have to follow some steps:

1. instead of using 2 lists (FirstName & LastName) you could just create a dictionary and put Firstnames and Lastnames in it.
example: Names = {'Anna':'Zenoff','Manny':'Ryan'} and then you could create a list, call it Final.

2. After that you could iterate trough the Dictionary by key & value.
in python 2.x you can do this as shown below:
for key, value in myDict.iteritems():
and in python 3.x
for key, value in myDict.items():
3. While iterating over the Dictionary, generate a random value from 10,99 and append all 3 (random, firstname, lastname) into the list that you have created, in this example it's called Final. And an easy way to do this is to use .format method
Final.append("{} {} {}".format(randint(10, 99), key, value))
now this will add each student into that list including their (randomly)selected IDs

4. last step is to sort Final by using 2 first characters, remember out list is made up of STRINGSand not integers so we have to tell the computer to choose two first characters in each list item and convert it to INTEGER before trying to sort the list.
To do this you can use sorted() function:
sorted(Final, key=lambda x: int(x[:2]))

Final is the listname that we want to sort.
xis each list item.
int(x[:2]) selects two first characters from the string, which are numbers/IDs and converting them to INTEGER values.

5. Make sure that you place sorted function in a new list newList = sorted( ... ) so that we can use it to print the sorted items.
for i in newList:
   print ''.join(i)
Reply
#4
(Apr-23-2017, 12:32 PM)idontreallywolf Wrote: Well, you will have to follow some steps:

1. instead of using 2 lists (FirstName & LastName) you could just create a dictionary and put Firstnames and Lastnames in it.
example: Names = {'Anna':'Zenoff','Manny':'Ryan'} and then you could create a list, call it Final.

And if the first name shows more than once in the first list? We have a beautiful zip for meshing lists
for first_name, last_name in zip(fristName, lastName):
I am not sure if 2 lists were a given - or it's OPs idea, but using dict the way you suggested here is definitely wrong
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#5
(Apr-23-2017, 07:06 PM)volcano63 Wrote:
(Apr-23-2017, 12:32 PM)idontreallywolf Wrote: Well, you will have to follow some steps:

1. instead of using 2 lists (FirstName & LastName) you could just create a dictionary and put Firstnames and Lastnames in it.
example: Names = {'Anna':'Zenoff','Manny':'Ryan'} and then you could create a list, call it Final.

And if the first name shows more than once in the first list? We have a beautiful zip for meshing lists
for first_name, last_name in zip(fristName, lastName):
I am not sure if 2 lists were a given - or it's OPs idea, but using dict the way you suggested here is definitely wrong

Well, then educate me brother. Why is using dict wrong? - in this case.
Reply
#6
(Apr-23-2017, 08:29 PM)idontreallywolf Wrote:
(Apr-23-2017, 07:06 PM)volcano63 Wrote: And if the first name shows more than once in the first list? We have a beautiful zip for meshing lists
for first_name, last_name in zip(fristName, lastName):
I am not sure if 2 lists were a given - or it's OPs idea, but using dict the way you suggested here is definitely wrong

Well, then educate me brother. Why is using dict wrong? - in this case.
I usually try to be polite - but since I'm a brother, let me treat you like a family Evil

You gave a useless advice, that adds nothing to the solution.

  1. For starters, dict has unique keys - thus my hint about more than once, which you missed.
  2. Suggesting manually writing dictionary instead of two lists has no merit  Wall - OP could have written full name from the start.
  3. You cant apply intto list slice - and why are you creating a list of strings if you want to sort it by integer component?
You suggested "solution" is a mess - so litter box is suggested Naughty
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#7
Well, zip() was mentioned.
What this function is doing is the to return tuples containing the n-th element of each iterable passed as an argument. It stops when the end of the shortest one is reached.

In [8]: n = [10, 9, 8]

In [1]: s = ['ten', 'nine', 'eight']

In [2]: pfff = ['10', '9', '8']

In [3]: from pprint import pprint

In [4]: pprint(zip(n, s, pfff)) # In Python 3 zip() returns an iterator.
<zip object at 0x7fc223d16408>

In [5]: pprint(list(zip(n, s, pfff)))
[(10, 'ten', '10'), (9, 'nine', '9'), (8, 'eight', '8')]
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#8
Just a little remark: repeatedly calling randint is not a good way to create unique ID's (you need to be quite lucky to not have duplicities if you roll sixteen times integer between 10 and 99). random.sample() is better suited for such task:
unique_id = random.sample(range(10,100), len(firstName))
Reply
#9
if you convert your lists to sets, then you can use:
  • subset - returns true if list1 is a subset of list2
  • superset - list1 is superset of list2
  • intersection - returns new set containing just the shared items
    between lists
  • Union - merge lists without duplication
Reply
#10
import uuid

print(str(uuid.uuid4())[9:13])
Output:
ca6d
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Forum Jump:

User Panel Messages

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