How to make a prime decomposition function faster?
I want to make a prime decomposition function faster, but it needs to use a precomputed list of primes. This is what I have so far:
def decompose(n):
factors = dict()
m = n
while m > 1:
for i in prime_list:
if i > m:
break
else:
if m%i == 0:
m = m//i
if i in factors.keys():
factors[i] += 1
else:
factors[i] = 1
return factors
Where prime_list is obviously the precomputed list of primes. Any help is much appreciated :)
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 can I speed up the routing process in OSMNX?
Say I have two taxi orders with Origin1、Destination1 and Origin2、Destination2(O1,O2,D1,D2). I want to calculate the possibility of ridesharing, so I need the path between two different points. And, here's my code:
def path_time(point1, point2): path = ox.distance.shortest_path(road, point1, point2, weight='travel_time') if path is None: #If there isn't a path, a big weight will be set, and it won't be selected during the matching process. route_time = 9999 else: route_time = int(sum(ox.utils_graph.get_route_edge_attributes(road, path, "travel_time"))) return route_time,path
Since there is four points, I need to do this six times, where tp means travel path :
tpO1O2 = path_time(O1,O2) tpO1D1 = path_time(O1,D1) tpO1D2 = path_time(O1,D2) tpO2D1 = path_time(O2,D1) tpO2D2 = path_time(O2,D2) tpD1D2 = path_time(D1,D2)
It's okay if I only have two points, but I got a 2 million order set, and each order has hundreds of potential matched orders. So this will take me a lot of time.
Does anyone knows how can I speed up this process? Thank you!
- Efficient way to know region of a coordinate
-
Lighthouse CLI: how to use current browser settings(running with extensions installed)
Try lighthouse CLI to measure performance of URLs with some extensions on.
With
lighthouse https://www.bing.com/search?q=curse+words --output json --output-path D:\lighthouseResults\0506.json --disable-device-emulation --chrome-flags="--user-agent=edge --window-size=360,640 --enable-experimental-extension-apis"
, it doesn't seem that the extension was working(usually takes a few seconds, very slow), and did not find http requests that were suppose to be there in the report.How should I do it in Lighthouse or I'm looking at the wrong tool?
-
Storing numbers larger than Big integer C#
I am having a really hard time finding a way to store massive prime numbers in c#. I tried everything but nothing worked out for me. For example. How can I store this number.
0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF
Do you know how or what an external library that could store that? Thanks!!!
-
Checking whether space should be printed in the middle or at the end in for loop?
I am trying to give info to my program whether it should print space or not. I am dealing with prime factorization.
0 1 2 2 3 3 4 2 2// I dont wanna print space at the end 5 5 6 2 3 //but between two nums or more I want space to be added 7 7 8 2 2 2 9 3 3 10 2 5 11 11 12 2 2 3 13 13
My code looks something like this, and its printing spaces at the end (which is not what I want)
void function(int given_limit) { int current_num = 2; while (given_limit > 1) { if (given_limit % current_num == 0) { if (current_num == 2) { printf("%d ", current_num); } else if (current_num == 3) { printf("%d ", current_num); } else if (current_num == 5) { printf("%d ", current_num); } else if (current_num == 7) { printf("%d ", current_num); } else { printf("%d ", current_num); } given_limit /= current_num; } else current_num++; } printf("\n"); }
In main() I am calling it something like this:
int main() { int given_limit = 13; for (int i = 0; i <= given_limit; i++) { printf("%d\t\t", i); function(i); } }
I would appreciate any tips and help. One of the ideas is maybe to store it in an array.
-
Why function is executed prior to printing of string in Python?
I'm executing this code:
#Printing a list of prime numbers till an input number: def is_prime(input): for counter1 in range(1,input): if(counter1==2): print("Prime number: 2") counter2=2 while (counter1%counter2!=0 and counter2<counter1): if(counter2==(counter1-1)): print("Prime number:",counter1) counter2+=1 print("Let us print prime numbers upto 10:",is_prime(10))
OUTPUT:
Prime number: 2 Prime number: 3 Prime number: 5 Prime number: 7 Let us print prime numbers upto 10: None
Why "Prime numbers:" are printed first then the string "Let us..." ??