I have a question about the following code:
str1 = "Race"
str2 = "Care"
# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
"Race" and "Care" are now anagrams, but how to make an anagram with sentences?
For example:
str1 = "Race is good"
str2 = "Careisgood"
They are also an anagram, but it gives that it is not an anagram. I think it's because of the spaces. How to skip the spaces?
To remove spaces from a string, you can use the replace(" ", "") method.
str1 = "Race is good"
str2 = "Careisgood"
# convert both the strings into lowercase
str1 = str1.lower().replace(" ", "")
str2 = str2.lower().replace(" ", "")
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
Related
Hi Need clarification for python variable stored as wrong value , here is code :
userinput1 = int(input('enter start value\n'))
userinput2 = int(input('enter stop value\n'))
userinput3 = int(input('enter rampup time in seconds\n'))
userinput4 = float(input('enter increments delta \n'))
userinput5 = input('Enter sequence channels: A A A A or D D D D - A Ascend, D Descent , E Exclude \n')
command1 = "RAMP " + str(userinput5) + " " + userinput1 + " " + userinput2 + " " + userinput4 + " " + userinput3
port.write(command1.encode())
#### ERROR #####
command1 = str("RAMP " + str(userinput5) + " " + userinput1 + " " + userinput2 + " " + userinput4 + " " + userinput3)
TypeError: can only concatenate str (not "int") to str
Can you please clarify me correct method to store both type variable input in single variable command. type caste was done already.
You can concate only strings, so before concate all your userinputs you must "convert" them into strings
Example1:
command1 = "RAMP " + " ".join(map(str, [userinput5, userinput1, userinput2, userinput4, userinput3]))
Example2:
command1 = f"RAMP {userinput5} {userinput1} {userinput2} {userinput4} {userinput3}"
So I'm trying to make a guessing game where you guess the name of a song using the first letter of each word, I've got the first word down but the next ones always display an extra '_' Can anyone help?
import random
import re
sWord = 0
correct = 0
lines = ["All Star-Smash Mouth", "Don't Stop Believin'-Journey", "Mr. Brightside-The Killers"]
song = random.choice(lines)
re.split(r"-", song)
sLists = (song.split("-"))
sList = sLists[0]
sLetter = sLists[0][0]
sWords = sList.split(" ")
sWordAmount = len(sWords)
sOutput = ("")
sGeneration = sList[1:]
for char in sGeneration:
if char == " ":
sOutput = sOutput + (" /")
elif char == "'":
sOutput = sOutput + (" '")
elif char == ".":
sOutput = sOutput + (" .")
elif char == ",":
sOutput = sOutput + (" ,")
elif char == "(":
sOutput = sOutput + (" (")
elif char == ")":
sOutput = sOutput + (" )")
else:
for i in range (sWordAmount):
if char == sWords[i][0]:
sOutput = sOutput + char
else:
sOutput = sOutput + (" _")
print (sLetter + sOutput + " By " + sLists[1])
If you need any more info please just ask!
This can be simplified with isalpha() to use an underscore in place of a letter otherwise keep the punctuation.
lines = ["All Star-Smash Mouth", "Don't Stop Believin'-Journey", "Mr. Brightside-The Killers"]
song = random.choice(lines)
name, artist = song.split('-')
s = ''
for word in name.split():
s += word[0] + ' '.join('_' if l.isalpha() else l for l in word[1:]) + ' /'
print(s[:-1] + ' By ' + artist)
What u are missing is a break in the for loop in your else branch.
for i in range(sWordAmount):
if char == sWords[i][0]:
sOutput = sOutput + char
break
else:
sOutput = sOutput + (" _")
Excerpt from Python Tips:
for loops also have an else clause which most of us are unfamiliar with. The else clause executes after the loop completes normally.
So the first letter of a new word inserted an additional _.
How would I replace the spaces in a string with underscores without using the replace function. I was told to also use a accumulation string with some type of loop
string = input("Enter a string")
i = 0
acc = ""
for char in string:
if char == " ":
acc = string + "_"
print(acc)
Try this,
string = input("Enter a string")
i = 0
acc = ""
newlist = [] #create a new list which will be the output
strlist = list(string) #create a list of each character in the input string
for char in strlist:
if char == " ":
newlist.append('_')
newlist.append(char)
acc = ''.join(newlist)
print(acc)
Your code should to be :
string = input("Enter a string")
i = 0
acc = ""
for char in string:
if char == " ":
acc += "_"
else:
acc += char
print(acc)
Try it if without replace.
string = input("Enter a string")
res = ''.join(["_" if i == " " else i for i in string])
print(res)
Another method:
string = input("Enter a string")
res = "_".join(string.split(" "))
print(res)
Your code isn't too far off. You can use an accumulation string like this:
string = input("Enter a string")
acc = ""
for char in string:
if char == " ":
char = "_"
acc += char
print(acc)
If you are allowed to use split, then
s = 'Your string with spaces'
s_ = ''
for word in s.split():
s_ += '_' + word
s_[1:] # 'Your_string_with_spaces'
Otherwise, instead of words, concatenate characters with '_' instead of ' ':
s_ = ''
for char in s:
if char == ' ':
s_ += '_'
else:
s_ += char
Is there another to have exception for capitalizing an entire sentence. I've heard of skipList method, but it didn't work for my code. See below:
string = input('Enter a string: ')
i = 0
tempString = ' '.join(s[0].upper() + s[1:] for s in string.split(' '))
result = ""
for word in tempString.split():
if i == 0:
result = result + word + " "
elif (len(word) <= 2):
result = result + word.lower() + " "
elif (word == "And" or word == "The" or word == "Not"):
result = result + word.lower() + " "
else:
result = result + word + " "
i = i + 1
print ("\n")
print (result)
Sure. Write a complete list of words that should not be title-cased ("and", "the", "or", "not", etc), and title-case everything else.
words = s.split(' ')
result = ' '.join([words[0]] + [w.title() for w in words[1:] if w not in skipwords])
of course this will still miss Mr. Not's last name, which should be capitalized, and some stranger things like "McFinnigan" will be wrong, but language is hard. If you want better than that, you'll probably have to look into NTLK.
You could rewrite this like this
skip_words = {w.capitalize(): w for w in 'a in of or to and for the'.split()}
words = string.title().split()
result = ' '.join(skip_words.get(w, w) for w in words).capitalize()
I'm trying to make a program which reads from two text file line by line and stores the line which you have specified in Name_Input earlier (in variable line and line 2), it then strips off anything which is not a number from the string.
for line in Roster_Inputed:
if Name_Input in line:
line = re.sub('[^0-20]', '', line)
if line == "1":
print(Name_Input + " " + "should have " + line + " " + "ally.")
print " "
else:
print(Name_Input + " " + "should have " + line + " " + "allies.")
print " "
for line2 in Roster_Should_Have:
if Name_Input in line2:
line2 = re.sub('[^0-20]', '', line2)
if line2 == "1":
print(Name_Input + " " + "actually has " + line2 + " " + "ally.")
print " "
else:
print(Name_Input + " " + "actually has " + line2 + " " + "allies.")
print " "
The code reads from two files which contain names and number after a space, it then goes on to compare them to determine what it outputs to the user:
if line == line2:
print "All good"
elif line != line2:
print "Check " + Name_Input + "'s " + "spies"
print " "
What I need it to do is check if the value of "line" is greater than "line2" however I cannot do so because they are strings which contain numbers. Is there a way to temporarily convert them to integers?
You can use chr() and ord() functions:
>>> chr(97)
'a'
>>> ord('a')
97
Hope it helps.
What about calling int?
>>> int('345')
345
Since I have now gotten confirmation that the characters will always be integers and the integers are what you want to compare, I can now say use int():
>>> int('4')
4
In your case, if int(line) > int(line2): should do what you want. Since files usually have new-line characters at the end of each line, you should probably consider using int(line.strip()) and int(line2.strip()).