Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
2
2024_WiSe_InfHAF_Notebooks
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package registry
Container Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
ml4nets_notebooks
2024_WiSe_InfHAF_Notebooks
Commits
29d47fbd
Commit
29d47fbd
authored
2 months ago
by
Anatol Wegner
Browse files
Options
Downloads
Patches
Plain Diff
Upload New File
parent
2b2cac58
Branches
main
No related tags found
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
PythonIntroNotebooks/functions.py
+53
-0
53 additions, 0 deletions
PythonIntroNotebooks/functions.py
with
53 additions
and
0 deletions
PythonIntroNotebooks/functions.py
0 → 100644
+
53
−
0
View file @
29d47fbd
import
random
import
multiprocessing
import
math
def
producer
(
queue
,
n_items
):
for
_
in
range
(
n_items
):
num
=
random
.
randint
(
1
,
100
)
print
(
"
Producer: Produced:
"
,
num
)
queue
.
put
(
num
)
queue
.
put
(
None
)
# None value to signal consumers to stop
def
consumer
(
queue
):
while
True
:
item
=
queue
.
get
()
if
item
is
None
:
# None value received, stop the consumer
break
processed_item
=
item
*
2
print
(
"
Consumer: Consumed
"
,
item
,
"
Processed
"
,
processed_item
)
def
count_divisors
(
n
):
"""
Calculates the number of divisors for a given integer n.
Args:
n: The integer for which to count divisors.
Returns:
The number of divisors of n.
"""
count
=
0
sqrt_n
=
int
(
math
.
sqrt
(
n
))
# Optimization: only check up to the square root
for
i
in
range
(
1
,
sqrt_n
+
1
):
if
n
%
i
==
0
:
count
+=
2
# i and n/i are both divisors
if
sqrt_n
*
sqrt_n
==
n
:
# if n is a perfect square, we counted the square root twice
count
-=
1
# Avoid double-counting the square root
return
count
def
sequential_processing
(
numbers
):
"""
Calculate number of divisors sequentially.
"""
results
=
[]
for
num
in
numbers
:
results
.
append
(
count_divisors
(
num
))
return
results
def
parallel_processing
(
numbers
,
cores
):
"""
Calculate number of divisors in parallel using a Pool.
"""
with
multiprocessing
.
Pool
(
processes
=
cores
)
as
pool
:
results
=
pool
.
map
(
count_divisors
,
numbers
)
return
results
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment