Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
A
assignment2-3
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
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
Bayan Alkhuzaei CS2023
assignment2-3
Commits
381b97f9
Commit
381b97f9
authored
1 year ago
by
Bayan Alkhuzaei CS2023
Browse files
Options
Downloads
Patches
Plain Diff
Upload New File
parent
eae85ee8
Branches
master
No related tags found
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
letters.py
+59
-0
59 additions, 0 deletions
letters.py
with
59 additions
and
0 deletions
letters.py
0 → 100644
+
59
−
0
View file @
381b97f9
#!/usr/bin/env python
letters
=
'
abcdefghijklmnopqrstuvwxyz
'
def
file2prob
(
filename
):
"""
Read a file and return a dictionary of letters and
their probabilities
"""
letter_dict
=
{
c
:
0
for
c
in
letters
}
letter_total
=
0
with
open
(
filename
,
encoding
=
"
utf-8
"
)
as
fp
:
for
c
in
fp
.
read
():
if
c
.
lower
()
not
in
letter_dict
:
continue
letter_dict
[
c
.
lower
()]
+=
1
letter_total
+=
1
probs
=
{
c
:
letter_dict
[
c
]
/
letter_total
for
c
in
letter_dict
}
return
probs
def
file2pairs
(
filename
):
"""
Read a file and return a dictionary of letters and
the probabilities of following letters. That is, the
conditional probability of a letter given its
predecessor.
"""
letter_dict
=
{
c
:
{
a
:
0
for
a
in
letters
}
for
c
in
letters
}
previous
=
None
with
open
(
filename
,
encoding
=
"
utf-8
"
)
as
fp
:
for
c
in
fp
.
read
():
if
c
not
in
letter_dict
:
continue
c
=
c
.
lower
()
if
previous
is
None
:
previous
=
c
continue
letter_dict
[
previous
][
c
]
+=
1
previous
=
c
probs
=
{
c
:
{
d
:
letter_dict
[
c
][
d
]
/
sum
(
letter_dict
[
c
].
values
())
for
d
in
letters
}
for
c
in
letters
}
return
probs
if
__name__
==
'
__main__
'
:
import
sys
if
len
(
sys
.
argv
)
!=
3
:
print
(
"
Usage: %s filename letter
"
%
sys
.
argv
[
0
])
sys
.
exit
(
-
1
)
filename
=
sys
.
argv
[
1
]
letter
=
sys
.
argv
[
2
]
probs
=
file2prob
(
filename
)
print
(
probs
[
letter
])
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