亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

生成隨機字符串,直到生成給定的字符串

生成隨機字符串,直到生成給定的字符串

慕村225694 2023-04-25 17:03:36
這是一個生成一些隨機字符串直到生成給定字符串的程序。我無法理解修復部分中的索引的想法else。如果隨機生成的字符與attemptThis[i]中的字符不匹配t[i],我們是否將字符存儲在右側attemptNext?之后當它再次檢查時,只有一個字符存儲在attemptThis?我不知道我問的方式是否正確。我在部分中得到了陳述的想法if。但是令人else:attemptNext += t[i]困惑。帶有示例的 exp 將不勝感激。(來自 gfg 的代碼)import string import random    possibleCharacters = string.ascii_lowercase + string.digits +                      string.ascii_uppercase + ' ., !?;:'  t = "geek"  attemptThis = ''.join(random.choice(possibleCharacters)                                 for i in range(len(t))) attemptNext = ''   completed = Falseiteration = 0  while completed == False:     print(attemptThis)           attemptNext = ''     completed = True          for i in range(len(t)):         if attemptThis[i] != t[i]:             completed = False            attemptNext += random.choice(possibleCharacters)         else:             attemptNext += t[i]                   iteration += 1    attemptThis = attemptNext   print("Target matched after " +      str(iteration) + " iterations") 
查看完整描述

3 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

for循環正在為 構建一個字符串attemptNext。如果 中的字符attemptThis等于 中的相應字符t,則將該字符添加到 的末尾attemptNext。

代碼寫得很奇怪。在代碼中,最好避免在語句的簡單表達式中使用notor 。在這種情況下,它使用了. 通常最好使用相反的 ( ) 并切換每個主體。!=if-else!===


查看完整回答
反對 回復 2023-04-25
?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

import string

import random


s1 = input("enter the string:")

n = len(a)

s2 = None

char = string.digits+string.ascii_uppercase+string.ascii_lowercase


c = 1

while s1!=s2:

    s2= ''.join(random.choice(char) for i in range(n))

    c+=1

    print(c,s2)


查看完整回答
反對 回復 2023-04-25
?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

import random

import string



possibleCharacters = string.ascii_lowercase + string.digits + 

string.ascii_uppercase + ' ., !?;:'


a='zero'

c=1

while a != random:

      b = ''.join(random.choice(possibleCharacters)for i in range(len(a)))

      c=c+1

      print(b)

      if b ==a:

         print(a)

         print("target is matched after",c," attermpts")

         break

#try this short and simple


查看完整回答
反對 回復 2023-04-25
  • 3 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號