serax
serax

Reputation: 216

how to get just one character form a string contained in a list

I'm trying to compare each character of the string num with each digit of the strings contained in computer_guesses. I must use the numbers as strings. I tried to run this code but the output was:

0
0
0
0
0
0
0
0
0
0

Process finished with exit code 0

Probably i'm just missing the syntax, i'm sure that it can be made without using the function split(word) .

def split(word):
    return [char for char in word]


computer_guesses = ["12345", "67890"]
num = "23648"
correct = 0
for x in range(len(computer_guesses)):
    for y in range(len(computer_guesses[x])):
        if num[y] == split(computer_guesses[x]):
            correct += 1
            print(correct)
        else:
            print(correct)

Upvotes: 1

Views: 81

Answers (3)

Tejas
Tejas

Reputation: 33

This can be one approach for your problem:

def split(num,word):
    num = num
    default = [char for char in num]
    wd = [char for char in word]
    correct = 0
    for m in range(len(wd)):
        if default[m]==wd[m]:
            correct += 1
    return correct


computer_guesses = ["12345", "67890"]
num = "23648"

for x in range(len(computer_guesses)):
    print(split(num, computer_guesses[x]))

Upvotes: 1

ocean
ocean

Reputation: 186

from my vision the wrong part in code it's 'if condition' side

 if num[y] == split(computer_guesses[x]):

i switch it to :

if num[y] == computer_guesses[x][y]:

and the code working , i hope that what you looking for

Upvotes: 0

Hook
Hook

Reputation: 354

You can use enumerate for iterating on iterable with index counting.

computer_guesses = ["12345", "67890"]
num = "23648"
correct = 0
for guess in computer_guesses:
    for idx, digit in enumerate(guess):
        if num[idx] == digit:
            correct += 1
            print(correct)
        else:
            print(correct)

Upvotes: 4

Related Questions