简体   繁体   English

为什么 Python 3 for loop output 和行为不同?

[英]Why does Python 3 for loop output and behave differently?

This is a password generator, I couldn't really determine where the problem is, but from the output, I could say it's around turnFromAlphabet()这是一个密码生成器,我无法确定问题出在哪里,但从 output 来看,我可以说它在turnFromAlphabet()附近

The function turnFromAlphabet() converts an alphabetical character to its integer value. function turnFromAlphabet()将字母字符转换为其 integer 值。

The random module, I think doesn't do anything here as it just decides whether to convert a character in a string to uppercase or lowercase. random模块,我认为这里没有做任何事情,因为它只是决定将字符串中的字符转换为大写还是小写。 And if a string is in either, when sent or passed to turnFromAlphabet() it is converted to lowercase first to avoid errors but there are still errors.如果一个字符串在其中一个,当发送或传递给turnFromAlphabet()时,它首先被转换为小写以避免错误,但仍然存在错误。

CODE:代码:

import random
import re

#variables
username = "oogisjab" #i defined it already for question purposes
index = 0
upperOrLower = []
finalRes = []
index2a = 0
#make decisions
for x in range(len(username)):
    decision = random.randint(0,1)
    if(decision is 0):
        upperOrLower.append(True)
    else:
        upperOrLower.append(False)
#Apply decisions
for i in range(len(username)):
    if(upperOrLower[index]):
        finalRes.append(username[index].lower())
    else:
        finalRes.append(username[index].upper())
    index+=1
s = ""
#lowkey final
s = s.join(finalRes)

#reset index to 0
index = 0

def enc(that):
    if(that is "a"):
        return "@"
    elif(that is "A"):
        return "4"
    elif(that is "O"):
        return "0" #zero
    elif(that is " "):
        # reduce oof hackedt
        decision2 = random.randint(0,1)
        if(decision2 is 0):
            return "!"
        else:
            return "_"
    elif(that is "E"):
        return "3"
    else:
        return that

secondVal = []

for y in range(len(s)):
    secondVal.append(enc(s[index]))
    index += 1

def turnFromAlphabet(that, index2a):
    alp = "abcdefghijklmnopqrstuvwxyz"
    alp2 = list(alp)
    for x in alp2:
        if(str(that.lower()) == str(x)):
            return index2a+1
            break
        else:
            index2a += 1
    else:
        return "Error: Input is not in the alphabet"    
#real final 
finalOutput = "".join(secondVal)

#calculate some numbers and chars from a substring
amount = len(finalOutput) - round(len(finalOutput)/3)
getSubstr = finalOutput[-(amount):]
index = 0
allFactors = {

};
#loop from substring
for x in range(len(getSubstr)):
    hrhe = re.sub(r'\d', 'a', ''.join(e for e in getSubstr[index] if e.isalnum())).replace(" ", "a").lower()
    print(hrhe)
    #print(str(turnFromAlphabet("a", 0)) + "demo")
    alpInt = turnFromAlphabet(hrhe, 0)
    print(alpInt)
    #get factors
    oneDimensionFactors = []
    for p in range(2,alpInt):
        # if mod 0
        if(alpInt % p) is 0:
            oneDimensionFactors.append(p)
    else:
        oneDimensionFactors.append(1)
    indexP = 0
    for z in oneDimensionFactors:
        allFactors.setdefault("index{0}".format(index), {})["keyNumber"+str(p)] = z

    index+=1
print(allFactors)

I think that you are getting the message "Error: input is not in the alphabet" because your enc() change some of your characters.我认为您收到消息“错误:输入不在字母表中”,因为您的enc()更改了某些字符。 But the characters they becomes (for example '@', '4' or '!') are not in your alp variable defined in turnFromAlphabet() .但是它们变成的字符(例如“@”、“4”或“!”)不在turnFromAlphabet()中定义的alp变量中。 I don't know how you want to fix that.我不知道你想如何解决这个问题。 It's up to you.由你决定。

But I have to say to your code is difficult to understand which may explain why it can be difficult for you to debug or why others may be reluctant to help you.但是我不得不说你的代码很难理解,这可以解释为什么你很难调试或者为什么其他人可能不愿意帮助你。 I tried to make sense of your code by removing code that don't have any impact.我试图通过删除没有任何影响的代码来理解您的代码。 But even in the end I'm not sure I understood what you tried to do.但即使最后我也不确定我是否理解你试图做的事情。 Here's what I understood of your code:这是我对您的代码的理解:

import random
import re

#username = "oogi esjabjbb" 
username = "oogisjab" #i defined it already for question purposes

def transform_case(character):
    character_cases = ('upper', 'lower')
    character_to_return = character.upper() if random.choice(character_cases) == 'upper' else character.lower()
    return character_to_return

username_character_cases_modified = "".join(transform_case(current_character) for current_character in username)

def encode(character_to_encode):
    translation_table = {
        'a' : '@',
        'A' : '4',
        'O' : '0',
        'E' : '3',
    }
    character_translated = translation_table.get(character_to_encode, None)
    if character_translated is None:
        character_translated = character_to_encode
    if character_translated == ' ':
        character_translated = '!' if random.choice((True, False)) else '_'
    return character_translated

final_output = "".join(encode(current_character) for current_character in username_character_cases_modified)

amount = round(len(final_output) / 3)
part_of_final_output = final_output[amount:]

all_factors = {}
for (index, current_character) in enumerate(part_of_final_output):
    hrhe = current_character 
    if not hrhe.isalnum():
        continue
    hrhe = re.sub(r'\d', 'a', hrhe)
    hrhe = hrhe.lower()
    print(hrhe)

    def find_in_alphabet(character, offset):
        alphabet = "abcdefghijklmnopqrstuvwxyz"
        place_found = alphabet.find(character)
        if place_found == -1 or not character:
            raise ValueError("Input is not in the alphabet")
        else:
            place_to_return = place_found + offset + 1
        return place_to_return

    place_in_alphabet = find_in_alphabet(hrhe, 0)
    print(place_in_alphabet)

    def provide_factors(factors_of):
        for x in range(1, int(place_in_alphabet ** 0.5) + 1):
            (quotient, remainder) = divmod(factors_of, x)
            if remainder == 0:
                for current_quotient in (quotient, x):
                    yield current_quotient

    unique_factors = set(provide_factors(place_in_alphabet))
    factors = sorted(unique_factors)

    all_factors.setdefault(f'index{index}', dict())[f'keyNumber{place_in_alphabet}'] = factors 

print(all_factors)

Is near what your wanted to do?接近你想做的事了吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 for 循环的行为与“pop” function 的 while 循环不同? - Why does the for loop behave differently than the while loop for the “pop” function? 为什么这个argparse代码在Python 2和3之间表现不同? - Why does this argparse code behave differently between Python 2 and 3? Python 2-为什么“ with”在嵌入式C代码中表现不同? - python 2 - why does 'with' behave differently in embedded c code? 为什么Python列表的行为会根据声明的不同而有所不同? - Why does Python list of lists behave differently depending on their declaration? 为什么Python **运算符在数组和标量上的行为不同 - Why does the Python ** operator behave differently on arrays and scalars 为什么 Python 对相同的函数(例如“sum”或“and”)表现不同? - Why does Python behave differently for the same function such as 'sum' or 'and'? Python:为什么带有附加参数的方法的行为有所不同? - Python: Why Does a Method Behave Differently with an Added Parameter? 为什么RestrictedPython在与Python 3.6一起使用时表现不同? - Why does RestrictedPython behave differently when used with Python 3.6? 为什么 Popen() function 在 Python 和 PyGTK 中的行为不同? - Why does the Popen() function behave differently in Python and PyGTK? 除非你使用set_event_loop,为什么asyncio子进程与创建的事件循环的行为不同? - Why does asyncio subprocess behave differently with created event loop unless you set_event_loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM