简体   繁体   English

Python-字符和索引匹配

[英]Python - char and index match

I can't figure out what I'm doing wrong. 我不知道我在做什么错。 I want a simple way of matching the char and position in two strings. 我想要一种在两个字符串中匹配char和position的简单方法。 The error is that it's not recognizing what I'm intending as an index. 错误是它无法识别我打算作为索引的内容。

I'm new at this. 我是新来的。 :) I think experts can understand what I'm starting to try to do here. :)我认为专家可以理解我在这里开始尝试做的事情。 I don't want to copy a complicated bulls and cows code, I'm just trying to do this early part. 我不想复制复杂的牛市和牛市代码,我只是想尽早完成这一部分。 Please advise: 请指教:

def bulls_and_cows(real, guess):
    bulls = 0
    cows = 0
    for i in guess:
        if i == i in real:
            if i[x] == i[x]
            bulls = bulls + 1
            print ("Bullseye!")
            print(bulls)
    else:
        print("No")

bulls_and_cows("like", "brig")

In the line 在行中

for i in guess:

the variable i will be each char in the string guess, instead of index. 变量i将是字符串猜测中的每个字符,而不是索引。 If you intend to get both indices and chars, you need to use enumerate() . 如果打算同时获取索引和字符,则需要使用enumerate()

Next I'm not sure what you intend to compare in 接下来,我不确定您打算比较什么

if i == i in real:

Also, x is not initialized anywhere before this line: 同样,x在此行之前的任何位置均未初始化:

if i[x] == i[x]

You can use a lot of handy utils, most of all zip : 您可以使用很多方便的工具,尤其是zip

from collections import Counter
def bulls_and_cows(real, guess):
    # count bulls
    bulls = sum(x == y for x, y in zip(real, guess))

    # get letter counts separately for each string
    c1, c2 = map(Counter, (real, guess))

    # cows: sum min count for any letter, subtract bulls
    cows = sum(min(c1[x], c2[x]) for x in set(real) | set(guess)) - bulls

    print(bulls, cows)

For pure explicit iterative bulls counting: 对于纯粹的显式迭代多头计数:

def bulls_and_cows(real, guess):
    bulls = 0
    for r, g in zip(real, guess):
        if r == g:
            bulls += 1
    print(bulls)

I guess you are trying to do this: 我想您正在尝试这样做:

def bulls_and_cows(real, guess):
    bulls = 0
    cows = 0
    for i in range(len(guess)):
        if guess[i] == real[i]:
            bulls = bulls + 1
            print ("Bullseye!")
        else:
            cows += 1

    if bulls == 0:
        print("No")
    else:
        print("Bulls: " , bulls, " Cows: ", cows)

bulls_and_cows("like", "brig")

Please let me know if it is not what you intend so I can help you more. 如果不是您想要的,请告诉我,以便我能为您提供更多帮助。 This code Prints "Bullseye!" 此代码打印“ Bullseye!” for every time a char in guess matches the char in real in the same place. 每次猜测的char都在同一位置匹配真实的char。 and prints "No" if they do not match. 如果不匹配,则打印“否”。 I couldn't understand why you needed a cows = 0 at first because you never used it in your code. 我不明白为什么一开始需要牛= 0,因为您从未在代码中使用它。

Also please notice that indention is very important in python. 还请注意,缩进在python中非常重要。 So in your code at least one of the lines after the if should be indented. 因此,在您的代码中,if后面的至少一行应缩进。 Also, in this code, I assumed that the length of the two input strings is the same. 另外,在此代码中,我假设两个输入字符串的长度相同。 If not you may encounter out of bound error. 如果没有,您可能会遇到错误。 To prevent such errors it is better to compare the length of the two strings at the start of the function: 为防止此类错误,最好在函数开始时比较两个字符串的长度:

if len(real) != len(guess):
    print("The strings Length does not match!")
    return

If you insist to compare the strings even though they are of different lengths, another option to prevent this error is to change the code like this: 如果您坚持要比较字符串,即使它们的长度不同,则防止此错误的另一种方法是更改​​代码,如下所示:

def bulls_and_cows(real, guess):
    bulls = 0
    cows = 0
    real_len = len(real)
    guess_len = len(guess)
    for i in range(real_len):
        if i < guess_len and guess[i] == real[i]:
            bulls = bulls + 1
            print ("Bullseye!")
        else:
            cows += 1

    if bulls == 0:
        print("No")
    else:
        print("Bulls: " , bulls, " Cows: ", cows)

Hopefully the code below isn't too advanced for you. 希望下面的代码对您来说不太高级。 It uses the very handy enumerate function which lets us loop over a string and get both the index and the character. 它使用了非常方便的enumerate函数,该函数使我们可以遍历字符串并获取索引和字符。 Actually, enumerate is a general function that can be used on any for loop when we need to get the item and its index. 实际上, enumerate是一个通用函数,当我们需要获取项目及其索引时,可以在任何for循环上使用。

def bulls_and_cows(real, guess):
    bulls = cows = 0
    for i, c in enumerate(guess):
        if c in real:
            # We have a match!
            if real[i] == c:
                # And it's in the correct position
                bulls += 1
            else:
                cows += 1

    print('Bulls', bulls, 'Cows', cows)

bulls_and_cows("like", "brig")

output 输出

Bulls 0 Cows 1

My code doesn't produce the exact output you want, but I'm sure you can figure that out. 我的代码无法产生您想要的确切输出,但是我敢肯定您可以弄清楚。 ;) ;)


If you can't quite understand how my code works, try putting 如果您不太了解我的代码的工作原理,请尝试将

print(i, c)

as the first line in the for i, c in enumerate(guess): block, before the if c in real: line. 作为for i, c in enumerate(guess):的第一行, for i, c in enumerate(guess):块中的if c in real:行中的if c in real:之前。

My teacher pointed out I should start with the "cows" section, and then for those results, narrow it to bulls. 我的老师指出,我应该从“母牛”部分开始,然后针对这些结果,将其范围缩小到多头。 This is the working answer i put together. 这是我整理的工作答案。 I appreciate the suggestions! 我感谢这些建议!

def bulls_and_cows(real, guess):
    bulls = 0
    cows = 0
    for i in guess:
        if i == i in real:
            cows = cows+1
            if guess.index(i) == real.index(i):
                cows = cows -1
                bulls = bulls +1
    print("Bulls: " + str(bulls))
    print("Cows: " + str(cows))

You can also go with a 1 liner for each of the cases: 对于每种情况,您还可以使用1个衬板:

real = "like"
guess = "brig"
print("Bulls", sum(1 for x in zip(real, guess) if x[0] == x[1])) # Bulls 0
print("Cows", sum(1 for x in real if x in guess and real.index(x) != guess.index(x))) # Cows 1

The first one "zips" the word and counts the tuples with similar characters. 第一个“压缩”单词并计算具有相似字符的元组。 The second, looks for characters that are in both words but positioned in different indexes. 第二个,查找两个单词中但位于不同索引中的字符。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM