[Tutor] Finding the largest gap in tuple between two lists.
Hello there everyone i hope you are all doing fantastic. Im currently working on a little program that is designed to do a basic function to help me to trade efficiently within the game Star Citizen: #1 take two inputs ( location and destination ) #2 Find what product is best to buy at location to sell at destination #3 Print the results currently i have figured out how to get python to take the two inputs and provide me with the lowest buy price and highest sell price. However the information i want to produce is what has the largest profit margin possible between the two locations so i need to compare what items are available in both locations and then see what one has the largest price difference then display that items name. Below is the code i have currently made for this. Current_Location = input("Where are you currently located? :").lower() Current_Destination = input("Where are you planning to travel? :").lower() def Find_Lowest_Buy_Olisar(): print("Finding lowest buy price for OLISAR...") print(*Sort_Buying_Olisar[:1], sep='\n') def Find_Highest_Sell_Olisar(): print("Finding highest sell price for OLISAR...") print(*Sort_Selling_Olisar[:1], sep='\n') def Find_Lowest_Buy_Levski(): print("Finding lowest buy price for LEVSKI...") print(*Sort_Buying_Levski[:1], sep='\n') def Find_Highest_Sell_Levski(): print("Finding highest sell price for LEVSKI...") print(*Sort_Selling_Levski[:1], sep='\n') Buying_Olisar = [('Medical Supply', 17.01), ('Waste', 0.005),] Sort_Buying_Olisar = sorted_by_second = sorted(Buying_Olisar, key=lambda tup: tup[1]) Selling_Olisar = [('Agricium', 25.60), ('Aluminum', 1.25), ('Beryl', 4.26), ('Chlorine', 1.57), ('Corundum', 2.53), ('Diamond', 6.90), ('Distilled Spirits', 4.95), ('Fluorine', 2.80), ('Gold', 6.07), ('Hydrogen', 1.02), ('Iodine', 0.41), ('Laranite', 28.91), ('Processed Food', 1.39), ('Quartz', 1.44), ('Scrap', 1.67), ('Stims', 3.40), ('Titanium', 8.27), ('Tungsten', 3.90),] Sort_Selling_Olisar = sorted(Selling_Olisar, key=lambda tup:(-tup[1], tup[0])) Buying_Levski = [('Agricultural Supply', 1.11), ('Aluminum', 1.20), ('Hydrogen', 0.98), ('Iodine', 0.38), ('Quartz', 1.37), ('Waste', 0.005),] Sort_Buying_Levski = sorted_by_second = sorted(Buying_Levski, key=lambda tup: tup[1]) Selling_Levski = [('Agricium', 25.60), ('Altruciatoxine', 11.63), ('Beryl', 4.25), ('Chlorine', 1.56), ('Corundum', 2.53), ('Diamond', 6.07), ('Distilled Spirits', 4.95), ('Fluorine', 2.80), ('Gold', 6.07), ('Laranite', 28.25), ('Medical Supply', 18.00), ('Processed Food', 1.38), ('Scrap', 1.68), ('Stims', 3.40), ('Titanium', 8.27), ('Tungsten', 3.90), ('Widdow', 24.00),] Sort_Selling_Levski = sorted(Selling_Levski, key=lambda tup:(-tup[1], tup[0])) if Current_Location == "olisar": Find_Lowest_Buy_Olisar() elif Current_Location == "levski": Find_Lowest_Buy_Levski() else: print("Unknown location please try again.") if Current_Destination == "olisar": Find_Highest_Sell_Olisar() elif Current_Destination == "levski": Find_Highest_Sell_Levski() else: print("Unknown location please try again.") Any input would be hugely appreciated. Kind regards, Harry O'Neill ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the largest gap in tuple between two lists.
On 11/17/18 6:55 PM, Harry Oneill wrote: > Hello there everyone i hope you are all doing fantastic. > > Im currently working on a little program that is designed to do a basic > function to help me to trade efficiently within the game Star Citizen: > > #1 take two inputs ( location and destination ) > #2 Find what product is best to buy at location to sell at destination > #3 Print the results > > currently i have figured out how to get python to take the two inputs and > provide me with the lowest buy price and highest sell price. > > However the information i want to produce is what has the largest profit > margin possible between the two locations so i need to compare what items are > available in both locations and then see what one has the largest price > difference then display that items name. > > Below is the code i have currently made for this. > > > Any input would be hugely appreciated. > > Kind regards, > > Harry O'Neill Harry, sounds like a fun little project. Thanks for asking it in a way that makes it easy to read! I'll give you a couple of ideas to think about, others may have completely different thoughts. == First off, think about how to represent the data you have. 1. while it is true that the item and the price can be considered a tuple, and then you can put those in a list, any time in Python (and in a number of other programming languages) you have what look like mapping a key to a data value, you should think dictionary - then you access the price by indexing by the goods string. An example of just quickly manipulating what you already have into dictionaries: Buying_Levski = {'Agricultural Supply': 1.11, 'Aluminum': 1.20, 'Hydrogen': 0.98, 'Iodine': 0.38, 'Quartz': 1.37, 'Waste': 0.005,} the price of buying Hydrogen on Levski is thus Buying_Levksi['Hydrogen'], which is a lot more readable than a numeric index into a tuple which is itself obtained by a numeric index into a list. Lists *do* have the advantage of being easy to sort, but bear with me. 2. storing the data pertinent to an endpoint by the name of the endpoint means each investigation has to hardcode the name of those endpoint variables. You probably want to think of a data structure that will let you fish out the pricing dictionary by endpoint name and transaction type (buy or sell). === Second, let's rethink how you can extract what you want from this data. 1. From an endpoint pair - say Buy/Levski and Sell/Olisar, you need the common items. No point in looking further at items that can't both be bought at the source and sold at the destination. Fortunately, Python sets are really good at this, but first you have to extract only the item names from your dictionary, since that comparison is based only on good names. Something like this: def common(curr, other): return set(curr.keys()).intersection(set(other.keys())) aka build a set using the keys from the first argument, and call the intersection method on that set giving it the set built from the keys of the second argument. Which you can call this way to see that it's working: possibles = common(Buying_Levski, Selling_Olisar) print("common Levski -> Olisar", possibles) (you can certainly solve this in other ways than using sets) 2. From the common items, figure out which provides the greatest difference between the buy price and sell price. We'll presume, because you didn't mention it, that there is no volume component to this and that these prices are all for one unit and units consume the same amount of carrying capacity in your vessel. So one way to tackle this might be to build a new dictionary containing the items and their price difference. Given our previous idea of having a set which contains the common items: prices = {k: Selling_Olisar[k] - Buying_Levski[k] for k in possibles} That's pretty concise... it's called a "dictionary comprehension" if you haven't seen those before, and means loop through "possibles" saving the possibles item as the key and the difference between sell price and buy price as the value. Note1: see how irritating it is to have to keep referring to the data structures by name this way? Note2: you'll probably get a surprise when you do this - floating point numbers don't always represent "cleanly", so the subtractions might give you intesting-looking values if you print them out. There are answers for that, too. Given that dictionary, what is the key corresponding to the largest value - the good you want to buy? That's a little tricky with a dictionary, but with some manipulation, or constructing the proper sort function as an argument to the max() function, it can be done. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regarding "IDLE Subprocess Didn't Make Connection" Error
On 11/17/18 10:38 AM, Avi Gross wrote: > I was wondering if I was the only one who felt the urge to apply a tad of > humor and suppressed most of the thoughts about idol/IDLE worship and other > puns so I am glad to see Steve do just a little of the same. > > It seems that despite how portable Python is touted to be, quite a few people > report problems in getting the basics working when installing. And if you > can't get started, that is obviously a barrier. My suggestion earlier was > based on the fact that IDLE is an add-on and they should first check if > Python itself works. Any text editor can be used that just produces plain > text and scripts can be run in other ways. > > But I have a thought. An old an often effective method to solve a problem is > to search in the source code. Yes, you did not write IDLE. > > I am still not clear on how IDLE aborts on startup but I recall that IDLE > may be written in Python with source code available. actually, one of the "surprising" ways IDLE can fail for people is specifically because it is written in Python itself: if they have a Python file in the directory they are starting it from that duplicates the name of an important file in IDLE - if the import statement is encountered in IDLE and that import can be satisfied by the local file it picks that one first, and then IDLE breaks... anyway, one of the common things people say to get around this is to just dump IDLE. this sounds harsh: Python strives to supply a usable beginner environment and then it doesn't work, and we say "so don't use it"? well, it doesn't bother me to say that... there are tons of IDE-type environments for Python, ones that call themselves editors but have "run script inside the editor" behavior and ones that are full IDE. By all means, try the information on the internet on getting IDLE working, but it's not worth spending a *ton* of time on it, IDLE is not Python, it's just a helpful tool, and if a tool doesn't work but another one will, throw away the broken one. Here are some thoughts: https://wiki.python.org/moin/PythonEditors https://wiki.python.org/moin/IntegratedDevelopmentEnvironments those are user-edited pages, if anyone has more favorites that are not listed there, please feel free to volunteer to add more. Between several systems I have the following things that let me edit and run Python code: IDLE (yup, works for me) Eric Atom (with additional Python configuration for nicer env) Eclipse (with Python environment pydev) PyCharm (with additional Python configuration for nicer env) SublimeText (with additional Python configuration for nicer env) Visual Studio Code (with additional Python configuration for nicer env) vim some often favored Windows tools don't appear on this list, like Code::Blocks, because I'm not principally a Windows user. I don't use all of those: some not at all, some frequently, some occasionally. They all work fine. All are free except SublimeText; PyCharm comes in both free community and non-free other editions. Some are big and heavy (I don't recommend Eclipse for the faint of heart), some are not. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] how to print lines which contain matching words or strings
Hi All , I have a set of words and strings : like : p = [A ,"B is good" ,123456 , "C "] I have a file in which I need to print only the lines which matches the pattern in p thanks, -- Asad Hasan +91 9582111698 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the largest gap in tuple between two lists.
Harry, Your code may not have come through as intended as the formatting often combined lines. It may help to think about the question before giving deeper answers. You have two places and two sets of goods with prices. You want the intersection of those two to focus on what goods are in both. There are various ways to do that ranging from using sets to creating an empty object (such as a list or dictionary) then iterating over all items in group A and adding only what is also IN group B. You then want to maximize the difference in price for a particular item in group A versus B. If you have the right data structures, that is a snap. Suppose you made two dictionaries holding the keys in A and the keys in B alongside values for each. You could iterate over the keys in either dictionary and calculate A[key] = B[key] and if it is higher than the previous high, replace the previous high while also saving the value of key. Is that roughly what is needed? You buy one item with the maximum "profit"? I can imagine having a fixed dollar amount to spend and a similar problem where you can buy as many as you can afford of that item as a variant or even a knapsack version where you might buy cheaper ones with any money left, ... If you post again, see if you can find a way to have the text formatted properly as we have seen examples where Python programs get different results, or fail completely, with changes in indentation. -Original Message- From: Tutor On Behalf Of Harry Oneill Sent: Saturday, November 17, 2018 8:55 PM To: tutor@python.org Subject: [Tutor] Finding the largest gap in tuple between two lists. Hello there everyone i hope you are all doing fantastic. Im currently working on a little program that is designed to do a basic function to help me to trade efficiently within the game Star Citizen: #1 take two inputs ( location and destination ) #2 Find what product is best to buy at location to sell at destination #3 Print the results currently i have figured out how to get python to take the two inputs and provide me with the lowest buy price and highest sell price. However the information i want to produce is what has the largest profit margin possible between the two locations so i need to compare what items are available in both locations and then see what one has the largest price difference then display that items name. Below is the code i have currently made for this. Current_Location = input("Where are you currently located? :").lower() Current_Destination = input("Where are you planning to travel? :").lower() def Find_Lowest_Buy_Olisar(): print("Finding lowest buy price for OLISAR...") print(*Sort_Buying_Olisar[:1], sep='\n') def Find_Highest_Sell_Olisar(): print("Finding highest sell price for OLISAR...") print(*Sort_Selling_Olisar[:1], sep='\n') def Find_Lowest_Buy_Levski(): print("Finding lowest buy price for LEVSKI...") print(*Sort_Buying_Levski[:1], sep='\n') def Find_Highest_Sell_Levski(): print("Finding highest sell price for LEVSKI...") print(*Sort_Selling_Levski[:1], sep='\n') Buying_Olisar = [('Medical Supply', 17.01), ('Waste', 0.005),] Sort_Buying_Olisar = sorted_by_second = sorted(Buying_Olisar, key=lambda tup: tup[1]) Selling_Olisar = [('Agricium', 25.60), ('Aluminum', 1.25), ('Beryl', 4.26), ('Chlorine', 1.57), ('Corundum', 2.53), ('Diamond', 6.90), ('Distilled Spirits', 4.95), ('Fluorine', 2.80), ('Gold', 6.07), ('Hydrogen', 1.02), ('Iodine', 0.41), ('Laranite', 28.91), ('Processed Food', 1.39), ('Quartz', 1.44), ('Scrap', 1.67), ('Stims', 3.40), ('Titanium', 8.27), ('Tungsten', 3.90),] Sort_Selling_Olisar = sorted(Selling_Olisar, key=lambda tup:(-tup[1], tup[0])) Buying_Levski = [('Agricultural Supply', 1.11), ('Aluminum', 1.20), ('Hydrogen', 0.98), ('Iodine', 0.38), ('Quartz', 1.37), ('Waste', 0.005),] Sort_Buying_Levski = sorted_by_second = sorted(Buying_Levski, key=lambda tup: tup[1]) Selling_Levski = [('Agricium', 25.60), ('Altruciatoxine', 11.63), ('Beryl', 4.25), ('Chlorine', 1.56), ('Corundum', 2.53), ('Diamond', 6.07), ('Distilled Spirits', 4.95), ('Fluorine', 2.80), ('Gold', 6.07), ('Laranite', 28.25), ('Medical Supply', 18.00), ('Processed Food', 1.38), ('Scrap', 1.68), ('Stims', 3.40), ('Titanium', 8.27), ('Tungsten', 3.90), ('Widdow', 24.00),] Sort_Selling_Levski = sorted(Selling_Levski, key=lambda tup:(-tup[1], tup[0])) if Current_Location == "olisar": Find_Lowest_Buy_Olisar() elif Current_Location == "levski": Find_Lowest_Buy_Levski() else: print("Unknown location please try again.") if Current_Destination == "olisar": Find_Highest_Sell_Olisar() elif Current_Destination == "levski": Find_Highest_Sell_Levski() else: print("Unknown location please try again.") Any input would be hugely appreciated. Kind regards, Harry O'Neill ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/
[Tutor] Issue in parsing the string output from the command using "subprocess"
Dear Python Experts Team, As am newbie to python and learning python, working on embedded linux platform, my intention is to delete all the SSID's before connecting my Wi-Fi module to specific SSID., I am trying to parse command output using the "subprocess" with wrapper "execute_cmd_output_string" written on it described as below, using the nmcli commands "*nmcli -t -f TYPE,UUID con" and "**"nmcli connection delete uuid ".* Could you please help me, what could be the bug in the below method "*def wifi_disconnect_reconnect(self, ssid, pw):" *using the method "execute_cmd_output_string" (in-turn uses "subprocess") which is failing to give correct output of., UUID's for *"nmcli connection delete uuid "* ? But which works fine with "commands.getstatusoutput" (res = commands.getstatusoutput("nmcli -t -f TYPE,UUID con")), but I dont want to include "commands.getstatusoutput" which costs me for including one more python module in my rootfs Typical output for "nmcli -t -f TYPE,UUID con" ~$ nmcli -t -f TYPE,UUID con 802-11-wireless:3f5011d4-5681-4fed-8dea-95dee790e9e2 802-11-wireless:bfb93be0-740d-426e-b215-0fdc2f652877 802-11-wireless:69b60cf4-65aa-442b-a54c-fb82905adb0d 802-11-wireless:dc2a15ec-d3da-491e-9c8f-cb054f375837 802-11-wireless:5164e7f2-4489-462e-b093-76bc51bf1303 802-11-wireless:d462e8c4-fac7-42f2-8f9a-6846f52d4e8c 802-11-wireless:e5020744-5c9c-453c-92ec-7a854fc893e6 802-11-wireless:eed3358e-8635-471d-b7e9-5c2973a05128 802-11-wireless:ceea6707-a929-4941-9047-a75e061914b6 802-11-wireless:dd6b9c83-db7b-42b9-99c0-14a04f6f35f5 802-11-wireless:9f764fff-6288-49c4-9412-902e89230136 802-11-wireless:72c627cd-77a3-4d16-bb2c-058040d8e4fc ~$ *Python Code Snipeet:* *--* *def wifi_disconnect_reconnect(self, ssid, pw):* *"""* *Connect to Access point using SSID and PW.* *:param ssid: SSID of the ACCESS POINT.* *:param pw: password for connecting to the access point.* *:return: command output as True or False.* *"""* *cmd = "nmcli -t -f TYPE,UUID con"* *res = self._helper.execute_cmd_output_string(cmd)* *print(res)* *lines = res[1].split('\n') > I suspect the issue might be here* *print(lines)* *for line in lines:* *parts = line.split(":")* *print(parts)* *print(parts[1])* *if (parts[0] == "802-11-wireless"):* *print("nmcli connection delete uuid "+ parts[1])* *os.system("nmcli connection delete uuid "+ parts[1])* *cmd = "nmcli device wifi connect '%s' password %s" % (ssid, pw)* *exit_code = self._helper.execute_cmd_return_code(cmd)* *return True if exit_code == 0 else False* def execute_cmd_output_string(self, cmd, enable_shell=False): """ Execute a command and return its output as a string. :param cmd: abs path of the command with arguments :param enable_shell : force the cmd to be run as shell script :return: a string. """ try: result = subprocess.check_output(split(cmd), stderr=subprocess.STDOUT, shell=enable_shell) except subprocess.CalledProcessError as e: s = """While executing '{}' something went wrong. Return code == '{}' Return output:\n'{}' """.format(cmd, e.returncode, e.output, shell=enable_shell) raise AssertionError(s) return result.strip().decode("utf-8") if __name__ == "__main__": m = wifi() print("disconnect and reconnect") print(m.wifi_disconnect_reconnect("NaWiFi", "abcds")) *Errors:* --- Traceback (most recent call last): 802-11-wireless:3f5011d4-5681-4fed-8dea-95dee790e9e2 802-11-wireless:dc2a15ec-d3da-491e-9c8f-cb054f375837 802-11-wireless:5164e7f2-4489-462e-b093-76bc51bf1303 File "/home/srinivasan/Downloads/qa_wifi_nov15_after_incorporating_thilo_comments_zip/qa/test_library/wifi.py", line 153, in 802-11-wireless:d462e8c4-fac7-42f2-8f9a-6846f52d4e8c print(m.wifi_connect("NI WiFi", "T.f.o.s.1996!")) 802-11-wireless:e5020744-5c9c-453c-92ec-7a854fc893e6 802-11-wireless:eed3358e-8635-471d-b7e9-5c2973a05128 File "/home/srinivasan/Downloads/qa_wifi_nov15_after_incorporating_thilo_comments_zip/qa/test_library/wifi.py", line 77, in wifi_connect 802-11-wireless:ceea6707-a929-4941-9047-a75e061914b6 print(parts[1]) 802-11-wireless:dd6b9c83-db7b-42b9-99c0-14a04f6f35f5 *IndexError: list index out of range* 802-11-wireless:9f764fff-6288-49c4-9412-902e89230136 802-11-wireless:72c627cd-77a3-4d16-bb2c-058040d8e4fc [u'0'] [u'0'] Process finished with exit code 1 But when I execute the below the command using the python module "commands". I am able to successfully parse the multi line string output and extarct the UUID's from
Re: [Tutor] Finding the largest gap in tuple between two lists.
Mats Wichmann wrote: > 1. From an endpoint pair - say Buy/Levski and Sell/Olisar, you need the > common items. No point in looking further at items that can't both be > bought at the source and sold at the destination. Fortunately, Python > sets are really good at this, but first you have to extract only the > item names from your dictionary, since that comparison is based only on > good names. Something like this: > > def common(curr, other): > return set(curr.keys()).intersection(set(other.keys())) As dict.keys() are very similar to a set you can also write curr.keys() & other.keys() or curr.keys() & other # if you don't care about symmetry ;) > So one way to tackle this might be to build a new dictionary containing > the items and their price difference. Given our previous idea of having > a set which contains the common items: > > prices = {k: Selling_Olisar[k] - Buying_Levski[k] for k in possibles} While a dict is almost always a good idea there is no need to build one if you're only interested in one entry. Instead feed the pairs directly to max(): selling = dict(Selling_Olisar) buying = dict(Buying_Levski) possibles = selling.keys() & buying if possibles: profit, good = max( (selling[k] - buying[k], k) for k in possibles ) if profit > 0: print("Best good", good, "wins", profit, "per unit") else: print("Found nothing profitable.") else: print("Found nothing that can be sold at your destination") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to print lines which contain matching words or strings
On Nov 18, 2018 12:14 PM, "Asad" wrote: > > Hi All , > >I have a set of words and strings : > > like : > > p = [A ,"B is good" ,123456 , "C "] > > I have a file in which I need to print only the lines which matches the > pattern in p > > thanks, you are welcome, but I'm not sure what you're thanking us for. I don't see any kind of request in your email. There are various resources on how to ask effective questions. You might try Googling that topic. I have more that I will say later. Bob Gailer ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to print lines which contain matching words or strings
On Nov 18, 2018 1:19 PM, "Bob Gailer" wrote: > > On Nov 18, 2018 12:14 PM, "Asad" wrote: > > > > Hi All , > > > >I have a set of words and strings : > > > > like : > > > > p = [A ,"B is good" ,123456 , "C "] > > > > I have a file in which I need to print only the lines which matches the > > pattern in p > > > > thanks, Terminology is very important. You say set then you show us a list. You say words and strings, but your list contains a python identifier and a number in addition to Strings. You say pattern but don't Define what you mean by pattern. I could not begin to guess what your definition of pattern is. We also do not know what the term word means to you. You may say that is obvious but it is not. So tell us your meaning of word. To make the question meaningful I would suggest you show us sample of the file indicating lines that meet the pattern and lines that don't. Please realize that we are not here to write code for you, rather we like to help you when we see you put in some effort. So I suggest you write a Python program that attempts to do what you want, then tell us where the program isn't doing what you want or where you are stuck will try to help. Please respond in some way so that we know you have heard us. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] please add gillidr...@gmail.com
___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] seeking beginners tutorial for async
I have yet to find a tutorial that helps me understand and apply async! The ones I have found are either incomplete, or they wrap some other service, or they are immediately so complex that I have no hope of understanding them. I did find a useful javascript tutorial at https://javascript.info/promise-basics, but trying to map it to python is very frustrating. The python docs also do not help. Can you point me to any resources that are actually useful to a beginner? Bob Gailer guru of many languages including Python ( up till now!) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor