while bulls != 4:
userinput = list(map(int,input().split()))
for i in range(len(userinput)):
if userinput[i] == Guess[i]:
bulls += 1
So code is working for example when guess (it's a list) [1,2,3,4] and user input is 1 2 3 4.
Code is working only when user gives input with space (because of map(.split())) can you show me how can it work with an input without space character?
Because a string is an iterable, you can iterate over its characters.
If you want to split the user input after every digit, this can be done easily:
userinput = [int(c) for c in input()]
or to keep your original approach:
userinput = list(map(int, input()))
Both attempts result in userinput being the list of integers [1, 2, 3, 4, 5] if user entered 12345.
If you want it to work with or without spaces:
[int(c) for c in input() if c != ' ']
or:
list(map(int, filter(lambda c: c != ' ', input())))
You can iterate directly over the string, as that will yield each character individually. A string is an iterable of individual characters.
FWIW, you could write your code pretty succinctly like so:
for i, n in enumerate(int(c) for c in input() if c != ' '):
if n == guess[i]:
bulls += 1
See enumerate.
Or something like:
userinput = (int(c) for c in input() if c != ' ')
bulls += sum(n == g for n, g in zip(userinput, guess))
Related
Write a program that asks the user to enter two strings of the same length. The program should then check to see if the strings are of the same length. If they are not, the program should print an appropriate message and exit. If they are of the same length, the program should print the alternate characters of the two strings. For example, if the user enters abcde and ABCDE the program should print out AaBbCcDdEe.
I have tried this but it does not work
t1 = input('Enter a string: ')
t2 = input('Enter another string: ')
run = True
while run:
if (len(t1)!=len(t2)):
run = False
elif (len(t1)==len(t2)):
for i in range(len(t1),len(t2)):
if (i%2 ==0):
t1[i]+=t2[i]
print(t1)
Something like this, it is possible to be more clever with building the string, but this maybe is the easiest to understand.
a = input("string a:")
b = input("string b:")
s= ""
if len(a) != len(b):
print("Not same length!")
else:
for i,k in zip(a,b):
s += i+k
print(s)
Here without rebuilding the string each time:
s= []
if len(a) != len(b):
print("Not same length!")
else:
for i,k in zip(a,b):
s.append(i)
s.append(k)
print("".join(s))
I want to multiply letter of string by digits of number. For example for a word "number" and number "123"
output would be "nuummmbeerrr". How do I create a function that does this? My code is not usefull, because it doesn't work.
I have only this
def new_word(s):
b=""
for i in range(len(s)):
if i % 2 == 0:
b = b + s[i] * int(s[i+1])
return b
for new_word('a3n5z1') output is aaannnnnz .
Using list comprehension and without itertools:
number = 123
word = "number"
new_word = "".join([character*n for (n, character) in zip(([int(c) for c in str(number)]*len(str(number)))[0:len(word)], word)])
print(new_word)
# > 'nuummmbeerrr'
What it does (with more details) is the following:
number = 123
word = "number"
# the first trick is to link each character in the word to the number that we want
# for this, we multiply the number as a string and split it so that we get a list...
# ... with length equal to the length of the word
numbers_to_characters = ([int(c) for c in str(number)]*len(str(number)))[0:len(word)]
print(numbers_to_characters)
# > [1, 2, 3, 1, 2, 3]
# then, we initialize an empty list to contain the repeated characters of the new word
repeated_characters_as_list = []
# we loop over each number in numbers_to_letters and each character in the word
for (n, character) in zip(numbers_to_characters, word):
repeated_characters_as_list.append(character*n)
print(repeated_characters_as_list)
# > ['n', 'uu', 'mmm', 'b', 'ee', 'rrr']
new_word = "".join(repeated_characters_as_list)
print(new_word)
# > 'nuummmbeerrr'
This will solve your issue, feel free to modify it to fit your needs.
from itertools import cycle
numbers = cycle("123")
word = "number"
output = []
for letter in word:
output += [letter for _ in range(int(next(numbers)))]
string_output = ''.join(output)
EDIT:
Since you're a beginner This will be easier to understand for you, even though I suggest reading up on the itertools module since its the right tool for this kind of stuff.
number = "123"
word = "number"
output = []
i = 0
for letter in word:
if(i == len(number)):
i = 0
output += [letter for _ in range(int(number[i]))]
i += 1
string_output = ''.join(output)
print(string_output)
you can use zip to match each digit to its respective char in the word (using itertools.cycle for the case the word is longer), then just multiply the char by that digit, and finally join to a single string.
try this:
from itertools import cycle
word = "number"
number = 123
number_digits = [int(d) for d in str(number)]
result = "".join(letter*num for letter,num in zip(word,cycle(number_digits)))
print(result)
Output:
nuummmbeerrr
I want to delete adjacent repeating characters in a string in Python 3. For ex if the input is AABBC the output is ABC or if the input is AAABBBCC the output is ABC. I made two attempts to solve this problem.
Attempt #1
string = input()
for i in range (len(string) - 1):
if string[i] == string[i+1]:
string.replace(string[i],"")
print(string)
The above code returns the same string that is entered. If I enter AABBC it simply returns the same string. Not knowing what I was doing wrong, I tried another attempt.
Attempt #2
string = input()
new = []
for i in string:
new.append(i)
for i in range (len(new) - 3):
"""in the above line, if I set the range to (len(new)-2), it gives me an
error saying "list index out of range"."""
if new[i] == new[i+1]:
new.pop(i)
print(new)
The above code works for double repeating characters, but fails when there are 3 or more repeating characters. If I input AABBC it returns the list ['A','B','C'] which is perfectly fine, but with the input AAABBCC it returns ['A', 'A', 'B', 'C'].
Using Regex:
import re
s = ["AABBC", "AAABBBCC"]
for i in s:
print( re.sub(r"(.)\1+", r"\1", i) )
Or:
s = ["AABBC", "AAABBBCC"]
for i in s:
temp = []
for j in i:
if not temp:
temp.append(j)
else:
if temp[-1] != j:
temp.append(j)
print("".join(temp))
Output:
ABC
ABC
You can use itertools to group the characters like,
>>> import itertools
>>> [x[0] for x in itertools.groupby('AABBCC')]
['A', 'B', 'C']
string = 'AAABBBCC'
result = ''
for letter in string:
if len(result) > 0:
if result[-1] != letter: # [-1] is the last letter
result += letter
else:
result = letter # the first letter will always be included
print(result) # ABC
That is, only append the letter if it is not already at the end of the result string.
An easy to understand short solution :
mot = 'AABBBCC'
a = [mot[0]] + [mot[i] if mot[i]!=mot[i-1] else '' for i in range(1, len(mot))]
>>> ['A', '', 'B', '', '', 'C', '']
result = ''
for lettre in a:
result += lettre
result
>>> 'ABC'
You first create a list of the letters which respects a certain condition, then you convert this list into a string. This algorithm can be used for many different conditions.
Note that you don't need to import any new library.
So I'm indexing letters in a list. If I put the letters of "h" "e" "l" "l" "o" in the list and I try to get the index of them, it returns
0
1
2
2
4.
How do I get the second "l" to show up as 3?
def gameboard():
print("_ " * len(secretword))
for i in secretword:
gameboardindexes.append("_ ")
def letterindexes():
for i in secretword:
wordindexes.append(i)
def guessLetter():
guess = input("Please enter one letter: ")
for i in wordindexes:
if guess == i:
x = wordindexes.index(i)
print(x)
secretword = input("Please enter word:")
wordindexes = []
gameboardindexes = []
wrongletters = []
letterindexes()
gameboard()
guessLetter()
For Python, the index method has the following parameters:
str.index(sub[, start[, end]] )
There is no way to control which index you are returned, as it will always return the first index possible. In this case, the first l is returned, so 2.
If you would like to solve this issue, however, you can maintain the most recent l that was encountered. You can use a dictionary to store this value, and for the next call, you can pass this as the start argument.
Essentially, maintain a dictionary as follows, with all the other global variables:
most_recent = {}
Every time after running:
print(x)
Add this line:
most_recent[i] = x+1
Then, edit this line:
x = wordindexes.index(i)
To this:
x = 0
try:
last = most_recent[i]
x = wordindexes.index(i, last)
except:
x = wordindexes.index(i)
This essentially checks if the letter has been found before, or not, and then edits search range to not include it again. This will not overwrite the word, but will guess every l (or any repeating letter) one at a time.
You will get 0 1 2 3 4 as intended.
The list index function returns the index of the first occurrence. A workaround for this could be to create a string from the array and use the rindex() function. The rindex() function returns the last index where the substring was found.
hello = ['h', 'e', 'l', 'l', 'o']
''.join(char for char in hello).rindex('l')
Another possibility would be to provide the list index function a start index one past the first found index.
hello = ['h', 'e', 'l', 'l', 'o']
hello.index('l', hello.index('l') + 1)
You could have guessLetter() overwrite any letter for which it returns an index:
def guessLetter():
guess = input("Please enter one letter: ")
for letter in wordindexes:
if guess == letter:
index = wordindexes.index(letter)
wordindexes[index] = 0
return index
return -1 # not found
TEST
>>> guessLetter()
Please enter one letter: l
2
>>> guessLetter()
Please enter one letter: l
3
>>> guessLetter()
Please enter one letter: l
-1
>>>
Use str.join with str.rindex:
print(''.join(yourList).rindex('l'))
Or use enumerate:
print([i for i,v in enumerate(yourList) if v == 'l'][-1])
Both output:
3
I'm a Python beginner and would like to know how to split a user input at pair and at space and add it to a list.
E.g:
user = input('A1 KW')
user.split(" " ) # split on space
Then I'd like to print the input on index 0 what should be A1 and also print the alphabet and number/alphabet of each index.
E.g:
input[0] = A1
alphabet = A
number = 1
input[1] = KW
alphabet1 = K
alphabet2 = W
Then add it to a list.
list = ['A1, KW']
I hope you guys know what I mean.
Basic String manipulation.
There are lots of tutorials out there on that, go look them up.
From your question, it looks like you would want to use the isalpha() builtin.
Here's a function that should do the string manipulation like you said.
def pair(user):
user=user.split(" ")
for x in range(len(user)):
print ("\nPair part "+str(x)+":")
for char in user[x]:
if char.isalpha():
print ("Alphabet: "+char)
else:
print ("Number: "+char)
then you can call it with:
print("example pair was 'A1 KW'")
pair("A1 KW")
pair(input("\nEnter your pair: "))
output:
example pair was 'A1 KW'
Pair part 0:
Alphabet: A
Number: 1
Pair part 1:
Alphabet: K
Alphabet: W
Enter your pair: AB 3F
Pair part 0:
Alphabet: A
Alphabet: B
Pair part 1:
Number: 3
Alphabet: F