I'm trying to write a script that when called prompts a user for a string and it displays the string forward, backward, tests if 2 strings are the same, and tests if a string is a palindrome. I want to test the individual functions for correctness before I input a menu, however the output when calling palindrome() function seems irregular. Any help on why the two statements in the palindrome() function prints this way would be appreciated.
string = raw_input('Enter a string\n>>>')
def forward():
for i in string:
print i,
return str(i)
def backwards():
back = len(string) - 1
while back > 0:
print string[back],
back -= 1
return str(string[back])
def match():
next_string = raw_input('Enter another string')
if string.upper() == next_string.upper():
print 'the strings ', string, ' and ', next_string, ' match.'
else:
print 'the strings ', string, ' and ', next_string, ' do not match.'
def palindrome():
print backwards() # When I don't print this call it only displays the last value in the string
y = forward() # When I do print this call it displays the last value in the string twice
# This is the only way where these calls are opposite
palindrome()
Related
I want to be able to write function that will reverse a phrase such as 'Hello World' into 'World Hello'. So far i can get to:
def reverser():
print('Please input a phrase')
inputphrase=input()
if ' ' in inputphrase:
after this I'm assuming you need to slice the string and then that slice gets stored in a tuple, and at the end the variables will print out.
It would be stored in a list, not a tuple. Here's how you do it in 2 lines:
my_input = input('Your phrase: ')
print(*reversed(my_input.split())) # Python 3
or
print ' '.join(reversed(a.split())) # Python 2
So the function would be:
func = lambda x: reversed(x.split())
which will return a list of reversed words from the phrase if called as follows:
arg = input('Enter a phrase :')
splitted = func(arg)
print(*splitted) # or in Python 2: print ' '.join(splitted)
you can use the reversed built-in
def reverser():
return ' '.join(reversed(input('Please input a phrase:').split()))
the input string is split on whitespace, then passed to reversed, then joined again
For example use it as
>>> print(reverser())
Please input a phrase:hello world how are you
you are how world hello
>>> inputphrase = "Hello World"
>>> parts = inputphrase.split(' ')
>>> parts.reverse()
>>> ' '.join(parts)
'World Hello'
You don't need to test if ' ' in inputphrase: as parts will contain just a single item in that case.
It's a good idea to make your functions have a single purpose. You should have one function for getting the input, and another for reversing it.
Python programming language provides a neat syntax to reverse a
tuple.The syntax is var[::-1] which returns a reverse copy of the var.
Example:
def reverser():
inputphrase = tuple(x.strip() for x in raw_input("Please input a phrase: ").split(' '))
return inputphrase[::-1]
print reverser()
Output:
Please input a phrase: Hello World
('World', 'Hello')
Or you can do it this way.
def reverser():
inputphrase = tuple(x.strip() for x in raw_input("Please input a phrase: ").split(' '))
return tuple(reversed(inputphrase))
print reverser()
Output:
Please input a phrase: Hello World.
('World.', 'Hello')
I have gotten about 80% of this program done but I cannot for the life of me figure out how to replace the vowels with asterisks and print the new string.
Instructions are as follows:
prompt the user to enter his/her first name.
output the number of letters in the name.
print all of the letters in the name separated by a space, all on one line.
print the name in all upper case.
use one slicing to make a new string from the name, but without the first and last letters.
print this new string.
pass the original name to a function named str_func.
inside the str_func function:
replace the vowels in the name with asterisks
return the modified name back to main
back in main, print the string returned by str_func.
My code so far:
def main():
name = input('Enter your first name: ')
print(name)
### print name with spaces in between characters
spaces = ''
for ch in name:
spaces = spaces + ch + ' '
print(spaces[:-1]) # to get rid of space after e
print('name in caps is,',name.upper()) # print name in all caps
print('After chopping the name we get',name[1:4])
print(str_func)
def str_func():
str_func = name.replace('a','*')
return str_func
main()
A friend of mine has helped somewhat stating I have issues with my str_func function:
The function is supposed to take the name as an argument in the main function when you call it.
You don't print it. You call it, something like this:
new_name = str_func(name)
Define str_func() like this. I put in some pseudocode for you.
def str_func(name):
###make a string containing the vowels
###loop through the name
###replace vowel if found with *
### after loop, return the name
Please help!!
This may help you.
import re
def main():
#Using "raw_input" instead of "input"
name = raw_input('Enter your first name: ')
print(name)
### print name with spaces in between characters
spaces = ''
for ch in name:
spaces = spaces + ch + ' '
print(spaces[:-1]) # to get rid of space after e
print('name in caps is,',name.upper()) # print name in all caps
print('After chopping the name we get',name[1:4])
new_name=str_func(name)
print(new_name)
def str_func(value):
#re is regular expression module. It will match string "Guido" and re.IGNORECASE makes it case insensitive.
#When value will Guido, it will be returned as it is.
if re.match(r"Guido",value,re.IGNORECASE):
return value
else:
for x in "aeiou":
value= value.replace(x, '*')
return value
main()
Output
C:\Users\Dinesh Pundkar\Desktop>python a.py
Enter your first name: Guido
Guido
G u i d o
('name in caps is,', 'GUIDO')
('After chopping the name we get', 'uid')
Guido
C:\Users\Dinesh Pundkar\Desktop>python a.py
Enter your first name: Jfalcone
Jfalcone
J f a l c o n e
('name in caps is,', 'JFALCONE')
('After chopping the name we get', 'fal')
Jf*lc*n*
C:\Users\Dinesh Pundkar\Desktop>
Others have provided a solution to your immediate problem but I’ll try to improve the whole code. I don't know what functions you've been introduced to so I might provide both a naive and a pythonic implementation for each steps.
To start with, you did not answered question 2: print the length of the input string. You can either count them manually:
size = 0
for letter in name:
size += 1
print(size)
or use the built-in function len:
size = len(name)
print(size) # or print(len(name)) if you don't need the intermediate variable
You can improve the spacing of your input using the join method of strings:
spaced = ' '.join(name)
print(spaced) # or print(' '.join(name)) if you don't need spaced
You can pass any iterable of strings to join and a string fits.
Your slicing take the second, third and fourth letter of your input. No matter what its length is. You need to either make use of the lenght of the string computed earlier:
sliced = name[1:size-1]
print(sliced)
or use negative numbers in the slice notation to count from the end of the string:
print(name[1:-1])
You're required to write a function and call it to mutate the string. You’ll thus have to call it like:
mutated = str_func(name)
print(mutated)
The function can either iterate over the original string:
def str_func(original):
copy = ''
for letter in original:
if letter in 'auieoy':
copy += '*'
else:
copy += letter
return copy
or use replace:
def str_func(original):
copy = original
for vowel in 'aeuioy':
copy = copy.replace(vowel, '*')
return copy
You can even use translate which can be a better fit in a more general use:
def str_func(original):
from string import maketrans
vowels = 'auieoy'
return original.translate(maketrans(vowels, '*' * len(vowels)))
Assembling all that together:
from string import maketrans
def do_stuff():
name = input('Enter your first name: ')
print('Your input is', name)
print('It\'s length is', len(name))
print('Adding spaces:', ' '.join(name))
print('Capitalizing it:', name.upper())
print('Chopping it:', name[1:-1])
mutated = str_func(name)
print('Removing vowels:', mutated)
def str_func(original):
vowels = 'auieoy'
return original.translate(maketrans(vowels, '*' * len(vowels)))
if __name__ == '__main__':
do_stuff()
test = 'qwertyuiopasdfghjklzxcvbnm'
def changestring(string):
for x in 'aeiou':
string = string.replace(x, '*')
return string
changestring(test)
'qw*rty***p*sdfghjklzxcvbnm'
Is this what you are trying to do?
been trying to wrap entire code in a comment, how do i do that? i tried #, """, with no success, and as a question, is this even possible? i guess im stacking comments on top of other comments but im sure there is a way, im wrapping this code because i want to keep it in one file along with other projects in the same file but i dont want to activate ALL of the code. here's the code i want to wrap as a comment:
"""Artithmetic expressions"""
addition = 1 + 1;
subtraction = 2-1;
miltiplication = 2*2;
division = 5/3; """5/3 = 1"""
"""Variables and Assignment"""
a, b = addition, subtraction; """a = addition, b = subtraction"""
""" prints 2 1"""
print a, b
"""Strings, indexing strings"""
string1 = "hello world hell"
string2 = string1[2]
"""prints 1"""
print string2
"""string extraction"""
string3 = string1[0:5]
""" hello """
print string3
"""Finding"""
stringfind1 = string1.find("hell", 4)
""" prints 12 """
print stringfind1
"""Python 2"""
"""If statement"""
if (3 < 10):
print "true"
else:
print "false"
""" Logical Operators"""
if (3 and 4 < 10):
print "true"
"""may use or"""
"""Loops, ex prints 10 iterations"""
count = 0
while (count < 10):
print 'The count is: ', count
count = count + 1
print "Good bye!"
"""converting between numbers and strings: str(one) converts int to string"""
"""use 'ord' for string --> int, lastly chr = """
one = 1
convert = str(one)
if convert == 1:
print "true"
else:
print "false"
'''returns one character string from number input'''
var1 = chr(65)
print var1
"""splitting strings: () prints all words in a string"""
""" ' ', 1 prints all except the last word?"""
string10 = "fucking hell i hate your life"
var2 = string10.split()
print var2
print string10.split(' ', 1)
"""Looping through strings with 'for' loop, ex prints all chars in 'string10' in new lines"""
for fuckoff in string10:
print 'Current letter :', fuckoff
You can't: Python comments are single line. And docstrings are not comments. However, during development if you need to "switch off" a block of code you can put it into an if False: block.
Eg:
if False:
addition = 1 + 1;
subtraction = 2-1;
miltiplication = 2*2;
division = 5/3;
After seven years of being not right answered here the right answer to the question above:
You can 'switch off' a block of code using appropriate triple quotes.
It will not always be possible (if the code uses both kinds of triple quoted strings), but in the case of code in the question it is possible to use ''' single quoted triple quoted string to achieve what you are after.
Below how it looks like:
'''
"""Artithmetic expressions"""
addition = 1 + 1;
subtraction = 2-1;
miltiplication = 2*2;
division = 5/3; """5/3 = 1"""
"""Variables and Assignment"""
a, b = addition, subtraction; """a = addition, b = subtraction"""
""" prints 2 1"""
print a, b
"""Strings, indexing strings"""
string1 = "hello world hell"
string2 = string1[2]
"""prints 1"""
print string2
"""string extraction"""
string3 = string1[0:5]
""" hello """
print string3
"""Finding"""
stringfind1 = string1.find("hell", 4)
""" prints 12 """
print stringfind1
"""Python 2"""
"""If statement"""
if (3 < 10):
print "true"
else:
print "false"
""" Logical Operators"""
if (3 and 4 < 10):
print "true"
"""may use or"""
"""Loops, ex prints 10 iterations"""
count = 0
while (count < 10):
print 'The count is: ', count
count = count + 1
print "Good bye!"
"""converting between numbers and strings: str(one) converts int to string"""
"""use 'ord' for string --> int, lastly chr = """
one = 1
convert = str(one)
if convert == 1:
print "true"
else:
print "false"
'''returns one character string from number input'''
var1 = chr(65)
print var1
"""splitting strings: () prints all words in a string"""
""" ' ', 1 prints all except the last word?"""
string10 = "fucking hell i hate your life"
var2 = string10.split()
print var2
print string10.split(' ', 1)
"""Looping through strings with 'for' loop, ex prints all chars in 'string10' in new lines"""
for fuckoff in string10:
print 'Current letter :', fuckoff
'''
You can see the evidence that it works as expected from the kind of highlighting of the above piece of code in its code textbox.
I'm trying to write a piece of dynamic programming code that allows me to split a string into valid words (validity is determined by dictionary lookup).
If the string cannot be split into valid words, I want to return ''.
#
Here's the first version of my code:
dictionary = {'cat':1,'hat':1,'in':1}
def memoize(f):
cache = {}
def memoize_function(*args):
if args[0] not in cache:
cache[args[0]] = f(*args) # compute and cache result
return cache[args[0]]
memoize_function.cache = cache
return memoize_function
#memoize
def splitintowords_version1(mystring, word_list):
if len(mystring) < 1:
return word_list
else:
for i in range(len(mystring)):
current_word = mystring[:i+1]
remaining_word = mystring[i+1:]
if current_word in dictionary:
word_list = word_list + current_word + ' '
return splitintowords_version1(remaining_word, word_list)
if i == len(mystring)-1 and current_word not in dictionary:
word_list = ''
return word_list
While strictly speaking, the code works, I know it's not using dynamic programming properly, because the full list of words is being passed even though the string is getting shorter. For example, after calling splitintowords_version1('catinhat'), splitintowords_version1.cache contains the following nonsense:
{'':'cat in hat'}
#
I then rewrote the program:
#memoize
def splitintowords_version2(mystring):
if len(mystring) < 1:
return ''
else:
for i in range(len(mystring)):
current_word = mystring[:i+1]
remaining_word = mystring[i+1:]
if current_word in dictionary:
return current_word + ' ' + splitintowords_version2(remaining_word)
if i == len(mystring)-1 and current_word not in dictionary:
return ''
This version caches values appropriately, but it returns an incorrect value for splitintowords_version2('catinhata'). It returns 'cat in hat ', instead of ''.
I feel like I'm missing just one last piece to get the code right. Can someone help me?
Thanks!
The behaviour you describe is due to your use of recursion in splitintowords_version2.
If the last character of the string cannot be found in the dictionary, it returns ''. This, however, is then added to the previous results (current_word + ' ' + splitintowords_version2(remaining_word)). Therefore, in your example, the returned '' is simply added to the already split "cat in hat" to produce "cat in hat ". Instead, you must check whether the return value of the recursion is empty and return an empty string if needed. However, this is not enough, because splitintowords_version2 also returns '' for an empty input string. You can easily fix this by returning another value for an empty string or if the string could not be split (in the following example, I return ' ' instead of '' for an empty string, because of which you may want to strip of whitespace using string.strip afterwards):
#memoize
def splitintowords_version2(mystring):
if len(mystring) < 1:
return ' '
else:
for i in range(len(mystring)):
current_word = mystring[:i+1]
remaining_word = mystring[i+1:]
if current_word in dictionary:
remaining_split = splitintowords_version2(remaining_word)
if len(remaining_split) > 0:
return current_word + ' ' + remaining_split
else:
return '' # Last part was not in the dictionary.
if i == len(mystring) - 1 and current_word not in dictionary:
return ''
Another way might be to return None if the string could not be split and (if desired) wrapping that into another function that turns None in the end result (not inbetween calls) back into an empty string. To do this, replace '' with None and the check len(remaining_split) > 0 into remaining_split != None.
I have to add str(iterMul(a,b)) to obtain what I want. Is it the proper way to do it?
def iterMul(a,b):
result = 0
while b > 0:
result += a
b -=1
return result
a=int(raw_input('Enter an integer: '))
print('')
b=int(raw_input('Enter an integer: '))
print('')
print (str(a) + ' times '+str(b)+' is equal to '+ str(iterMul(a,b)))
Thanks in advance!
Use string formatting instead:
print '{0} times {1} is equal to {2}'.format(a, b, iterMul(a,b))
String formatting automatically transforms integers to string when interpolating the values, and is more readable than print value, ' some text ', othervalue, ' more text and ', thirdvalue.