hope someone can help please. I was able to get the code but unable to display the characters similar to the input. I capitalized the input for comparison but output should be similar to the input. See image pls. Thanks.
morse_code_dict = {
'A' : '.-',
'B' : '-...',
'C' : '-.-.',
'D' : '-..',
'E' : '.',
'F' : '..-.',
'G' : '--.',
'H' : '....',
'I' : '..',
'J' : '.---',
'K' : '-.-',
'L' : '.-..',
'M' : '--',
'N' : '-.',
'O' : '---',
'P' : '.--.',
'Q' : '--.-',
'R' : '.-.',
'S' : '...',
'T' : '-',
'U' : '..-',
'V' : '...-',
'W' : '.--',
'X' : '-..-',
'Y' : '-.--',
'Z' : '--..',
'0' : '-----',
'1' : '.----',
'2' : '..---',
'3' : '...--',
'4' : '....-',
'5' : '.....',
'6' : '-....',
'7' : '--...',
'8' : '---..',
'9' : '----.',
'.' : '.-.-.-',
',' : '--..--'
}
text = input("Please enter the phrase to send: ")
text2 = ' '.join(text.split()).upper()
for character in text2:
if character in morse_code_dict:
print(f"{character} in morse is {morse_code_dict[character]}")
elif character == ' ':
print("Gap")
else:`enter code here`
print(f"{character} is not available in morse.")
correct output
incorrect output I'm getting
Don't convert the string to uppercase before iterating over it, you can use .upper inside the loop. For example:
text = input("Please enter the phrase to send: ")
morse_code_dict[" "] = "Gap"
for ch in " ".join(text.split()):
if ch.upper() in morse_code_dict:
print(f"{ch} in morse is {morse_code_dict[ch.upper()]}")
else:
print(f"{ch} is not available in morse.")
Prints:
T in morse is -
h in morse is ....
e in morse is .
in morse is Gap
l in morse is .-..
a in morse is .-
s in morse is ...
t in morse is -
in morse is Gap
c in morse is -.-.
h in morse is ....
a in morse is .-
r in morse is .-.
a in morse is .-
c in morse is -.-.
t in morse is -
e in morse is .
r in morse is .-.
in morse is Gap
i in morse is ..
s in morse is ...
in morse is Gap
n in morse is -.
o in morse is ---
t in morse is -
in morse is Gap
p in morse is .--.
r in morse is .-.
e in morse is .
s in morse is ...
e in morse is .
n in morse is -.
t in morse is -
! is not available in morse.
Related
I'm trying to move all consonants in order at the end of a string as soon as the first vowel is encountered.
For example, with this code the goal I would like to achieve is to have the word "atch"
sentence = 'chat'
splitted = sentence.chars
splitted.each do |letter|
%w[a e i o u].include?(letter) ? break : splitted << splitted.shift
end
p splitted.join
But what I finally get is "hatc"
Any suggestions on how to implement this?
You could try:
vowels = %w[a e i o u]
sentence = 'chat'
splitted = sentence.chars
right_part = []
sentence.each_char do |letter|
vowels.include?(letter) ? break : right_part << splitted.shift
end
new_sentence = (splitted + right_part).join
p new_sentence # => "atch"
i am Trying to extract vowels element of each string value and a separate 3,3 array consisting of vowels of respective string value.
INPUT= array ([['teeth', 'cheek', 'chin'],
['eye', 'ear', 'nose'],
['hair', 'leg', 'hand']]
Expected Output= array ([['ee','ee','i'],
['ee','ea','oe'],
['ai','e','a']]
i tried many ways but no result ,PLease help me to get the solution,,
Here you go:
vowels = ('a', 'e', 'i', 'o', 'u')
INPUT=[['teeth', 'cheek', 'chin'],['eye', 'ear', 'nose'], ['hair', 'leg', 'hand']]
out=[]
for list_i in INPUT:
temp_list =[]
for word in list_i:
sel = [w for w in word if w in vowels]
temp_list.append(''.join(sel))
out.append(temp_list)
print(out)
Output: [['ee', 'ee', 'i'], ['ee', 'ea', 'oe'], ['ai', 'e', 'a']]
Code explanation:
[w for w in word if w in vowels]
In this line , the for loop is used to iterate over each letter of a single word (word). If the letter (w) is a vowel, then it is insert in the list (sel).
temp_list.append(''.join(sel))
This line is just a parsing: the list of letters sel is converted to a string and inserted in temp_list. I hope it is more clear now!
I am new to ruby and creating a hangman game. Soo far I have my code comparing the words to the correct word. But I want it to compare letters. So basically, if the secrect word is glue, the user enters G it would come inncorrect, but if the user enters glue it would be correct. I need it to compare letter by letter just like hangman.
Having a bit of trouble with that. I have attached my code below.
secret_word = []
puts "enter a word to be guessed"
secret_word = gets.chomp
guess_letters = []
guess = ""
guess_limit = 3
guess_count = 0
out_of_guesses = false
while guess != secret_word and !out_of_guesses
if guess_count < guess_limit
puts "enter your guess: "
guess = gets.chomp()
guess_letters << guess
guess_count +=1
puts "you have used these letters thus far #{guess_letters.join(", ")}"
else
out_of_guesses = true
end
end
if out_of_guesses
puts "you Lose, the word was #{secret_word}"
else
puts "you win"
end
I'm not sure which hangman rules you are using but here's a rough draft that allows three failed attempts and works with lowercase characters
def guess_word(word, tries)
if tries < 1
puts "You are hanged!"
elsif word.empty?
puts "You guessed it! You are saved from the gallows!"
else
print "Enter character: "
c = STDIN.getc.downcase
STDIN.getc # get rid of newline
if word.index(c).nil?
puts "Ooops, #{c} was wrong!"
guess_word(word, tries - 1)
else
puts "#{c} was correct!"
guess_word(word.sub(/["#{c}"]/, ''), tries)
end
end
end
if __FILE__ == $0
TRIES = 3
print "Enter word to guess: "
word = gets.chomp
guess_word(word.downcase, 3)
end
This is untested..
The rules of the game hangman are given at its Wiki. I've assumed the player trying to guess the word loses when all seven parts of the man on the gallows have been drawn (head, neck, left arm, body, right arm, left leg, right leg).
Helper methods
Draw the man being hanged
First create a hash that can be used to draw the partial or full hangman:
MAN = [" O\n", " |\n", "\\", "|", "/\n", " |\n/", " \\"].
map.each_with_object([""]) { |s,arr| arr << (arr.last + s) }.
each.with_index.with_object({}) { |(s,i),h| h[i] = s }
The keys are the number of incorrect guesses. For example:
puts MAN[2]
O
|
puts MAN[6]
O
|
\|/
|
/
Keep track of the positions of the letters of the word
Next create a hash whose keys are unique letters of the secret word and whose values are arrays of indices of the keys location(s) in the word.
def construct_unknown(word)
word.each_char.with_index.with_object({}) { |(c,i),h| (h[c] ||= []) << i }
end
For example,
unknown = construct_unknown("beetle")
#=> {"b"=>[0], "e"=>[1, 2, 5], "t"=>[3], "l"=>[4]}
We will also create an empty hash for letters whose positions are known:
known = {}
Move guessed letters from the hash unknown to the hash known
If a letter that is guessed is a key of unknown that key and value are moved to known.
def move_unknown_to_known(letter, unknown, known)
known.update(letter=>unknown[letter])
unknown.delete(letter)
end
For example (for unknown and known above),
move_unknown_to_known("e", unknown, known)
unknown #=> {"b"=>[0], "t"=>[3], "l"=>[4]}
known #=> {"e"=>[1, 2, 5]}
See if the guesser has won or lost
We to determine when, after guessing a letter, the player has won or lost, or is to continue:
def win?(word_size, known)
known.values.flatten.sum == word_size
end
def lose?(wrong_guess_count)
wrong_guess_count == HANGMAN.size
end
For example,
win?(word.size, known)
#=> false
lose?(6) #=> false
lose?(7) #=> true
Display the known letters
def display_known(word_size, known)
known.each_with_object('_' * word_size) { |(k,a),s| a.each { |i| s[i] = k } }
end
For example (recall word #=> "beetle"),
puts display_known(word.size, known)
_ee__e
Main method
We are now ready to write the main method.
def hangman
puts "Player 2, please avert your eyes for a moment."
print "Player 1: enter a secret word with at least two letters: "
word = gets.chomp.downcase
unknown = construct_unknown(word)
known = {}
wrong_guess_count = 0
loop do
puts display_known(word.size, known)
puts MAN[wrong_guess_count] if wrong_guess_count > 0
if win?(word.size, known)
puts "You win! You win! Congratulations!"
break
end
if lose?(wrong_guess_count)
puts "Sorry, but you've run out of guesses"
break
end
print "Player 2: enter a letter or your guess of the word: "
guess = gets.chomp.downcase
if guess.size > 1
if guess == word
puts word
puts "You win! You win! Congratulations!"
break
else
puts "Sorry, that's not the word"
wrong_guess_count += 1
end
elsif unknown.key?(guess)
nbr = unknown[guess].size
puts nbr == 1 ? "There is 1 #{guess}" : "There are #{nbr} #{guess}'s"
move_unknown_to_known(guess, unknown, known)
else
puts "Sorry, the word contains no #{guess}'s"
wrong_guess_count += 1
end
end
end
Example
After explaining the rules to the two players and to the audience, the guest host ends by saying, "And don't forget, when guessing a letter or the word it must be expressed as a question...one moment...hold that...I've been told it is not necessary to frame that as a question".
Suppose the word is beetle and the letter guesses are 't', 'i', 'a', 'l', 'r', 's', 't', 'u', 'e', 'beetle'.
hangman
Player 2, please avert your eyes for a moment.
Player 1: enter a secret word with at least two letters: beetle
______
Player 2: enter a letter or your guess of the word: t
There is 1 t
___t__
Player 2: enter a letter or your guess of the word: i
Sorry, the word contains no i's
___t__
O
Player 2: enter a letter or your guess of the word: a
Sorry, the word contains no a's
___t__
O
|
Player 2: enter a letter or your guess of the word: l
There is 1 l
___tl_
O
|
Player 2: enter a letter or your guess of the word: r
Sorry, the word contains no r's
___tl_
O
|
\
Player 2: enter a letter or your guess of the word: s
Sorry, the word contains no s's
___tl_
O
|
\|
Player 2: enter a letter or your guess of the word: t
Sorry, the word contains no t's
___tl_
O
|
\|/
Player 2: enter a letter or your guess of the word: u
Sorry, the word contains no u's
___tl_
O
|
\|/
|
/
Player 2: enter a letter or your guess of the word: e
There are 3 e's
_eetle
O
|
\|/
|
/
Player 2: enter a letter or your guess of the word: beetle
beetle
You win! You win! Congratulations!
I have created an multi dimensional array of empty strings with some row/columns being filled with a letter. Goal is to to fill the adjacent empty slots where the letters are found with that letter. I have most of array filling but I also want to count how many times loops occur to fill array.
This is in python 3 using numpy module only.
It keeps going out of range of index or I get infinite loops.
import numpy as np
letter_spots=[[3,0],[3,4],[1,3]]
A_array= np.zeros([5,5],str)
for lists in letter_spots:
A_array[lists[0]][lists[1]]='A'
for row in range(A_array.shape[0]):
for column in range(A_array.shape[1]):
if A_array[row][column]=='A':
if column+1 < A_array.shape[0]:
if A_array[row][column+1]=='':
A_array[row][column+1]='A'
if column>0:
if A_array[row][column - 1] == '':
A_array[row][column - 1] = 'A'
if row + 1 < A_array.shape[0]:
if A_array[row + 1][column] == '':
A_array[row + 1][column] = 'A'
if row > 0:
if A_array[row - 1][column] == '':
A_array[row - 1][column] = 'A'
Start array:
[['' '' '' '' '']
['' '' '' 'A' '']
['' '' '' '' '']
['A' '' '' '' 'A']
['' '' '' '' '']]
Current End Array:
[['' '' '' 'A' 'A']
['' '' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']]
Expected End Array:
[['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']]
You could just use where
import numpy as np
array1 = np.array([2, 2, 2, 0, 2, 0, 2])
print np.where(array1==0, 1, array1)
I'm trying to count the number of vowels in a string by splitting the string into an array of letters and then map vowel letters to 1 and summing up the array.
def count_vowels(string)
vowels = ['a','e', 'i', 'o', 'u']
return string.split("").map{ |n| vowels.include? n ? 1 : 0}.inject(0,:+)
end
The include? part doesn't correctly return 1 or 0. Any suggestion why this won't fly?
I hacked it to this version which works, but looks kind of foolish:
def count_vowels(string)
vowels = ['a','e', 'i', 'o', 'u']
return string.split("").map{ |n| vowels.include? n}.inject(0) do |mem,x|
x ? mem + 1 : mem
end
end
The reason:
string.split("").map{ |n| vowels.include? n ? 1 : 0}.inject(0,:+)
does not work is because n ? 1 : 0 is evaluated and passed as an argument to include? instead of n. You need to add some parentheses in include?:
string.split("").map{ |n| vowels.include?(n) ? 1 : 0}.inject(0,:+)
You can simply do
def count_vowels(string)
vowels = ['a','e', 'i', 'o', 'u']
string.split(//).select { |x| vowels.include? x }.length
end
You don't need map.
def count_vowels(string)
vowels = %w[a e i o u]
string.chars.select{|n| vowels.include? n}.size
end
In this case you need parantheses for include? method parameter. So
return string.split("").map{ |n| vowels.include?(n) }.inject(0) do |mem,x|
Anyway, your code might be better
VOWELS = %w(a e i o u) # string's array
you don't need return in your method, it's the last statement
string.split("") => string.chars
Note that your method could be so:
def count_vowels(string)
string.count "aeiou"
end