list,python-2.7,sorting , Sort List of Numbers according to Custom Number Sequence

Sort List of Numbers according to Custom Number Sequence


Tag: list,python-2.7,sorting

Question :
A set of numbers will be passed as input. Also the redefined relationship of the digits 0-9 in ascending order will be passed as input. Based on the redefined relationship, the set of numbers must be listed in ascending order.

Input Format:
The first line will contain the the set of numbers. The next line will contain the digits 0-9 in the redefined ascending order.

Boundary Conditions:
The size of the set of numbers will be from 2 to 100.

Output Format:
The set of numbers in ascending order as per the redefined order of digits separated by a space.

Example Input/Output 1:


20 50 11 121


50 11 20 121


121 is a three digit number and hence comes first.
As per the redefined order 2 > 1 > 5.
So 121 is greater than all others and comes in the end.
20 > 11 > 50 and hence in ascending order this is reversed.

Example Input/Output 2:


319 311 198 420


319 311 420 198


As per the redefined order 1 > 4 > 3
Among  319 and 311, 1 > 9
Hence the final ascending order is 319 311 420 198

My Solution :

if __name__ == '__main__':
    list_ = raw_input().split()
    num = str(raw_input())
    output = sorted(list_, key = num.index)
    print(' '.join(output))

I need to know how to do multiple levels of sorting such that it compares indexes of first character, then second character & so on...


This matches your input/output examples, but I had to use descending numbers to get the example answers. Are you sure your explanation is correct? If not, just use 0123456789 instead of 9876543210 in the code below.

The algorithm is to provide a sorting key based on translating the digits of the number into their corresponding rank digits:

import string

def xsort(L,xlat):
    def xform(s):
        return int(str(s).translate(string.maketrans(xlat,'9876543210')))
    return sorted(L,key=xform)

print xsort([20,50,11,121],'9231476058')
print xsort([319,311,198,420],'1948327605')


[50, 11, 20, 121]
[319, 311, 420, 198]

References: str.translate, string.maketrans


Count function counting only last line of my list

Count function counting only last line of my list N = int(raw_input()) cnt = [] for i in range(N): string = raw_input() for j in range(1,len(string)): if string[j] =='K': cnt.append('R') elif string[j] =='R': cnt.append('R') if string[0] == 'k': cnt.append('k') elif string[0] == 'R': cnt.append('R') print cnt.count('R') if I am giving...

represent an index inside a list as x,y in python

I have a list which contains 1000 integers. The 1000 integers represent 20X50 elements of dimensional array which I read from a file into the list. I need to walk through the list with an indicator in order to find close elements to each other. I want that my indicator...

Java Get and then remove from a list

In my code i have a list of instances of a class. And i want to get a attribute of 1 instance which is ArrayList. In this class i have implement getters and setters. So I call listofinstances.get(i).getArrayList().remove(0); in order to remove the 1st item of this list. Is this...

List of tuples from (a, all b) to (b, all a)

I am starting with a list of tuples (a,all b). I want to end with a list of tuples (b,all a). For example: FROM (a1,[b1,b2,b3]) (a2,[b2]) (a3,[b1,b2]) TO (b1,[a1,a3]) (b2[a1,a2,a3]) (b3,[a1] How do I do this using Python 2? Thank you for your help....

Parse text from a .txt file using csv module

I have an email that comes in everyday and the format of the email is always the same except some of the data is different. I wrote a VBA Macro that exports the email to a text file. Now that it is a text file I want to parse the...

Pass function call as a function argument

Code: def function1(a,b): return a-1,b-1 def function2(c,d): return c+1,d+1 print function1(function2(1,2)) Error: Traceback (most recent call last): File "C:\Users\sony\Desktop\Python\scripts\", line 6, in <module> print function1(function2(1,2)) TypeError: function1() takes exactly 2 arguments (1 given) [Finished in 0.1s with exit code 1] Why the above error? ...

Use NamedTemporaryFile to read from stdout via subprocess on Linux

import subprocess import tempfile fd = tempfile.NamedTemporaryFile() print(fd) print( p = subprocess.Popen("date", stdout=fd).communicate() print(p[0]) fd.close() This returns: <open file '<fdopen>', mode 'w' at 0x7fc27eb1e810> /tmp/tmp8kX9C1 None Instead, I would like it to return something like: Tue Jun 23 10:23:15 CEST 2015 I tried adding mode="w", as well as delete=False, but...

how to fetch a column in browse_record_list in orm browse method in openERP

I'm beginner in openERP. I'm trying to get a column in a table. While using ORM browse method and iterating that object i got the result in browse_record_list as browse_record(,21). I want to fetch that particular id 21 alone through that browse method but instead im getting same browse_record as...

Stopping list selection in Python 2.7

Imagine that I have an order list of tuples: s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] Given a parameter X, I want to select all the tuples that have a first element equal or greater than X up to but not including the first tuple that has...

Can I put StreamReaders in a list? Or any other way to read a lot of text files at once?

I have a lot of text files and want to read them all by once, how do I do this? This is my code till now: List<StreamReader> lijst = new List<StreamReader>(); using (StreamReader qwe = new StreamReader("C:\\123.txt")) using (StreamReader qwer = new StreamReader("C:\\1234.txt")) lijst.Add(qwe); lijst.Add(qwer); But I get an ObjectDisposedException(Cannot...

How can I resolve my variable's unexpected output?

I have a variable in django named optional_message. If I debug the variable then it says Swenskt but when I try to print the variable on my page the following comes out: (u'Swenskt',) and the variable can't be tested for its length etc. What should I do if I only...

Is there a way to say for every x values, do this?

Before I start, I am new to Python, so any low-level description would be incredibly helpful! I have a list of lets say 60 values (representing one hour, from 8:00-9:00) and I want to run average, maximums, minimums, and standard deviation for each set of 15. (I already have the...

Pandas Dataframe Complex Calculation

I have the following dataframe,df: Year totalPubs ActualCitations 0 1994 71 191.002034 1 1995 77 2763.911781 2 1996 69 2022.374474 3 1997 78 3393.094951 I want to write code that would do the following: Citations of currentyear / Sum of totalPubs of the two previous years I want something to...

Python 2.7 “list index out of range”

I keep getting "IndexError: list index out of range", the code does fine with things like "s = 'miruxsexxzlbveznyaidekl'" but this particular length makes it throw an error. Can anyone help me understand what I did wrong here, not just give me the answer? (I'd like to not have to...

How to check for multiple attributes in a list

I am making a TBRPG game using Python 2.7, and i'm currently making a quest system. I wanted to make a function that checks all of the quests in a list, in this case (quests), and tells you if any of of the quests in the list have the same...

join two different list by id into one list

I've got two different list of two different objects. Then i got one list of a viewmodel that contains properties from both the objects and i want them to be joined into that list. //Product public string id { get; set; } public string unitMeasurement { get; set; } public...

Parsing Google Custom Search API for Elasticsearch Documents

After retrieving results from the Google Custom Search API and writing it to JSON, I want to parse that JSON to make valid Elasticsearch documents. You can configure a parent - child relationship for nested results. However, this relationship seems to not be inferred by the data structure itself. I've...

Python Popen - wait vs communicate vs CalledProcessError

Continuing from my previous question I see that to get the error code of a process I spawned via Popen in python I have to call either wait() or communicate() (which can be used to access the Popen stdout and stderr attributes): app7z = '/path/to/7z.exe' command = [app7z, 'a', dstFile.temp,...

Sort when values are None or empty strings python

I have a list with dictionaries in which I sort them on different values. I'm doing it with these lines of code: def orderBy(self, col, dir, objlist): if dir == 'asc': sorted_objects = sorted(objlist, key=lambda k: k[col]) else: sorted_objects = sorted(objlist, key=lambda k: k[col], reverse=True) return sorted_objects Now the problem...

Update list of items in c#

I would like to know if you can suggest me an efficient way to update a list of items in c#. Here is a generic example: If CurrentList is [ {Id: 154, Name: "George", Salary: 10 000} {Id: 233, Name: "Alice", Salary: 10 000}] And NewList is [ {Id: 154,...

Reduction of list dimensions in Python

I'm trying to assign classes to a list of nodes, and separate all nodes into separate lists based on class tag. For example, if we have the following code: #define number of classes MaxC=5 index=[4 4 5 1 4 1 4 5 4 4 3 1 3 3 1 1]...

How do I read this list and parse it?

I'm using requests and the output I get from the sites API is a list, I've been stuck trying to parse it to get the data from it. I use r = requests.get(urlas, params=params) r.json() to get the data I want. Here is a snippet of the list [{'relation_type': None,...

Anaconda site-packages

After installing a package in an anaconda environment, I'll like to make some changes to the code in that package. Where can I find the site-packages directory containing the installed packages? I do not find a directory /Users/username/anaconda/lib/python2.7/site-packages...

group indices of list in list of lists

I am looking for an elegant solution for the following problem. I have a list of ints and I want to create a list of lists where the indices with the same value are grouped together in the order of the occurrences of said list. [2, 0, 1, 1, 3,...

Python split by comma delimiter and strip

I am trying to open a file in python in read mode then write striped and split data to an output file. I am unsure how to split and strip the same data. Do I need to create a different line? Do I need to write the data out first?...

Implementing a dictionary function to calculate the average of a list

As always, I've attempted this for awhile before I proceed to ask a question on here. I know there are several attempts at answering this, but none really worked for what I needed. Here are the instructions: Implement the following three functions (you should use an appropriate looping construct to...

Slicing a Python OrderedDict

In my code I frequently need to take a subset range of keys+values from a Python OrderedDict (from collections package). Slicing doesn't work (throws TypeError: unhashable type) and the alternative, iterating, is cumbersome: from collections import OrderedDict o = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) # want to...

Why does `for lst in lst:` work? [duplicate]

This question already has an answer here: Why can I use the same name for iterator and sequence in a Python for loop? 6 answers The following code lst = ['foo', 'bar', 'baz'] for lst in lst: print lst gives me this output foo bar baz I would expect...

PySerial client unable to write data

I'm trying to write a python program which can communicate over a serial interface using PySerial module as follows: import serial if __name__ == '__main__': port = "/dev/tnt0" ser = serial.Serial(port, 38400) print print ser.isOpen() x = ser.write('hello') ser.close() print "Done!" But if I execute the above I get...

How do I copy a row from one pandas dataframe to another pandas dataframe?

I have a dataframe of data that I am trying to append to another dataframe. I have tried various ways with .append() and there has been no successful way. When I print the data from iterrows. I provide 2 possible ways I tried to solve the issue below, one creates...

from x(defined in program) import y(defined in program) python

I need some assitance since I really have no idea how I can fix this: x="test" y="test2" When I try to import y from x , it says that there is no file with the name "x" (from x import y) Is there any way to import test2 from test...

How to extract efficientely content from an xml with python?

I have the following xml: <?xml version="1.0" encoding="UTF-8" standalone="no"?><author id="user23"> <document><![CDATA["@username: That boner came at the wrong time ????" HELP I'M DYING ]]></document> <document><![CDATA[Ugh ]]></document> <document><![CDATA[YES !!!! WE GO FOR IT. ]]></document> <document><![CDATA[@username Shout out to me???? ]]></document> </author> What is the most efficient...

python - how to properly evaluate a value from a system command

I'm just learning python (using 2.7.8) and i'm trying to figure out what is the best way to evaluate the output of a system command. I've read to use subprocess. For example, I need to run this IF statment and evaluate for anything > 0, then process it. Example of...

Why cant I refer to a random index in my 4D list, while I know it exists?

I got a 4D list, and I want where I want to display only the [k][3][j][z], but this isnt working. I checked all the counts and they are all 5+, so 3[4] should work... for (int k = 0; k < lijst4D.Count; k++) { for (int i = 0; i...

How to remove structure with python from this case?
How to remove "table" from HTML using python? I had case like this: paragraph = ''' <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem molestiae consequuntur officiis corporis sint.<br /><br /> <table> <tr> <td> text title </td> <td> text title 2 </td> </tr> </table> <p> lorem ipsum</p> ''' how...

How can I iterate through nested HTML lists without returning the “youngest” children?

Fiddle: I want to iterate through an HTML nested list that is 3-layers deep. <ul> <li>animals <ul> <li>birds <ul> <li>crow</li> <li>parrot</li> </ul> </li> <li>reptiles</li> </ul> </li> <li>plants</li> <li>bugs</li> </ul> I want it to iterate through the list so that it returns the elements in this order (note, this isn't...

Strange Behavior: Floating Point Error after Appending to List

I am writing a simple function to step through a range with floating step size. To keep the output neat, I wrote a function, correct, that corrects the floating point error that is common after an arithmetic operation. That is to say: correct(0.3999999999) outputs 0.4, correct(0.1000000001) outputs 0.1, etc. Here's...

What is the difference between <> and == in python?

In [142]: (MON,TUE,WED,THR,FRI,SAT,SUN)<>range(7) Out[142]: True In [143]: (MON,TUE,WED,THR,FRI,SAT,SUN)==range(7) Out[143]: False ...

I need to make sure that only certain characters are in a list?

I have this to get input and put it in a list: def start(): move_order=[raw_input("Enter your moves: ").split()] And I only want the characters A, D, S, C, H (it's for a game >_>) to be allowed. I've tried using the regular expressions stuff: if re.match('[ADSCH]+', [move_order]) is False: print...

why java API prevents us to call add and remove together?

As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

Python regular expression, matching the last word

I've the following problem. I'm looking to find all words in a string that typically looks like so HelloWorldToYou Notice, each word is capitalized as a start followed by the next word and so on. I'm looking to create a list of words from it. So the final expected output...

multiple iteration of the same list

I have one list of data as follows: from shapely.geometry import box data = [box(1,2,3,4), box(4,5,6,7), box(1,2,3,4)] sublists = [A,B,C] The list 'data' has following sub-lists: A = box(1,2,3,4) B = box(4,5,6,7) C = box(1,2,3,4) I have to check if sub-lists intersect. If intersect they should put in one tuple;...

Get element starting with letter from List

I have a list and I want to get the position of the string which starts with specific letter. I am trying this code, but it isn't working. List<String> sp = Arrays.asList(splited); int i2 = sp.indexOf("^w.*$"); ...

ZipList with Scalaz

Suppose I have a list of numbers and list of functions to apply to numbers: val xs: List[Int] = List(1, 2, 3) val fs: List[Int => Int] = List(f1, f2, f3) Now I would like to use an Applicative to apply f1 to 1, f2 to 2, etc. val ys:...

Operand order in Scala List.prepend (::)

Odersky has brilliantly optimized Java syntax, enabling object calls without dots and parenthesis. I.e. instead of list.prepend(item), you now simply write list :: item, which also turns language operators into simple object methods. Here, List defines :: (prepend) operator. However, you normally write it vice-verse in Scala, using item ::...

Python initialize strings as variable

I have a calculation schema as string calc = "((k+m+46)/2)" and some strings containing variable like m = 2 k = m*2 all only strings. Now I want to initialize them into Python. my goal is it to calculate with the calculating schema the varible values. calc should return 26...

Identify that a string could be a datetime object

If I knew the format in which a string represents date-time information, then I can easily use datetime.datetime.strptime(s, fmt). However, without knowing the format of the string beforehand, would it be possible to determine whether a given string contains something that could be parsed as a datetime object with the...