Python Arrays Minimize Values
I am trying to change the values of an array into smaller numbers like
list = [1,3,7,3]
into
list = [1,2,3,2]
I already have a few lines of code to keep it organized.
def sortItems(list):
counts = collections.Counter(list)
sortedlist = sorted(list, key=counts.get, reverse=True)
return sortedlist
been crawling all over W3Schools and other forums but still unsure
2 answers
-
answered 2022-01-23 02:57
Raymond Kwok
l = [1, 3, 7, 3] unique_keys = set(l) mappings = {key: val for val, key in enumerate(sorted(unique_keys), 1)} print(list(map(mappings.get, l)))
Orders are preserved by the
sorted()
. -
answered 2022-01-23 03:07
Mateen Ulhaq
(This answer addresses the information in the comments.)
For a performant implementation, count, sort keys, then repeat and flatmap.
from collections import Counter from itertools import repeat def flatmap_repeat_sort_count(xs): counts = Counter(xs) keys = sorted(counts.keys()) return [ x for i, k in enumerate(keys, start=1) for x in repeat(i, counts[k]) ]
Example runs:
>>> flatmap_repeat_sort_count([1, 3, 7, 3]) [1, 2, 2, 3] >>> flatmap_repeat_sort_count([7, 1, 3, 1]) [1, 1, 2, 3]
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
How to get pass an array through a function with a user input?
I want to ask the user for the size of a 2D array arr[][], but also pass it through the function initializeArray. However, if I pass it through the function, I would have to have a size declarator for col, which doesn't allow the user to enter their own value for the size
#include<iostream> using namespace std; void initializeArray(arr[][10], int N); int main() { int N; cout << "enter an array size: "; cin >> N; int arr[N][N]; initializeArray(arr, N); // I get an error here for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) cout << arr[i][j] << " "; cout << endl; } } void initializeArray(int arr[][10], int N) { for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) arr[i][j] = 0; }
The only solution I found was the make arr[][] a global array, but in that case, I would have to still declare the size parameters, and I want the user to enter whatever they want. Is there another way to fix this?
-
Two-dimensional array C++
Problem: Write a program of a two dimensional integer array of exactly four rows and four columns, and find the sum of the integers each row of the array as well as determine the smallest inputted element/data in the array. The user will input the elements. Display the elements in tabular form. Make the program user friendly. Use a Class and a member function for the process involve.
-
Pass Associative Array from Symfony Controller to Twig and JavaScript
So, I have 2 arrays that I've combined into one array after making sure they're the same length as such.
//Fetching Ratings for All Coaches & Making a Key, Value Associative Array with Coach id as Key and Rating as Value $coaches = $coachRepository->findAll(); $rating = $coachRepository->findRatingByCoach(); //Array of coach IDs $id_array = array(); foreach ($coaches as $c){ $id_array[] = $c->getId(); } $combined = array_combine($id_array, $rating);
Now I want to pass this key, value array to Twig template and JavaScript. I'm currently doing this
return $this->render('...', [ ..., 'combined'=>$combined ]);
And I'm accessing the array in Twig as such
{% for key, value in combined %} {{ key }} - {{ value }} {% endfor %}
And I'm getting this error.
Object of class App\Entity\Coach could not be converted to string
Looking at the Stack Trace I can see that the array combined is being passed in this form.
'combined' => array(object(Coach))
After a bit of debugging it turns out that I thought the issue was with the $
id_array
when in fact it's the $rating
variable that's presenting an issue. I'm not sure why but I'm getting a single float value. I fixed the issue by changing how I'm fetching the $rating, now instead of using a QueryBuilder to get it from the DB, I'm getting it from list of Coaches as such//Array of coach IDs and array of Ratings $id_array = array(); $rating_array = array(); foreach ($coaches as $c){ $id_array[] = $c->getId(); $rating_array [] = $c->getRating(); }
Even if I set the array
-
Convert 2D meshgrid into a 3D array in Python
I have coordinates (lat, lon) in a meshgrid, and data asociated with each "point". I want to export into a .csv and have each point asociated with the data i want to analyze. So far, my code looks like this.
xx1,yy1=np.meshgrid(xx,yy) row_format = np.stack([z.ravel() for z in (xx1, yy1, data['Hs'])], axis=1) print(row_format) pd.DataFrame(row_format).to_csv('sample.csv')
The data is in a dataframe that has a certain order. But the output is as follows:
x y Hs 265 19 0 266 19 1 267 19 2 And it should be as follows, in order to make sense with the data order:
x y Hs 265 19 0 265 18 1 265 17 2 I only need to make the "x" column to be the one with the "still" value while the "y" column goes through its values ("x" will change value once every "y" value has been written). Anyone know how to change that order? Or another way to get my desired output?
-
Range Not Found, Google Apps Script for Google Sheets
I'm trying to build a custom range for this sort function in an Apps Script for Google Sheets but I keep getting the error: "Exception: Range not found; sortProductionLog @ macros.gs:15"
I'm sure this is something basic but I have searched far and wide and can't seem to find it. Can anyone shed some light?
Thank you, Ryan
SORT_ORDER = [ {column: 118, ascending: true}, // 3 = column number, sorting by descending order {column: 119, ascending: true}, // 1 = column number, sort by ascending order {column: 117, ascending: true}, {column: 25, ascending: true} ]; function sortProductionLog(){ var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName(SHEET_NAME); var LastRow_WithValue = sheet.getLastRow(); var LastColumn_WithValue = sheet.getLastColumn(); var buildRange = "4,1," + (LastRow_WithValue - 4) + "," + (LastColumn_WithValue - 1); var range = sheet.getRange(buildRange); ss.toast(buildRange); range.sort }
-
Categorize similar transactions
Given a list of transactions, some transactions are categorized, some transactions are not categorized. Find similar transactions and categorize them if possible. Similar transactions have the same targetAccount and the amount difference is not greater than 1000 (for all currencies) from the originally categorized transaction. If an uncategorized transaction is similar to more than one transaction, it should take the category from the one with the smallest amount difference. Transactions that cannot be categorized should still be included in the returned list. The returned list should preserve the order of the original list.
categorizeSimilarTransactions(transactions)
Input You can assume that the transactions parameter will always be present and valid. list of transactions (Transaction[])
Output List of transactions(Transaction[]) with enhanced categorization if possible.
This is what a categorized transaction looks like:
{ id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -350, currency: "EUR", category: "eating_out", time: "2021-03-12T12:34:00Z" }
An uncategorized transaction does not have category property. This is what an uncategorized transaction looks like:
{ id: "0f0ffbf9-2e26-4f5a-a6c0-fcbd504002f8", sourceAccount: "my_account", targetAccount: "eating_out", amount: -1900, time: "2021-03-12T12:34:00Z" }
The following two transactions are similar:
{ id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -350, category: "eating_out", time: "2021-03-12T12:34:00Z" }
and
{ id: "a001bb66-6f4c-48bf-8ae0-f73453aa8dd5", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -620, time: "2021-04-10T10:30:00Z" }
Input
categorizeSimilarTransactions([ { id: "a001bb66-6f4c-48bf-8ae0-f73453aa8dd5", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 350, time: "2021-04-10T10:30:00Z", }, { id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -150, category: "eating_out", time: "2021-03-12T12:34:00Z", }, { id: "6359091e-1187-471f-a2aa-81bd2647210f", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 100, category: "entertainment", time: "2021-01-12T08:23:00Z", }, { id: "a8170ced-1c5f-432c-bb7d-867589a9d4b8", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -1690, time: "2021-04-12T08:20:00Z", }, ]);
Expected Output
[ { id: "a001bb66-6f4c-48bf-8ae0-f73453aa8dd5", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 350, category: "entertainment", time: "2021-04-10T10:30:00Z", }, { id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -150, category: "eating_out", time: "2021-03-12T12:34:00Z", }, { id: "6359091e-1187-471f-a2aa-81bd2647210f", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 100, category: "entertainment", time: "2021-01-12T08:23:00Z", }, { id: "a8170ced-1c5f-432c-bb7d-867589a9d4b8", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -1690, time: "2021-04-12T08:20:00Z", }, ];
I could find a solution but it's a brute-force approach & not efficient. Is there any other solution with less time complexity may be O(n) or O(log(n))/O(nlog(n)) which is easy to read & understand
const categorizeSimilarTransactions = (transactions) => { if (!(Array.isArray(transactions) && transactions.length)) return []; const categorizedTransactions = transactions.filter(t => t.category); const uncategorizedTransactions = transactions.filter(t => !t.category); let lowestDiff; uncategorizedTransactions.forEach(uncategorizedTransaction => { lowestDiff = Math.min(); categorizedTransactions.forEach(cat => { if (cat.targetAccount === uncategorizedTransaction.targetAccount) { lowestDiffComp = Math.abs(cat.amount - uncategorizedTransaction.amount); if (lowestDiffComp < lowestDiff && lowestDiffComp < 1000) { lowestDiff = lowestDiffComp; uncategorizedTransaction.category = cat.category; } } }) }); const merged = [...categorizedTransactions, ...uncategorizedTransactions]; const orderIds = transactions.map(transaction => transaction.id); merged.sort((a, b) => { return orderIds.indexOf(a.id) - orderIds.indexOf(b.id); }) return merged; };