这是Python。我正在尝试编写一个程序,要求用户输入字符串而不使用全局变量。如果字符串只有并排的括号,那么它是偶数。如果它有字母,数字或括号间隔,那么它是不均匀的。例如,()和()()和(()())是偶数,而(()和(pie)和()不是。下面是我到目前为止写的。我的程序继续打印'无限地输入你的字符串,我现在仍然坚持这个问题。
selection = 0
def recursion():
#The line below keeps on repeating infinitely.
myString = str(input("Enter your string: "))
if not myString.replace('()', ''):
print("The string is even.")
else:
print("The string is not even.")
while selection != 3:
selection = int(input("Select an option: "))
#Ignore this.
if selection == 1:
print("Hi")
#This won't work.
elif selection == 2:
def recursion():
recursion()
答案 0 :(得分:0)
这会输出正确的偶数/不均匀答案。
selection = 0
def recursion():
myString = str(raw_input("Enter your string: ")) #Use raw_input or ( ) will be ()
paren = 0
for char in myString:
if char == "(":
paren += 1
elif char == ")":
paren -= 1
else:
print "Not Even"
return
if paren < 0:
print "Not even"
return
if paren != 0:
print "Not even"
return
print "Even"
return
while selection != 3:
selection = int(input("Select an option: "))
#Ignore this.
if selection == 1:
print("Hi")
#This won't work.
elif selection == 2:
recursion() #This isn't a recursive function - naming it as so is...
答案 1 :(得分:0)
除非你使用的是Python 3,否则你应该使用raw_input而不是input,因为输入会以最适合输入的类型返回结果,而raw_input总是返回一个字符串。在Python 3中,输入始终返回一个字符串。另外,为什么要重新定义递归?只需从elif语句中调用它即可。例如:
selection = 0
def recursion():
#The line below keeps on repeating infinitely.
myString = raw_input("Enter your string: ") # No need to convert to string.
if not myString.replace('()', ''):
print("The string is even.")
else:
print("The string is not even.")
while selection != 3:
selection = int(raw_input("Select an option: "))
#Ignore this.
if selection == 1:
print("Hi")
#This won't work.
elif selection == 2:
recursion() # Just call it, as your program already
# recurs because of the if statement.