私はPythonのスキルを再学習する初心者です。私はこのコードを調べてきましたが、26回一意のランダム整数を生成する方法がわかりません。誰かが私にそれを説明できますか?
import random
alpha = [" "] * 26
def unique_char():
notfound = True
while (notfound):
possible_pos = random.randint(0,25)
if alpha[possible_pos] != "*":
notfound = False
new_char = alpha[possible_pos]
alpha[possible_pos] = "*"
return new_char
def main():
for i in range(26):
alpha[i] = chr(i+65) #genderates a-z
print(alpha)
for count in range(26):
good_char = unique_char()
print(good_char, end="")
print()
main()
私はいくつかのコメントでコードを説明しようとします
ただし、最初に、プログラムの縮小版を紹介します。
import random
import string
alpha = list(string.ascii_uppercase) # generate a list from the alphabet iterator
print(alpha) # print the alphabet
random.shuffle(alpha) # shuffle the alphabet
print(''.join(alpha)) # print the shuffled alphabet
そしてここにあなたのプログラムの説明があります
# This program outputs the chars from A-Z in a random order
import random # import random used to generate random numbers
alpha = [" "] * 26 # multiply the ' ' string 26 times results in a array with 26 spaces [' ', ' ', .....]
# This array will later be set to the alphabet
def unique_char():
# This function picks char in a fancy way from alpha
# Tut it will never return a char i has previosly return
# So all piked chars are only picked ones
notfound = True # set a boolen to true (this is called flag)
while (notfound): # while the flag notfount is true repeat that step
possible_pos = random.randint(0,25) # generate a random number between 0 and 25
# alpha[possible_pos] will return the a char in the alpha array on the random position from the previos line
if alpha[possible_pos] != "*": # set notfound to false(exit the loop) if the array alpha hasn't a '*' in alpha[possible_pos]
notfound = False
new_char = alpha[possible_pos] # set new char to alpha[possible_pos](explaint previosly)
alpha[possible_pos] = "*" # and set alpha[possible_pos](explaint previosly) to '*'
# ↑ That means if the random number is again the same number we will exit the loop
return new_char # return the latest char from alpha
def main():
for i in range(26):
alpha[i] = chr(i+65) #genderates a-z
# chr converts a asci number to a char
# fill alpha with 'A-Z'
print(alpha) # print the lphabet
for count in range(26): # generate 26 unique chars that means every char is generated one time (time inefficiently)
good_char = unique_char() # generate the random char
print(good_char, end="") # print the random char without newline -> end=""
print() # print an empty string
main() # call the main function
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加