Key generating program in Python
$begingroup$
I am about two months into programming with Python (no previous experience) and I tried to write a program which would generate a key and assign it to a student.
import random
import string
code_list =
students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana",
"Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja",
"Kristjan", "Urban", "Janja", "Lea", "Žana", "Aljaž", "Tilen",
"Matic", "Marija", "Žiga T."]
#It generates the code and puts it in a list
size = 6
code = string.ascii_uppercase + string.digits
for i in range(24):
code_list.append(str(''.join(random.choice(code) for _ in range(size))))
#Combines the two lists (students and codes) into one
students_plus_codes = [x + str(" - " + y) for y in students for x in
code_list]
#It prints only every 25th element from the combined list
new = [x for i, x in enumerate(students_plus_codes) if i % 25 == 0]
for i in new:
print(i)`
My problem is that this code is not very elegant and just want to ask how I could write it more efficiently (especially the last part where I have to manually print out every 25th element of a list because every key gets assigned to every student).
python
New contributor
$endgroup$
add a comment |
$begingroup$
I am about two months into programming with Python (no previous experience) and I tried to write a program which would generate a key and assign it to a student.
import random
import string
code_list =
students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana",
"Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja",
"Kristjan", "Urban", "Janja", "Lea", "Žana", "Aljaž", "Tilen",
"Matic", "Marija", "Žiga T."]
#It generates the code and puts it in a list
size = 6
code = string.ascii_uppercase + string.digits
for i in range(24):
code_list.append(str(''.join(random.choice(code) for _ in range(size))))
#Combines the two lists (students and codes) into one
students_plus_codes = [x + str(" - " + y) for y in students for x in
code_list]
#It prints only every 25th element from the combined list
new = [x for i, x in enumerate(students_plus_codes) if i % 25 == 0]
for i in new:
print(i)`
My problem is that this code is not very elegant and just want to ask how I could write it more efficiently (especially the last part where I have to manually print out every 25th element of a list because every key gets assigned to every student).
python
New contributor
$endgroup$
add a comment |
$begingroup$
I am about two months into programming with Python (no previous experience) and I tried to write a program which would generate a key and assign it to a student.
import random
import string
code_list =
students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana",
"Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja",
"Kristjan", "Urban", "Janja", "Lea", "Žana", "Aljaž", "Tilen",
"Matic", "Marija", "Žiga T."]
#It generates the code and puts it in a list
size = 6
code = string.ascii_uppercase + string.digits
for i in range(24):
code_list.append(str(''.join(random.choice(code) for _ in range(size))))
#Combines the two lists (students and codes) into one
students_plus_codes = [x + str(" - " + y) for y in students for x in
code_list]
#It prints only every 25th element from the combined list
new = [x for i, x in enumerate(students_plus_codes) if i % 25 == 0]
for i in new:
print(i)`
My problem is that this code is not very elegant and just want to ask how I could write it more efficiently (especially the last part where I have to manually print out every 25th element of a list because every key gets assigned to every student).
python
New contributor
$endgroup$
I am about two months into programming with Python (no previous experience) and I tried to write a program which would generate a key and assign it to a student.
import random
import string
code_list =
students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana",
"Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja",
"Kristjan", "Urban", "Janja", "Lea", "Žana", "Aljaž", "Tilen",
"Matic", "Marija", "Žiga T."]
#It generates the code and puts it in a list
size = 6
code = string.ascii_uppercase + string.digits
for i in range(24):
code_list.append(str(''.join(random.choice(code) for _ in range(size))))
#Combines the two lists (students and codes) into one
students_plus_codes = [x + str(" - " + y) for y in students for x in
code_list]
#It prints only every 25th element from the combined list
new = [x for i, x in enumerate(students_plus_codes) if i % 25 == 0]
for i in new:
print(i)`
My problem is that this code is not very elegant and just want to ask how I could write it more efficiently (especially the last part where I have to manually print out every 25th element of a list because every key gets assigned to every student).
python
python
New contributor
New contributor
edited 6 mins ago
Jamal♦
30.3k11116227
30.3k11116227
New contributor
asked 1 hour ago
urban pečolerurban pečoler
62
62
New contributor
New contributor
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
The reason that you are getting so many more entries is because this list comprehension:
students_plus_codes = [x + str(" - " + y) for y in students for x in code_list]
It's a nested for loop. If we expand it we can see what is happening:
students_plus_codes =
for y in students: # students has 24 items
for x in code_list: # code_list has 24 items
students_plus_codes(x + str(" - " + y))
So for every iteration of students
you do 24 iterations of code_list
.
Fortunately, python has a builtin function called zip
that will merge lists for us. So we can replace the nested list comprehension with this line:
students_plus_codes = list(zip(students, code_list))
Which results in a list of tuples:
[('Aljoša', '256D2B'), ('Blažka', 'OEGJL9'), ('Nana', 'GB1PJL'), ('Kaja', 'F0P0F2'),
('Alja', '62KU94'), ... ('Matic', 'E7CJIP'), ('Marija', '1D2UCL'), ('Žiga T.', '6X1DD5')]
Generating the codes:
First, I would replace for i in range(24):
with for i in range(len(students)):
as this allows you to change the number of students without having change other aspects of your code. In this instance 24
is a magic number that could cause issues down the line.
You could even create a function that generates the the code, then you can use an easy to read list comprehension.
# <=python3.5
def generate_code(n, characters):
return ''.join([random.choice(characters) for _ in range(n)])
# >=python3.6
def create_code(n, characters):
return ''.join(random.choices(characters, k=n))
Printing the codes:
It isn't ideal to join the names and codes a single string as this makes it hard to use them separately later. For this reason, I used a list of tuples to match them as pairs. To print them the for loop has two variables, student
and code
that takes advantage of unpacking and then prints them using the format
function.
Instead of joining the students names with the codes for printing is not an ideal thing to do as it makes it harder to use the names and codes separately later.
Altogether:
import random
import string
def create_code(n, characters):
return ''.join(random.choices(characters, k=n))
students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana",
"Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja",
"Kristjan", "Urban", "Janja", "Lea", "Žana", "Aljaž", "Tilen",
"Matic", "Marija", "Žiga T."]
# It generates the code and puts it in a list
size = 6
chars = string.ascii_uppercase + string.digits
code_list = [create_code(size, chars) for _ in range(len(students))]
# Combines the two lists (students and codes) into a list of tuples
students_plus_codes = list(zip(students, code_list))
for student, code in students_plus_codes:
print('{} - {}'.format(code, student))
New contributor
$endgroup$
$begingroup$
Thank you, this was really helpful, I would never figure it out on my own :D
$endgroup$
– urban pečoler
9 mins ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
urban pečoler is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212338%2fkey-generating-program-in-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
The reason that you are getting so many more entries is because this list comprehension:
students_plus_codes = [x + str(" - " + y) for y in students for x in code_list]
It's a nested for loop. If we expand it we can see what is happening:
students_plus_codes =
for y in students: # students has 24 items
for x in code_list: # code_list has 24 items
students_plus_codes(x + str(" - " + y))
So for every iteration of students
you do 24 iterations of code_list
.
Fortunately, python has a builtin function called zip
that will merge lists for us. So we can replace the nested list comprehension with this line:
students_plus_codes = list(zip(students, code_list))
Which results in a list of tuples:
[('Aljoša', '256D2B'), ('Blažka', 'OEGJL9'), ('Nana', 'GB1PJL'), ('Kaja', 'F0P0F2'),
('Alja', '62KU94'), ... ('Matic', 'E7CJIP'), ('Marija', '1D2UCL'), ('Žiga T.', '6X1DD5')]
Generating the codes:
First, I would replace for i in range(24):
with for i in range(len(students)):
as this allows you to change the number of students without having change other aspects of your code. In this instance 24
is a magic number that could cause issues down the line.
You could even create a function that generates the the code, then you can use an easy to read list comprehension.
# <=python3.5
def generate_code(n, characters):
return ''.join([random.choice(characters) for _ in range(n)])
# >=python3.6
def create_code(n, characters):
return ''.join(random.choices(characters, k=n))
Printing the codes:
It isn't ideal to join the names and codes a single string as this makes it hard to use them separately later. For this reason, I used a list of tuples to match them as pairs. To print them the for loop has two variables, student
and code
that takes advantage of unpacking and then prints them using the format
function.
Instead of joining the students names with the codes for printing is not an ideal thing to do as it makes it harder to use the names and codes separately later.
Altogether:
import random
import string
def create_code(n, characters):
return ''.join(random.choices(characters, k=n))
students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana",
"Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja",
"Kristjan", "Urban", "Janja", "Lea", "Žana", "Aljaž", "Tilen",
"Matic", "Marija", "Žiga T."]
# It generates the code and puts it in a list
size = 6
chars = string.ascii_uppercase + string.digits
code_list = [create_code(size, chars) for _ in range(len(students))]
# Combines the two lists (students and codes) into a list of tuples
students_plus_codes = list(zip(students, code_list))
for student, code in students_plus_codes:
print('{} - {}'.format(code, student))
New contributor
$endgroup$
$begingroup$
Thank you, this was really helpful, I would never figure it out on my own :D
$endgroup$
– urban pečoler
9 mins ago
add a comment |
$begingroup$
The reason that you are getting so many more entries is because this list comprehension:
students_plus_codes = [x + str(" - " + y) for y in students for x in code_list]
It's a nested for loop. If we expand it we can see what is happening:
students_plus_codes =
for y in students: # students has 24 items
for x in code_list: # code_list has 24 items
students_plus_codes(x + str(" - " + y))
So for every iteration of students
you do 24 iterations of code_list
.
Fortunately, python has a builtin function called zip
that will merge lists for us. So we can replace the nested list comprehension with this line:
students_plus_codes = list(zip(students, code_list))
Which results in a list of tuples:
[('Aljoša', '256D2B'), ('Blažka', 'OEGJL9'), ('Nana', 'GB1PJL'), ('Kaja', 'F0P0F2'),
('Alja', '62KU94'), ... ('Matic', 'E7CJIP'), ('Marija', '1D2UCL'), ('Žiga T.', '6X1DD5')]
Generating the codes:
First, I would replace for i in range(24):
with for i in range(len(students)):
as this allows you to change the number of students without having change other aspects of your code. In this instance 24
is a magic number that could cause issues down the line.
You could even create a function that generates the the code, then you can use an easy to read list comprehension.
# <=python3.5
def generate_code(n, characters):
return ''.join([random.choice(characters) for _ in range(n)])
# >=python3.6
def create_code(n, characters):
return ''.join(random.choices(characters, k=n))
Printing the codes:
It isn't ideal to join the names and codes a single string as this makes it hard to use them separately later. For this reason, I used a list of tuples to match them as pairs. To print them the for loop has two variables, student
and code
that takes advantage of unpacking and then prints them using the format
function.
Instead of joining the students names with the codes for printing is not an ideal thing to do as it makes it harder to use the names and codes separately later.
Altogether:
import random
import string
def create_code(n, characters):
return ''.join(random.choices(characters, k=n))
students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana",
"Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja",
"Kristjan", "Urban", "Janja", "Lea", "Žana", "Aljaž", "Tilen",
"Matic", "Marija", "Žiga T."]
# It generates the code and puts it in a list
size = 6
chars = string.ascii_uppercase + string.digits
code_list = [create_code(size, chars) for _ in range(len(students))]
# Combines the two lists (students and codes) into a list of tuples
students_plus_codes = list(zip(students, code_list))
for student, code in students_plus_codes:
print('{} - {}'.format(code, student))
New contributor
$endgroup$
$begingroup$
Thank you, this was really helpful, I would never figure it out on my own :D
$endgroup$
– urban pečoler
9 mins ago
add a comment |
$begingroup$
The reason that you are getting so many more entries is because this list comprehension:
students_plus_codes = [x + str(" - " + y) for y in students for x in code_list]
It's a nested for loop. If we expand it we can see what is happening:
students_plus_codes =
for y in students: # students has 24 items
for x in code_list: # code_list has 24 items
students_plus_codes(x + str(" - " + y))
So for every iteration of students
you do 24 iterations of code_list
.
Fortunately, python has a builtin function called zip
that will merge lists for us. So we can replace the nested list comprehension with this line:
students_plus_codes = list(zip(students, code_list))
Which results in a list of tuples:
[('Aljoša', '256D2B'), ('Blažka', 'OEGJL9'), ('Nana', 'GB1PJL'), ('Kaja', 'F0P0F2'),
('Alja', '62KU94'), ... ('Matic', 'E7CJIP'), ('Marija', '1D2UCL'), ('Žiga T.', '6X1DD5')]
Generating the codes:
First, I would replace for i in range(24):
with for i in range(len(students)):
as this allows you to change the number of students without having change other aspects of your code. In this instance 24
is a magic number that could cause issues down the line.
You could even create a function that generates the the code, then you can use an easy to read list comprehension.
# <=python3.5
def generate_code(n, characters):
return ''.join([random.choice(characters) for _ in range(n)])
# >=python3.6
def create_code(n, characters):
return ''.join(random.choices(characters, k=n))
Printing the codes:
It isn't ideal to join the names and codes a single string as this makes it hard to use them separately later. For this reason, I used a list of tuples to match them as pairs. To print them the for loop has two variables, student
and code
that takes advantage of unpacking and then prints them using the format
function.
Instead of joining the students names with the codes for printing is not an ideal thing to do as it makes it harder to use the names and codes separately later.
Altogether:
import random
import string
def create_code(n, characters):
return ''.join(random.choices(characters, k=n))
students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana",
"Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja",
"Kristjan", "Urban", "Janja", "Lea", "Žana", "Aljaž", "Tilen",
"Matic", "Marija", "Žiga T."]
# It generates the code and puts it in a list
size = 6
chars = string.ascii_uppercase + string.digits
code_list = [create_code(size, chars) for _ in range(len(students))]
# Combines the two lists (students and codes) into a list of tuples
students_plus_codes = list(zip(students, code_list))
for student, code in students_plus_codes:
print('{} - {}'.format(code, student))
New contributor
$endgroup$
The reason that you are getting so many more entries is because this list comprehension:
students_plus_codes = [x + str(" - " + y) for y in students for x in code_list]
It's a nested for loop. If we expand it we can see what is happening:
students_plus_codes =
for y in students: # students has 24 items
for x in code_list: # code_list has 24 items
students_plus_codes(x + str(" - " + y))
So for every iteration of students
you do 24 iterations of code_list
.
Fortunately, python has a builtin function called zip
that will merge lists for us. So we can replace the nested list comprehension with this line:
students_plus_codes = list(zip(students, code_list))
Which results in a list of tuples:
[('Aljoša', '256D2B'), ('Blažka', 'OEGJL9'), ('Nana', 'GB1PJL'), ('Kaja', 'F0P0F2'),
('Alja', '62KU94'), ... ('Matic', 'E7CJIP'), ('Marija', '1D2UCL'), ('Žiga T.', '6X1DD5')]
Generating the codes:
First, I would replace for i in range(24):
with for i in range(len(students)):
as this allows you to change the number of students without having change other aspects of your code. In this instance 24
is a magic number that could cause issues down the line.
You could even create a function that generates the the code, then you can use an easy to read list comprehension.
# <=python3.5
def generate_code(n, characters):
return ''.join([random.choice(characters) for _ in range(n)])
# >=python3.6
def create_code(n, characters):
return ''.join(random.choices(characters, k=n))
Printing the codes:
It isn't ideal to join the names and codes a single string as this makes it hard to use them separately later. For this reason, I used a list of tuples to match them as pairs. To print them the for loop has two variables, student
and code
that takes advantage of unpacking and then prints them using the format
function.
Instead of joining the students names with the codes for printing is not an ideal thing to do as it makes it harder to use the names and codes separately later.
Altogether:
import random
import string
def create_code(n, characters):
return ''.join(random.choices(characters, k=n))
students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana",
"Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja",
"Kristjan", "Urban", "Janja", "Lea", "Žana", "Aljaž", "Tilen",
"Matic", "Marija", "Žiga T."]
# It generates the code and puts it in a list
size = 6
chars = string.ascii_uppercase + string.digits
code_list = [create_code(size, chars) for _ in range(len(students))]
# Combines the two lists (students and codes) into a list of tuples
students_plus_codes = list(zip(students, code_list))
for student, code in students_plus_codes:
print('{} - {}'.format(code, student))
New contributor
New contributor
answered 22 mins ago
AlexAlex
1364
1364
New contributor
New contributor
$begingroup$
Thank you, this was really helpful, I would never figure it out on my own :D
$endgroup$
– urban pečoler
9 mins ago
add a comment |
$begingroup$
Thank you, this was really helpful, I would never figure it out on my own :D
$endgroup$
– urban pečoler
9 mins ago
$begingroup$
Thank you, this was really helpful, I would never figure it out on my own :D
$endgroup$
– urban pečoler
9 mins ago
$begingroup$
Thank you, this was really helpful, I would never figure it out on my own :D
$endgroup$
– urban pečoler
9 mins ago
add a comment |
urban pečoler is a new contributor. Be nice, and check out our Code of Conduct.
urban pečoler is a new contributor. Be nice, and check out our Code of Conduct.
urban pečoler is a new contributor. Be nice, and check out our Code of Conduct.
urban pečoler is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212338%2fkey-generating-program-in-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown