Logic Error (Pythons): Not getting write output but function works? - python

Inputted:
Akash Das
Expected return:
Das Akash
My code is outputting:
Da Akash
Here's my code:
#a
def firstWord(string):
space = string.find(" ")
first = string[:space]
return first
#b
def removeFirst(string):
space = string.find(" ")
word = string[space + 1:]
return word
print(removeFirst("Akash Das"))
#c
def reversePhrase(string):
reverse = []
numSpace = string.count(" ")
reverse.append(firstWord(string))
while numSpace > 0:
string = removeFirst(string)
reverse.insert(0, firstWord(string))
numSpace -= 1
return reverse
def printReverse(string):
for i in reversePhrase(string):
print (i, end = " ")
#d
def main():
string = input("Enter a phrase. ")
print("Your reversed phrase is", end = " ") #call reverse
printReverse(string)
main()
And here's the output:
>>>
Das
Enter a phrase. Akash Das
Your reversed phrase is Da Akash
>>>

CSZ is right, that is simpler. But your problem is in firstWord. If the string has no spaces, then find will return -1. So space will be -1, and string[:space] will be string[:-1] which is all characters except the last. You just need to check whether you actually found a space:
def firstWord(string):
space = string.find(" ")
first = string[:space] if space >= 0 else string
return first

There is simplier way:
def main():
string = input("Enter a phrase. ")
print("Your reversed phrase is", end = " ")
print(' '.join(reversed(string.split())))
main()
output
Enter a phrase. Akash Das
Your reversed phrase is Das Akash

You are not taking care of the case when find returns -1, it happens when it does not find " ".
Try:
#a
def firstWord(string):
space = string.find(" ")
if space >=0:
first = string[:space]
else:
first = string
return first

Try this :
>>> import re
>>> name = 'Harsha Biyani'
>>> s = re.split('\W',s)
>>> s.reverse()
>>> ' '.join(s)
'Biyani Harsha'

Related

Reversing first and last name - code not printing

I'm trying to reverse names given by the user, for example Herbert von Knass should be written as von Knass, Herbert. I've run into a brick wall now as my code doesn't print anything despite the print command, where am I going wrong? This is my code:
def reverse_name(name):
if len(name) == 2:
first = name.split()[0]
last = name.split()[-1]
print(f"{last}, {first}")
if len(name) == 3:
first = name.split()[0]
last = name.split()[-2] + " " + name.split()[-1]
print(f"{last}, {first}")
if len(name) == 1:
print(f"{name}")
def main():
name = input()
reverse_name(name)
if __name__ == "__main__":
main()
You should check for len(name.split()) in your conditionals as now you're checking the string length and not the word count.
Just change the usage of len(). Some basic change could look like this:
def reverse_name(name):
name_parts = name.split(" ")
reverse_name = name
if len(name_parts) == 2:
first = name_parts[0]
last = name_parts[1]
reverse_name = f"{last}, {first}"
elif len(name_parts) > 2:
first = name.split()[0]
last = name.split()[-2] + " " + name.split()[-1]
reverse_name = f"{last}, {first}"
print(reverse_name)
return reverse_name
You are using len on string which does return its' number of characters, consider that
print(len("Herbert von Knass"))
gives output
17
You are using len() for finding len of full string, I think first you split then find len() like below then it works .
def reverse_name(name):
l=name.split(" ")
name_len=len(l)
if len(name) == 2:
first = name.split()[0]
last = name.split()[-1]
print(f"{last}, {first}")
if len(name) == 3:
first = name.split()[0]
last = name.split()[-2] + " " + name.split()[-1]
print(f"{last}, {first}")
if len(name) == 1:
print(f"{name}")
def main():
name = input()
reverse_name(name)
if __name__ == "__main__":
main()
Adding to the other answers re your conditionals, and using a .split(), suggesting the following code in your function to simplify your conditions:
def reverse_name(name):
name_parts = name.split(" ")
first = name_parts[0]
last = " ".join(name_parts[1:])
print(f"{last}, {first}") if last else print(first)
If a single name is entered, there will not be a last name (last is falsy), so only the first name (first) is printed.

How to convert alphabetical input to numbers and add them together

i'm trying to convert user input into only alphabets, and convert each alphabet into a number(ex. a=1, b=2), then the numbers together. I've been able to complete the first part, but not sure how to do the second part.
import re
name = input("Name: ")
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,
'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
for al in range(len(cleaned_name)):
print(numbers,sep='+')
#if input is jay1joe2, cleaned name will be jayjoe
#after the 'numerology', will print the following below
#10+1+25+10+15+5 = 66
Something like this should work for what you're trying to do.
Note: I'm hardcoding the name here rather than using the user input, so it's easier to test it out if needed.
import string
# name = input("Name: ")
name = 'jay1joe2'
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {char: i for i, char in enumerate(string.ascii_lowercase, start=1)}
result = list(map(numbers.get, cleaned_name))
print(*result, sep='+', end=' ')
print('=', sum(result))
Where the second part (after numbers) could also be written alternatively as follows, using f-strings in 3.6+:
result = [numbers[c] for c in cleaned_name]
print(f"{'+'.join(map(str, result))} = {sum(result)}")
Result:
Your 'cleaned up' name is: jayjoe
10+1+25+10+15+5 = 66
name = input("Name: ")
name = name.lower()
name1 = list(name)
Addition: int = 0
for k in name1:
if ord(k)-96 < 1 or ord(k)-96 > 26:
pass
else:
Addition = Addition + ord(k) - 96
print(Addition)
We can use ascii codes for Numbers and Characters :)

printing the 1st letter of the first 3 words using split() python

This is my code so far for getting the string of the 1st letters of each word in a string but when I return it to main it does not print anything.
def phrases(string):
result2 = ''
for letter in string.split():
result2 += letter[0]
return result2
def main():
string = input('Please enter a string: ')
replacePhrases = input('Do you want to replace phrases? ')
if replacePhrases == 'y' or replacePhrases == 'Y':
result2 = phrases(string)
print(result2)

Removing extra whitespace between words using for loop Python

I need to remove all excess white space and leave one space, between my words while only using if and while statements. and then state the amount of characters that have been removed and the new sentence
edit, it must also work for punctuation included within the sentence.
This is what I have come up with however it leaves me with only the first letter of the sentence i choose as both the number, and the final sentence. can anyone Help.
def cleanupstring(S):
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
else:
lasti = i
result += i
return result
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
Your code should be something like this:
def cleanupstring(S):
counter = 0
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
counter += 1
else:
lasti = i
result += i
return result, counter
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
The counter keeps track of how often you remove a character and your [0] and [1] work now the way you want them to.
This is because outputList is now a tuple, the first value at index 0 is now the result and the second value at index 1 is the counter.

Recreating sentences with numbers

So I have developed a code which lets you recreate a sentence but there is one problem,it cuts out a word! I don't know why so if somebody can correct it that would be brilliant thanks!
Sentence = input("Please enter a sentence: ")
Sen = Sentence.split()
remove=(",")
numbers = input("Enter Numbers(Separating them with a comma for example 1,3,2): ")
newnumbers = ""
for char in numbers:
if char not in remove:
newnumbers = newnumbers + char + " "
numlist = newnumbers.split()
length = len(numlist) -1
del numlist[length]
savenum = " ".join(numlist) -1
file = open("Bruh.txt","w")
file.write(Sentence)
file.write("\n"+savenum)
file.close()
newli = []
for char in numlist:
newnum = (int(char)-1)
newli = newli + [Sen[int(newnum)]]
words = " ".join(newli)
print("Original Sentence: ",Sentence)
print("Recreated Sentence: ", words)
These lignes are responsible for that behaviour :
# length = len(numlist) -1 # <==== comment these lines
# del numlist[length] # <==== comment these lines
Put them in comments, or remove them :
Sentence = input("Please enter a sentence: ")
Sen = Sentence.split()
remove=(",")
numbers = input("Enter Numbers(Separating them with a comma for example 1,3,2): ")
newnumbers = ""
for char in numbers:
if char not in remove:
newnumbers = newnumbers + char + " "
numlist = newnumbers.split()
# length = len(numlist) -1 # <==== comment these lines
# del numlist[length] # <==== comment these lines
savenum = " ".join(numlist) -1
file = open("Bruh.txt","w")
file.write(Sentence)
file.write("\n"+savenum)
file.close()
newli = []
for char in numlist:
newnum = (int(char)-1)
newli = newli + [Sen[int(newnum)]]
words = " ".join(newli)
print("Original Sentence: ",Sentence)
print("Recreated Sentence: ", words)

Categories